@usine/server 0.2.0 → 0.3.0

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 (146) hide show
  1. package/README.md +37 -21
  2. package/dist/backend.d.ts +28 -5
  3. package/dist/backend.d.ts.map +1 -1
  4. package/dist/backend.js +40 -12
  5. package/dist/backend.js.map +1 -1
  6. package/dist/backup.d.ts +6 -3
  7. package/dist/backup.d.ts.map +1 -1
  8. package/dist/backup.js +25 -5
  9. package/dist/backup.js.map +1 -1
  10. package/dist/cli.d.ts +20 -7
  11. package/dist/cli.d.ts.map +1 -1
  12. package/dist/cli.js +65 -15
  13. package/dist/cli.js.map +1 -1
  14. package/dist/export-run.d.ts +1 -1
  15. package/dist/export-run.d.ts.map +1 -1
  16. package/dist/export-run.js +3 -3
  17. package/dist/export-run.js.map +1 -1
  18. package/dist/failure-message.d.ts +13 -0
  19. package/dist/failure-message.d.ts.map +1 -0
  20. package/dist/failure-message.js +58 -0
  21. package/dist/failure-message.js.map +1 -0
  22. package/dist/http.d.ts.map +1 -1
  23. package/dist/http.js +69 -23
  24. package/dist/http.js.map +1 -1
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/instance-lock.d.ts +23 -0
  30. package/dist/instance-lock.d.ts.map +1 -0
  31. package/dist/instance-lock.js +58 -0
  32. package/dist/instance-lock.js.map +1 -0
  33. package/dist/main.js +4 -10
  34. package/dist/main.js.map +1 -1
  35. package/dist/reload-signal.d.ts +8 -0
  36. package/dist/reload-signal.d.ts.map +1 -0
  37. package/dist/reload-signal.js +21 -0
  38. package/dist/reload-signal.js.map +1 -0
  39. package/dist/shutdown.d.ts +5 -2
  40. package/dist/shutdown.d.ts.map +1 -1
  41. package/dist/shutdown.js +11 -5
  42. package/dist/shutdown.js.map +1 -1
  43. package/dist/up.d.ts +1 -1
  44. package/dist/up.d.ts.map +1 -1
  45. package/dist/up.js +29 -16
  46. package/dist/up.js.map +1 -1
  47. package/dist/web/assets/DialogTitle-DrHlwOSg.js +1 -0
  48. package/dist/web/assets/_agent-cBqm12lE.js +1 -0
  49. package/dist/web/assets/_loop-kf1h3qkS.js +1 -0
  50. package/dist/web/assets/_name-CKWcxUh0.js +2 -0
  51. package/dist/web/assets/_name-DCEDRHnF.js +1 -0
  52. package/dist/web/assets/_name-sJkGyn7O.js +1 -0
  53. package/dist/web/assets/_number-DbgcVg1N.js +1 -0
  54. package/dist/web/assets/_run-DqslP0y6.js +8 -0
  55. package/dist/web/assets/_worker-CH4UoJT_.js +1 -0
  56. package/dist/web/assets/action-DYT048Jm.js +1 -0
  57. package/dist/web/assets/agents-DIZolb0U.js +1 -0
  58. package/dist/web/assets/agents-DMhSMb9O.js +1 -0
  59. package/dist/web/assets/button-C4yvcSko.js +2 -0
  60. package/dist/web/assets/copy-BM1l6IGB.js +1 -0
  61. package/dist/web/assets/core-BUmsKffF.js +12 -0
  62. package/dist/web/assets/engine-javascript-D-6se_EF.js +141 -0
  63. package/dist/web/assets/error-alert-BrI00JbQ.js +1 -0
  64. package/dist/web/assets/file-error-C--_cWuj.js +1 -0
  65. package/dist/web/assets/index-BljdfRBm.js +10 -0
  66. package/dist/web/assets/index-YKcAk3No.css +2 -0
  67. package/dist/web/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
  68. package/dist/web/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
  69. package/dist/web/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
  70. package/dist/web/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
  71. package/dist/web/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
  72. package/dist/web/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
  73. package/dist/web/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
  74. package/dist/web/assets/item-rBBCTV8x.js +1 -0
  75. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  76. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  77. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  78. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  79. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  80. package/dist/web/assets/label-badge-ohqvZnY7.js +1 -0
  81. package/dist/web/assets/loops-CXM3f90o.js +1 -0
  82. package/dist/web/assets/loops-DWLXyUPN.js +1 -0
  83. package/dist/web/assets/markdown-D07-JkYB.js +29 -0
  84. package/dist/web/assets/moves-RiWgdCxQ.js +5 -0
  85. package/dist/web/assets/operator-copy-DsM7LJx6.js +301 -0
  86. package/dist/web/assets/outcome-YiIf6xbJ.js +5 -0
  87. package/dist/web/assets/project-not-found-CQVclgb0.js +1 -0
  88. package/dist/web/assets/query-DWN8IHdt.js +1 -0
  89. package/dist/web/assets/repositories-CoTEmYmS.js +1 -0
  90. package/dist/web/assets/repositories-Cq7zGzNb.js +1 -0
  91. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  92. package/dist/web/assets/route-CE9U74a9.js +1 -0
  93. package/dist/web/assets/route-DNH2EwHP.js +1 -0
  94. package/dist/web/assets/routes-XAUJJqfj.js +1 -0
  95. package/dist/web/assets/run-again-DxjFCuNu.js +1 -0
  96. package/dist/web/assets/run-drawer-CyjxH5mf.js +1 -0
  97. package/dist/web/assets/section-BBnBOk-U.js +1 -0
  98. package/dist/web/assets/section-Cm-j3zHs.js +1 -0
  99. package/dist/web/assets/section-DkBCDv4D.js +1 -0
  100. package/dist/web/assets/settings-iZf872O5.js +1 -0
  101. package/dist/web/assets/status-badge-CNlyvwWL.js +1 -0
  102. package/dist/web/assets/table-B6NH8hTW.js +1 -0
  103. package/dist/web/assets/tasks-DhLW-1gg.js +1 -0
  104. package/dist/web/assets/usage-DPUTTLGs.js +1 -0
  105. package/dist/web/assets/use-now-CcFZyFvf.js +1 -0
  106. package/dist/web/assets/useNavigate-lXd3v3E0.js +1 -0
  107. package/dist/web/assets/usePositioner-WErrA3Ah.js +1 -0
  108. package/dist/web/assets/useScrollLock-BOb01sL8.js +1 -0
  109. package/dist/web/assets/useTriggerFocusGuards-B0FItfLc.js +1 -0
  110. package/dist/web/assets/utils-BEQKLGgi.js +1 -0
  111. package/dist/web/assets/with-selector-NsM_5qXG.js +1 -0
  112. package/dist/web/assets/workers-BgocBXT9.js +1 -0
  113. package/dist/web/assets/workers-Dw2uHY0Y.js +1 -0
  114. package/dist/web/index.html +13 -10
  115. package/package.json +13 -9
  116. package/dist/web/assets/_name-BHFMXhWe.js +0 -1
  117. package/dist/web/assets/_name-Cz2YmpSb.js +0 -1
  118. package/dist/web/assets/_name-D1NH8oUE.js +0 -6
  119. package/dist/web/assets/badge-BQobsECb.js +0 -142
  120. package/dist/web/assets/button-BoOukj77.js +0 -1
  121. package/dist/web/assets/core-Cg4Mi2IQ.js +0 -12
  122. package/dist/web/assets/empty-DbVYU7bi.js +0 -1
  123. package/dist/web/assets/engine-javascript-h-x4hGa4.js +0 -141
  124. package/dist/web/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  125. package/dist/web/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  126. package/dist/web/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  127. package/dist/web/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  128. package/dist/web/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  129. package/dist/web/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  130. package/dist/web/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  131. package/dist/web/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  132. package/dist/web/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  133. package/dist/web/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  134. package/dist/web/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  135. package/dist/web/assets/index-CJ-Nk5DM.js +0 -10
  136. package/dist/web/assets/index-DxGXwXIP.css +0 -2
  137. package/dist/web/assets/loops-huxrr83I.js +0 -1
  138. package/dist/web/assets/operator-copy-BDZ_fazz.js +0 -1
  139. package/dist/web/assets/overview-DTxvvQ4b.js +0 -1
  140. package/dist/web/assets/rolldown-runtime-hePW80VL.js +0 -1
  141. package/dist/web/assets/routes-CbvAb2gn.js +0 -1
  142. package/dist/web/assets/run-drawer-3blrdBMZ.js +0 -157
  143. package/dist/web/assets/status-badge-BTkHx8qb.js +0 -1
  144. package/dist/web/assets/table-B8cLYNvq.js +0 -1
  145. package/dist/web/assets/useCompositeItem-CuLyiETJ.js +0 -1
  146. package/dist/web/assets/with-selector-N6m4X0X_.js +0 -1
@@ -0,0 +1,301 @@
1
+ import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{lt as t,ut as n}from"./button-C4yvcSko.js";var r=e(n(),1),i=t(),a=r.createContext(void 0),o=e=>{let t=r.useContext(a);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},s=({client:e,children:t})=>(r.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,i.jsx)(a.Provider,{value:e,children:t})),c={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},l=new class{#e=c;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function u(e){setTimeout(e,0)}var d=typeof window>`u`||`Deno`in globalThis;function f(){}function p(e,t){return typeof e==`function`?e(t):e}function m(e){return typeof e==`number`&&e>=0&&e!==1/0}function h(e,t){return Math.max(e+(t||0)-Date.now(),0)}function g(e,t){return typeof e==`function`?e(t):e}function _(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==y(o,t.options))return!1}else if(!b(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function v(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(ee(t.options.mutationKey)!==ee(a))return!1}else if(!b(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function y(e,t){return(t?.queryKeyHashFn||ee)(e)}function ee(e){return JSON.stringify(e,(e,t)=>ae(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function b(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!b(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!b(e[r],t[r]))return!1;return!0}return!1}var te=Object.prototype.hasOwnProperty;function ne(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ie(e)&&ie(t);if(!r&&!(ae(e)&&ae(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:te.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=ne(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function re(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function ie(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ae(e){if(!oe(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!oe(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function oe(e){return Object.prototype.toString.call(e)===`[object Object]`}function se(e){return new Promise(t=>{l.setTimeout(t,e)})}function ce(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:ne(e,t)}function le(e){return e}function ue(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function de(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var fe=Symbol();function pe(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===fe?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function me(e,t){return typeof e==`function`?e(...t):!!e}function he(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ge=()=>d,_e=()=>ge(),ve=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},ye=new class extends ve{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},be=u;function xe(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=be,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Se=xe(),Ce=new class extends ve{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function we(e){return Math.min(1e3*2**e,3e4)}function Te(e){return(e??`online`)!==`online`||Ce.isOnline()}var Ee=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function De(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(f);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Ee(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},p=()=>ye.isFocused()&&(e.networkMode===`always`||Ce.isOnline())&&e.canRun(),m=()=>Te(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(h).catch(r=>{if(c())return;let i=e.retry??(_e()?0:3),a=e.retryDelay??we,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),se(o).then(()=>p()?void 0:_(p)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:m,start:()=>(m()?v():_(m).then(v),s)}}var Oe=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),m(this.gcTime)&&(this.#e=l.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(_e()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(l.clearTimeout(this.#e),this.#e=void 0)}};function ke(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{he(e,()=>t.signal,()=>n=!0)},u=pe(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?de:ue;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?je:Ae,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:Ae(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Ae(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function je(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Me=class extends Oe{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Fe(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Fe(this.options);e.data!==void 0&&(this.setState(Pe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ce(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(f).catch(f):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>g(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===fe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>g(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!h(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=pe(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ke(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=De({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Ee&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Ee){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Ne(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Pe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Se.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Ne(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Te(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Pe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Fe(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ie=class extends ve{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Re(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ze(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ze(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof g(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!re(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Be(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||g(this.options.enabled,this.#t)!==g(t.enabled,this.#t)||g(this.options.staleTime,this.#t)!==g(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||g(this.options.enabled,this.#t)!==g(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return re(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(f)),t}#h(e){return!_e()&&g(this.options.enabled,this.#t)!==!1&&m(e)}#g(){this.#b();let e=g(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=h(this.#r.dataUpdatedAt,e)+1;this.#u=l.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return g(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=l.setInterval(()=>{(this.options.refetchIntervalInBackground||ye.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(l.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(l.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Re(e,t),o=i&&Be(e,n,t,r);(a||o)&&(l={...l,...Ne(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=ce(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=ce(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let _=l.fetchStatus===`fetching`,v=m===`pending`,y=m===`error`,ee=v&&_,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:v,isSuccess:m===`success`,isError:y,isInitialLoading:ee,isLoading:ee,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:_,isRefetching:_&&!v,isLoadingError:y&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:y&&b,isStale:Ve(e,t),refetch:this.refetch,isEnabled:g(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),re(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Se.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Le(e,t){return g(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||g(t.retryOnMount,e)!==!1)}function Re(e,t){return Le(e,t)||e.state.data!==void 0&&ze(e,t,t.refetchOnMount)}function ze(e,t,n){if(g(t.enabled,e)!==!1&&g(t.staleTime,e)!==`static`){let r=g(n,e);return r===`always`||r!==!1&&Ve(e,t)}return!1}function Be(e,t,n,r){return(e!==t||g(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ve(e,n)}function Ve(e,t){return g(t.enabled,e)!==!1&&e.isStaleByTime(g(t.staleTime,e))}var He=r.createContext(!1),Ue=()=>r.useContext(He);He.Provider;function We(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ge=r.createContext(We()),Ke=()=>r.useContext(Ge),qe=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?me(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Je=e=>{r.useEffect(()=>{e.clearReset()},[e])},Ye=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||me(n,[e.error,r])),Xe=(e,t)=>t.state.data===void 0,Ze=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Qe=(e,t)=>e?.suspense&&t.isPending,$e=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function et(e,t,n){let i=Ue(),a=Ke(),s=o(n),c=s.defaultQueryOptions(e),l=s.getQueryCache().get(c.queryHash),u=e.subscribed!==!1;c._optimisticResults=i?`isRestoring`:u?`optimistic`:void 0,Ze(c),qe(c,a,l),Je(a);let[d]=r.useState(()=>new t(s,c)),p=d.getOptimisticResult(c),m=!i&&u;if(r.useSyncExternalStore(r.useCallback(e=>{let t=m?d.subscribe(Se.batchCalls(e)):f;return d.updateResult(),t},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),r.useEffect(()=>{d.setOptions(c)},[c,d]),Qe(c,p))throw $e(c,d,a);if(Ye({result:p,errorResetBoundary:a,throwOnError:c.throwOnError,query:l,suspense:c.suspense}))throw p.error;return c.notifyOnChangeProps?p:d.trackResult(p)}function tt(e,t){return et({...e,enabled:!0,suspense:!0,throwOnError:Xe,placeholderData:void 0},Ie,t)}var nt=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},rt={pipe(){return nt(this,arguments)}},it=function(){function e(){}return e.prototype=rt,e}(),x=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},at=e=>e,ot=e=>()=>e,st=ot(!0),ct=ot(!1),lt=ot(null),ut=ot(void 0),dt=ut;function ft(e,...t){return nt(e,t)}function pt(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function mt(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),t.set(i,i),i}}var ht=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n<e.length;n++)t.add(e[n]);r=Object.getPrototypeOf(r)}return t.has(`constructor`)&&typeof e.constructor==`function`&&n===e.constructor.prototype&&t.delete(`constructor`),t},gt=new WeakSet;function _t(e){return typeof e==`string`}function vt(e){return typeof e==`number`}function yt(e){return typeof e==`boolean`}function bt(e){return typeof e==`bigint`}function xt(e){return typeof e==`symbol`}function St(e){return _t(e)||vt(e)||xt(e)}function Ct(e){return typeof e==`function`}function wt(e){return e!==void 0}function Tt(e){return e!=null}function Et(e){return!1}function Dt(e){return!0}function Ot(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kt(e){return typeof e==`object`&&!!e||Ct(e)}var At=x(2,(e,t)=>kt(e)&&t in e),jt=x(2,(e,t)=>At(e,`_tag`)&&e._tag===t);function Mt(e){return e instanceof Error}function Nt(e){return At(e,Symbol.iterator)||_t(e)}var Pt=`~effect/interfaces/Hash`,Ft=e=>{switch(typeof e){case`number`:return Bt(e);case`bigint`:return Vt(e.toString(10));case`boolean`:return Vt(String(e));case`symbol`:return Vt(String(e));case`string`:return Vt(e);case`undefined`:return Vt(`undefined`);case`function`:case`object`:if(e===null)return Vt(`null`);if(e instanceof Date)return Number.isNaN(e.getTime())?Vt(`Invalid Date`):Vt(e.toISOString());if(e instanceof RegExp)return Vt(e.toString());{if(gt.has(e))return It(e);if(Yt.has(e))return Yt.get(e);let t=Zt(e,()=>zt(e)?e[Pt]():typeof e==`function`?It(e):e instanceof DataView?Gt(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):Array.isArray(e)||ArrayBuffer.isView(e)?Gt(e):e instanceof Map?Kt(e):e instanceof Set?qt(e):Ut(e));return Yt.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},It=e=>(Jt.has(e)||Jt.set(e,Bt(Math.floor(Math.random()*(2**53-1)))),Jt.get(e)),Lt=x(2,(e,t)=>e*53^t),Rt=e=>e&3221225471|e>>>1&1073741824,zt=e=>At(e,Pt),Bt=e=>{if(e!==e)return Vt(`NaN`);if(e===1/0)return Vt(`Infinity`);if(e===-1/0)return Vt(`-Infinity`);let t=e|0;for(t!==e&&(t^=e*4294967295);e>4294967295;)t^=e/=4294967295;return Rt(t)},Vt=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Rt(t)},Ht=(e,t)=>{let n=12289;for(let r of t)n^=Lt(Ft(r),Ft(e[r]));return Rt(n)},Ut=e=>Ht(e,ht(e)),Wt=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return Rt(r)},Gt=Wt(6151,Ft),Kt=Wt(Vt(`Map`),([e,t])=>Lt(Ft(e),Ft(t))),qt=Wt(Vt(`Set`),Ft),Jt=new WeakMap,Yt=new WeakMap,Xt=new WeakSet;function Zt(e,t){if(Xt.has(e))return Vt(`[Circular]`);Xt.add(e);let n=t();return Xt.delete(e),n}var Qt=`~effect/interfaces/Equal`;function $t(){return arguments.length===1?e=>en(e,arguments[0]):en(arguments[0],arguments[1])}function en(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||gt.has(e)||gt.has(t)?!1:on(e,t,an):!1}function tn(e,t,n){let r=nn.has(e),i=rn.has(t);if(r&&i)return!0;if(r||i)return!1;nn.add(e),rn.add(t);let a=n();return nn.delete(e),rn.delete(t),a}var nn=new WeakSet,rn=new WeakSet;function an(e,t){if(Ft(e)!==Ft(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=hn(e),r=hn(t);if(n!==r)return!1;let i=n&&r;return typeof e==`function`&&!i?!1:tn(e,t,()=>{if(i)return e[Qt](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:cn(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView)return!1;if(n){let n=t;return ln(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}return ln(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:fn(e,t):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:mn(e,t):un(e,t)})}function on(e,t,n){let r=sn.get(e);if(!r)r=new WeakMap,sn.set(e,r);else if(r.has(t))return r.get(t);let i=n(e,t);r.set(t,i);let a=sn.get(t);return a||(a=new WeakMap,sn.set(t,a)),a.set(e,i),i}var sn=new WeakMap;function cn(e,t){for(let n=0;n<e.length;n++)if(!en(e[n],t[n]))return!1;return!0}function ln(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function un(e,t){let n=ht(e),r=ht(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!en(e[i],t[i]))return!1;return!0}function dn(e,t){return function(n,r){let i=Array.from(r);for(let[r,a]of n){let n=!1;for(let o=0;o<i.length;o++){let[s,c]=i[o];if(e(r,s)&&t(a,c)){i[o]=i[i.length-1],i.pop(),n=!0;break}}if(!n)return!1}return!0}}var fn=dn(en,en);function pn(e){return function(t,n){let r=Array.from(n);for(let n of t){let t=!1;for(let i=0;i<r.length;i++){let a=r[i];if(e(n,a)){r[i]=r[r.length-1],r.pop(),t=!0;break}}if(!t)return!1}return!0}}var mn=pn(en),hn=e=>At(e,Qt),gn=()=>$t,_n=e=>(t,n)=>t===n||e(t,n),vn=(e,t)=>e===t,yn=()=>vn;function bn(e){return _n((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function xn(e){return _n((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}var Sn=e=>e.length>0;function Cn(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function wn(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Cn(e,n,t[n])}var Tn=Symbol.for(`~effect/Redactable`),En=e=>At(e,Tn);function Dn(e){return En(e)?On(e):e}function On(e){return e[Tn](globalThis[`~effect/Fiber/currentFiber`]?.context??jn)}var kn=`~effect/Fiber/currentFiber`,An=new Map,jn={"~effect/Context":{},base:An,depth:0,mapUnsafe:An,pipe(){return nt(this,arguments)}};function Mn(e,t){let n=t?.space??0,r=new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return Nn;r.add(e);let l;if(Tn in e)l=c(On(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
2
+ `+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=In(e);else if(!t?.ignoreToString&&At(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Ln(e);l=e instanceof Error&&e.cause?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${Pn(t)}:${c(e[t],n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Pn(t)}: ${c(e[t],n+1)}`).join(`,
3
+ `)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}var Nn=`[Circular]`;function Pn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Fn(e){return e.map(e=>`[${Pn(e)}]`).join(``)}function In(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Ln(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Rn(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=At(r,Tn)?Dn(r):Dn(t);if(typeof i==`bigint`)return Mn(i);if(typeof i!=`object`||!i)return i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(!n.includes(i))return n.push(i),i},t?.space)??`null`}var zn=Symbol.for(`nodejs.util.inspect.custom`),Bn=e=>{try{return e=Dn(e),At(e,`toJSON`)&&Ct(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(Bn):e}catch{return`[toJSON threw]`}},Vn=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Rn(e,{space:t}):Mn(e,{space:t})}catch{return String(e)}},Hn={toJSON(){return Bn(this)},[zn](){return this.toJSON()},toString(){return Mn(this.toJSON())}},Un=class{[zn](){return this.toJSON()}toString(){return Mn(this.toJSON())}},Wn=class e{called=!1;self;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}[Symbol.iterator](){return new e(this.self)}},Gn=(()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}};return t[e](()=>Error().stack)?.includes(e)===!0?t[e]:n[e]})(),Kn=`~effect/Effect`,qn=`~effect/Exit`,Jn={_A:at,_E:at,_R:at},Yn=`${Kn}/identifier`,Xn=`${Kn}/args`,Zn=`${Kn}/evaluate`,Qn=`${Kn}/successCont`,$n=`${Kn}/failureCont`,er=`${Kn}/ensureCont`,tr=Symbol.for(`effect/Effect/Yield`),nr={pipe(){return nt(this,arguments)},toJSON(){return{...this}},toString(){return Mn(this.toJSON(),{ignoreToString:!0,space:2})},[zn](){return this.toJSON()}},rr={[Kn]:Jn,...nr,[Symbol.iterator](){return new Wn(this)},toJSON(){return{_id:`Effect`,op:this[Yn],...`~effect/Effect/args`in this?{args:this[Xn]}:void 0}}},ir=e=>At(e,Kn),ar=e=>At(e,qn),or=`~effect/Cause`,sr=`~effect/Cause/Reason`,cr=e=>At(e,or),lr=e=>At(e,sr),ur=class{[or];reasons;constructor(e){this[or]=or,this.reasons=e}pipe(){return nt(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${Mn(this.reasons)})`}[zn](){return this.toJSON()}[Qt](e){return cr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>$t(t,e.reasons[n]))}[Pt](){return Gt(this.reasons)}},dr=new WeakMap,fr=class{[sr];annotations;_tag;constructor(e,t,n){if(this[sr]=sr,this._tag=e,t!==pr&&typeof n==`object`&&n&&t.size>0){let e=dr.get(n);e&&(t=new Map([...e,...t])),dr.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return nt(this,arguments)}toString(){return Mn(this)}[zn](){return this.toString()}},pr=new Map,mr=class extends fr{error;constructor(e,t=pr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${Mn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[Qt](e){return xr(e)&&$t(this.error,e.error)&&$t(this.annotations,e.annotations)}[Pt](){return Lt(Vt(this._tag))(Lt(Ft(this.error))(Ft(this.annotations)))}},hr=e=>new ur(e),gr=new ur([]),_r=e=>new ur([new mr(e)]),vr=class extends fr{defect;constructor(e,t=pr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${Mn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[Qt](e){return Sr(e)&&$t(this.defect,e.defect)&&$t(this.annotations,e.annotations)}[Pt](){return Lt(Vt(this._tag))(Lt(Ft(this.defect))(Ft(this.annotations)))}},yr=e=>new ur([new vr(e)]),br=x(e=>cr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new ur(e.reasons.map(e=>e.annotate(t,n)))),xr=e=>e._tag===`Fail`,Sr=e=>e._tag===`Die`,Cr=e=>e._tag===`Interrupt`;function wr(e){return Nr(`Effect.evaluate: Not implemented`)}var Tr=e=>({...rr,[Yn]:e.op,[Zn]:e[`~effect/Effect/evaluate`]??wr,[Qn]:e[Qn],[$n]:e[$n],[er]:e[er]}),Er=e=>{let t=Tr(e);return function(){let n=Object.create(t);return n[Xn]=e.single===!1?arguments:arguments[0],n}},Dr=e=>{let t={[qn]:qn,_tag:e.op,get[e.prop](){return this[Xn]},...Tr(e),toString(){return`${e.op}(${Mn(this[Xn])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[Xn]}},[Qt](e){return ar(e)&&e._tag===this._tag&&$t(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[Pt](){return Lt(Vt(e.op),Ft(this[Xn]))}};return function(e){let n=Object.create(t);return n[Xn]=e,n}},Or=Dr({op:`Success`,prop:`value`,[Zn](e){let t=e.getCont(Qn);return t?t[Qn](this[Xn],e,this):e.yieldWith(this)}}),kr={key:`effect/Cause/StackTrace`},Ar={key:`effect/Cause/InterruptorStackTrace`},jr=Dr({op:`Failure`,prop:`cause`,[Zn](e){let t=this[Xn],n=!1;e.currentStackFrame&&(t=br(t,{mapUnsafe:new Map([[kr.key,e.currentStackFrame]])}),n=!0);let r=e.getCont($n);for(;e.interruptible&&e._interruptedCause&&r;)r=e.getCont($n);return r?r[$n](t,e,n?void 0:this):e.yieldWith(n?jr(t):this)}}),Mr=e=>jr(_r(e)),Nr=e=>jr(yr(e)),Pr=Er({op:`WithFiber`,[Zn](e){return this[Xn](e)}}),Fr=function(){class e extends globalThis.Error{}let t=Tr({op:`YieldableError`,[Zn](){return Mr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Ir=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends Fr{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(wn(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),Lr=e=>{class t extends Ir{_tag=e}return t.prototype.name=e,t},Rr=`~effect/Cause/Done`,zr=e=>At(e,Rr),Br={[Rr]:Rr,_tag:`Done`,value:void 0},Vr=e=>e===void 0?Br:{[Rr]:Rr,_tag:`Done`,value:e},Hr=Mr(Br),Ur=e=>e===void 0?Hr:Mr(Vr(e)),Wr=`~effect/data/Option`,Gr={[Wr]:{_A:e=>e},...nr,[Symbol.iterator](){return new Wn(this)}},Kr=Object.defineProperty(Object.assign(Object.create(Gr),{_tag:`Some`,_op:`Some`,[Qt](e){return Yr(e)&&Zr(e)&&$t(this.value,e.value)},[Pt](){return Lt(Ft(this._tag))(Ft(this.value))},toString(){return`some(${Mn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:Bn(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),qr=Ft(`None`),Jr=Object.assign(Object.create(Gr),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[Qt](e){return Yr(e)&&Xr(e)},[Pt](){return qr},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Yr=e=>At(e,Wr),Xr=e=>e._tag===`None`,Zr=e=>e._tag===`Some`,Qr=Object.create(Jr),$r=e=>{let t=Object.create(Kr);return t.value=e,t},ei=`~effect/data/Result`,ti={[ei]:{_A:e=>e,_E:e=>e},...nr,[Symbol.iterator](){return new Wn(this)}},ni=Object.assign(Object.create(ti),{_tag:`Success`,_op:`Success`,[Qt](e){return ii(e)&&oi(e)&&$t(this.success,e.success)},[Pt](){return Lt(Ft(this._tag))(Ft(this.success))},toString(){return`success(${Mn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:Bn(this.success)}}}),ri=Object.assign(Object.create(ti),{_tag:`Failure`,_op:`Failure`,[Qt](e){return ii(e)&&ai(e)&&$t(this.failure,e.failure)},[Pt](){return Lt(Ft(this._tag))(Ft(this.failure))},toString(){return`failure(${Mn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:Bn(this.failure)}}}),ii=e=>At(e,ei),ai=e=>e._tag===`Failure`,oi=e=>e._tag===`Success`,si=e=>{let t=Object.create(ri);return t.failure=e,t},ci=e=>{let t=Object.create(ni);return t.success=e,t},li=x(2,(e,t)=>Xr(e)?si(t()):ci(e.value));function ui(e){return(t,n)=>t===n?0:e(t,n)}var di=ui((e,t)=>e<t?-1:1),fi=ui((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1);function pi(e){return ui((t,n)=>e(n,t))}function mi(e){return ui((t,n)=>{let r=0;for(let i of e)if(r=i(t,n),r!==0)return r;return r})}var hi=x(2,(e,t)=>ui((n,r)=>e(t(n),t(r)))),gi=e=>x(2,(t,n)=>e(t,n)===-1),_i=e=>x(2,(t,n)=>e(t,n)===1),vi=e=>x(2,(t,n)=>e(t,n)!==1),yi=e=>x(2,(t,n)=>e(t,n)!==-1),S=()=>Qr,C=$r,bi=Yr,w=Xr,T=Zr,E=x(2,(e,{onNone:t,onSome:n})=>w(e)?t():n(e.value)),xi=x(2,(e,t)=>w(e)?t():e.value),Si=x(2,(e,t)=>w(e)?t():e),Ci=e=>{let t=S();for(t of e)if(T(t))return t;return t},wi=e=>e==null?S():C(e),Ti=e=>e===void 0?S():C(e),Ei=e=>e===null?S():C(e),Di=xi(lt),Oi=xi(ut),ki=e=>(...t)=>{try{return C(e(...t))}catch{return S()}},Ai=x(2,(e,t)=>w(e)?S():C(t(e.value))),ji=x(2,(e,t)=>w(e)?S():t(e.value)),Mi=ji(at),Ni=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(w(n))return S();t.push(n.value)}return C(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(w(r))return S();Cn(t,n,r.value)}return C(t)},Pi=e=>w(e)?[]:[e.value],Fi=x(2,(e,t)=>w(e)?S():t(e.value)?C(e.value):S()),Ii=e=>_n((t,n)=>w(t)?w(n):!w(n)&&e(t.value,n.value)),Li=(e=>x(2,(t,n)=>!w(t)&&e(t.value,n)))(gn()),Ri=x(2,(e,t)=>!w(e)&&t(e.value)),zi=ci,Bi=si,Vi=li,Hi=e=>{if(Ct(e))try{return zi(e())}catch(e){return Bi(e)}try{return zi(e.try())}catch(t){return Bi(e.catch(t))}},Ui=ii,Wi=ai,Gi=oi,Ki=x(2,(e,t)=>Gi(e)?zi(t(e.success)):e),qi=x(2,(e,{onFailure:t,onSuccess:n})=>Wi(e)?t(e.failure):n(e.success)),Ji=x(2,(e,t)=>{if(Gi(e))return e.success;throw t(e.failure)})(at),Yi=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(Wi(n))return n;t.push(n.success)}return zi(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(Wi(r))return r;Cn(t,n,r.success)}return zi(t)},Xi=(...e)=>e,Zi=bn,Qi={[Symbol.iterator](){return $i}},$i={next(){return{done:!0,value:void 0}}},ea=()=>Qi,ta=x(2,(e,t)=>Object.hasOwn(e,t)),na=x(2,(e,t)=>{let n={...e};for(let r of ra(e))Cn(n,r,t(e[r],r));return n}),ra=e=>Object.keys(e),ia=e=>x(2,(t,n)=>{for(let r of ra(t))if(!ta(n,r)||!e(t[r],n[r]))return!1;return!0}),aa=e=>{let t=ia(e);return(e,n)=>t(e,n)&&t(n,e)},oa=globalThis.Array,sa=e=>oa.isArray(e)?e:oa.from(e),ca=e=>oa.isArray(e)?e:[e],la=x(2,(e,t)=>[t,...e]),ua=x(2,(e,t)=>[...e,t]),da=x(2,(e,t)=>sa(e).concat(sa(t)));oa.isArray;var fa=Sn,pa=Sn;function ma(e,t){return!Number.isFinite(e)||e<0||e>=t.length}var ha=x(2,(e,t)=>{let n=Math.floor(t);return ma(n,e)?S():C(e[n])}),ga=x(2,(e,t)=>{let n=Math.floor(t);if(ma(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]}),_a=ha(0),va=ga(0),ya=e=>e.slice(1),ba=x(2,(e,t)=>{let n=sa(e);for(let e=n.length-1;e>=0;e--){let r=n[e],i=t(r,e);if(typeof i==`boolean`){if(i)return C(r)}else if(T(i))return i}return S()}),xa=x(2,(e,t)=>{let n=oa.from(e);return n.sort(t),n}),Sa=x(2,(e,t)=>Ca(e,t,Xi)),Ca=x(3,(e,t,n)=>{let r=sa(e),i=sa(t);if(pa(r)&&pa(i)){let e=[n(va(r),va(i))],t=Math.min(r.length,i.length);for(let a=1;a<t;a++)e[a]=n(r[a],i[a]);return e}return[]}),wa=x(2,(e,t)=>{let n=sa(e);if(pa(n)){let[e,r]=t(n),i=[e],a=r;for(;Sn(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),Ta=x(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Ea(e),[]]:[la(e.slice(1,n),va(e)),e.slice(n)]}),Ea=e=>e.slice(),Da=x(2,(e,t)=>{let n=sa(e);return pa(n)?wa(n,Ta(t)):[]}),Oa=x(2,(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e].push(r):Cn(n,e,[r])}return n}),ka=(e,t)=>{let n=Ft(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if($t(e,t))return!1;return r.push(t),!0},Aa=x(2,(e,t)=>{let n=sa(e),r=sa(t);return pa(n)?pa(r)?La(da(n,r)):n:r}),ja=()=>[],Ma=e=>[e],Na=x(2,(e,t)=>e.map(t)),Pa=e=>{let t=[];for(let n of e)T(n)&&t.push(n.value);return t},Fa=xn,Ia=x(2,(e,t)=>{let n=sa(e);if(pa(n)){let e=[va(n)],r=ya(n);for(let n of r)e.every(e=>!t(n,e))&&e.push(n);return e}return[]}),La=e=>{let t=sa(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)ka(n,e)&&r.push(e);return r},Ra=`~effect/BigDecimal`,za={[Ra]:Ra,[Pt](){let e=Ka(this);return Lt(Ft(e.value),Bt(e.scale))},[Qt](e){return Ba(e)&&Xa(this,e)},toString(){return`BigDecimal(${Za(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[zn](){return this.toJSON()},pipe(){return nt(this,arguments)}},Ba=e=>At(e,Ra),Va=(e,t)=>{let n=Object.create(za);return n.value=e,n.scale=t,n},Ha=(e,t)=>{if(e!==Ua&&e%Wa===Ua)throw RangeError(`Value must be normalized`);let n=Va(e,t);return n.normalized=n,n},Ua=BigInt(0),Wa=BigInt(10),Ga=Ha(Ua,0),Ka=e=>{if(e.normalized===void 0){if(e.value===Ua)e.normalized=Ga;else{let t=`${e.value}`,n=0;for(let e=t.length-1;e>=0&&t[e]===`0`;e--)n++;n===0&&(e.normalized=e),e.normalized=Ha(BigInt(t.substring(0,t.length-n)),e.scale-n)}}return e.normalized},qa=x(2,(e,t)=>t>e.scale?Va(e.value*Wa**BigInt(t-e.scale),t):t<e.scale?Va(e.value/Wa**BigInt(e.scale-t),t):e),Ja=e=>e.value<Ua?Va(-e.value,e.scale):e,Ya=_n((e,t)=>e.scale>t.scale?qa(t,e.scale).value===e.value:e.scale<t.scale?qa(e,t.scale).value===t.value:e.value===t.value),Xa=x(2,(e,t)=>Ya(e,t)),Za=e=>{let t=Ka(e);if(Math.abs(t.scale)>=16)return Qa(t);let n=t.value<Ua,r=n?`${t.value}`.substring(1):`${t.value}`,i,a;if(t.scale>=r.length)i=`0`,a=`0`.repeat(t.scale-r.length)+r;else{let e=r.length-t.scale;if(e>r.length){let t=e-r.length;i=`${r}${`0`.repeat(t)}`,a=``}else a=r.slice(e),i=r.slice(0,e)}let o=a===``?i:`${i}.${a}`;return n?`-${o}`:o},Qa=e=>{if($a(e))return`0e+0`;let t=Ka(e),n=`${Ja(t).value}`,r=n.slice(0,1),i=n.slice(1),a=`${eo(t)?`-`:``}${r}`;i!==``&&(a+=`.${i}`);let o=i.length-t.scale;return`${a}e${o>=0?`+`:``}${o}`},$a=e=>e.value===Ua,eo=e=>e.value<Ua,to=e=>Tr({op:e.label,[Zn]:e.evaluate}),no=`~effect/Context/Service`,ro=function(){function e(){}let t=e;Object.setPrototypeOf(t,io);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[oo]=oo,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&ao.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},io={[no]:no,...to({label:`Service`,evaluate(e){return Or(Ao(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return wo(this,e)},use(e){return Pr(t=>e(Ao(t.context,this)))},useSync(e){return Pr(t=>Or(e(Ao(t.context,this))))}},ao=new Set,oo=`~effect/Context/Reference`,so=`~effect/Context`,co=8,lo=8,uo=(e,t,n,r)=>{let i=Object.create(vo);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},fo=(e,t)=>{t&&(fo(e,t.parent),e.set(t.key,t.value))},po=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return fo(t,e.overlay),e._flat=t},mo=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),_o(n)},ho=Symbol(),go=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?ho:(n.overlay&&++n.baseHits>=lo&&(n.base=po(n),n.overlay=void 0,n.depth=0),r)},_o=e=>uo(void 0,e,void 0,0),vo={get mapUnsafe(){return po(this)},...nr,[so]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[Qt](e){if(!bo(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!$t(r,n.get(e)))return!1;return!0},[Pt](){return Bt(this.mapUnsafe.size)}},yo=(e,t)=>e.cacheRoot===t.cacheRoot,bo=e=>At(e,so),xo=e=>!!e[oo],So=()=>Co,Co=_o(new Map),wo=(e,t)=>_o(new Map([[e.key,t]])),To=x(3,(e,t,n)=>Eo(e,t.key,n)),Eo=(e,t,n)=>{let r=e,i=ao.has(t)?void 0:r.cacheRoot;if(r.depth>=co){let e=new Map(r.mapUnsafe);return e.set(t,n),uo(i,e,void 0,0)}return uo(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},Do=x(2,(e,t)=>Oo(e,t.key)),Oo=(e,t)=>{let n=go(e,t);return n===ho?void 0:n},ko=x(2,(e,t)=>{let n=go(e,t.key);if(n===ho){if(xo(t))return Mo(t);throw No(t)}return n}),Ao=ko,jo=`~effect/Context/defaultValue`,Mo=e=>jo in e?e[jo]:e[jo]=e.defaultValue(),No=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
4
+ `);e.splice(1,3),t.stack=e.join(`
5
+ `)}return t},Po=x(2,(e,t)=>{let n=go(e,t.key);return n===ho?xo(t)?C(Mo(t)):S():C(n)}),Fo=x(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:mo(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),Io=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return _o(t)},Lo=(...e)=>t=>{let n=new Set(e.map(e=>e.key));return mo(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},Ro=ro,zo=`~effect/time/Duration`,Bo=BigInt(0),Vo=BigInt(1),Ho=BigInt(2),Uo=BigInt(10),Wo=BigInt(1e3),Go=e=>BigInt(e<0?Math.ceil(e-.5):Math.floor(e+.5)),Ko=e=>Go(e*1e6),qo=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Uo**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t,s=o/a+(o%a*Ho>=a?Vo:Bo);return r?-s:s},Jo=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Yo=e=>{switch(typeof e){case`number`:return ss(e);case`bigint`:return os(e);case`string`:{if(e===`Infinity`)return is;if(e===`-Infinity`)return as;let t=Jo.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return os(qo(r,Vo));if(i===`micro`||i===`micros`)return os(qo(r,Wo));let a=Number(r);switch(i){case`milli`:case`millis`:return ss(a);case`second`:case`seconds`:return cs(a);case`minute`:case`minutes`:return ls(a);case`hour`:case`hours`:return us(a);case`day`:case`days`:return ds(a);case`week`:case`weeks`:return fs(a)}break}case`object`:{if(e===null)break;if(zo in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(vt)?Xo(e):Number.isNaN(e[0])||Number.isNaN(e[1])?rs:e[0]===-1/0||e[1]===-1/0?as:e[0]===1/0||e[1]===1/0?is:ts(Go(e[0]*1e9+e[1]));let t=e,n=0;return t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds?ts(n):ts(Go(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0)))}}return Xo(e)},Xo=e=>{throw Error(`Invalid Input: ${e}`)},Zo={_tag:`Millis`,millis:0},Qo={_tag:`Infinity`},$o={_tag:`NegativeInfinity`},es={[zo]:zo,[Pt](){switch(this.value._tag){case`Millis`:{let e=this.value.millis*1e6;return Number.isFinite(e)?Ft(Go(e)):Bt(this.value.millis)}case`Nanos`:return Ft(this.value.nanos);default:return Ut(this.value)}},[Qt](e){return ns(e)&&vs(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[zn](){return this.toJSON()},pipe(){return nt(this,arguments)}},ts=e=>{let t=Object.create(es);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Zo:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ko(e)}:e>0?Qo:$o:e===Bo?Zo:{_tag:`Nanos`,nanos:e},t},ns=e=>At(e,zo),rs=ts(0),is=ts(1/0),as=ts(-1/0),os=e=>ts(e),ss=e=>ts(e),cs=e=>ts(e*1e3),ls=e=>ts(e*6e4),us=e=>ts(e*36e5),ds=e=>ts(e*864e5),fs=e=>ts(e*6048e5),ps=e=>hs(Yo(e),{onMillis:at,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),ms=e=>{let t=Yo(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return Ko(t.value.millis)}},hs=x(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),gs=x(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(ms(e),t.value.nanos):n.onNanos(e.value.nanos,ms(t))),_s=(e,t)=>gs(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),vs=x(2,(e,t)=>_s(e,t)),ys=e=>t=>!Wi(e(t)),bs=e=>t=>t.has(e)?zi(t):Bi(t),xs=x(2,(e,t)=>n=>{let r=e(n);return Wi(r)?r:t(r.success)}),Ss=Ro(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new Es}),Cs=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ws=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Ts=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},Es=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?ws:Cs)}shouldYield(e){return e.currentOpCount>=e.maxOpsBeforeYield}makeDispatcher(){return new Ds(this.setImmediate)}},Ds=class{tasks=new Ts;running=void 0;setImmediate;constructor(e=Cs){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}},Os=Ro(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),ks=Ro(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),As=class extends it{constructor(e){super(),e&&wn(this,e)}},js=e=>class extends As{_tag=e},Ms=Lr,Ns=`~effect/encoding/EncodingError`,Ps=class extends Ms(`EncodingError`){[Ns]=Ns},Fs=e=>Vs(typeof e==`string`?zs.encode(e):e),Is=e=>{let t=Bs(e),n=t.length;if(n%4!=0)return Bi(new Ps({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Bi(new Ps({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=Hs(t.charCodeAt(e))<<18|Hs(t.charCodeAt(e+1))<<12|Hs(t.charCodeAt(e+2))<<6|Hs(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return zi(r)}catch(e){return Bi(new Ps({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Ls=e=>Ks(typeof e==`string`?zs.encode(e):e),Rs=e=>{let t=``;for(let n=e>>>3;n>0;n--){let e=Math.random()*4294967296>>>0;t+=Gs[e>>>24]+Gs[e>>>16&255]+Gs[e>>>8&255]+Gs[e&255]}return t},zs=new TextEncoder,Bs=e=>e.replace(/[\n\r]/g,``),Vs=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Us[e[r-2]>>2],n+=Us[(e[r-2]&3)<<4|e[r-1]>>4],n+=Us[(e[r-1]&15)<<2|e[r]>>6],n+=Us[e[r]&63];return r===t+1&&(n+=Us[e[r-2]>>2],n+=Us[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Us[e[r-2]>>2],n+=Us[(e[r-2]&3)<<4|e[r-1]>>4],n+=Us[(e[r-1]&15)<<2],n+=`=`),n};function Hs(e){if(e>=Ws.length)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);let t=Ws[e];if(t===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return t}var Us=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),Ws=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Gs=[];for(let e=0;e<256;e++)Gs.push(e.toString(16).padStart(2,`0`));var Ks=e=>{let t=``;for(let n=0;n<e.length;n++)t+=Gs[e[n]];return t},qs=`effect/Tracer/ParentSpan`,Js=class extends ro()(qs,{fiberCached:!0}){},Ys=e=>e,Xs=Ro(`effect/Tracer/DisablePropagation`,{defaultValue:ct}),Zs=Ro(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Qs=Ro(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),$s=`effect/Tracer`,ec=Ro($s,{fiberCached:!0,defaultValue:()=>Ys({span:e=>new tc(e)})}),tc=class{_tag=`Span`;spanId;traceId=`native`;sampled;name;parent;annotations;links;startTime;kind;status;attributes;events=[];constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime},this.attributes=new Map,this.traceId=Oi(e.parent)?.traceId??Rs(32),this.spanId=Rs(16)}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}},nc=`effect/observability/Metric/FiberRuntimeMetricsKey`,rc=Ro(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:ut}),ic=Ro(`effect/References/TracerEnabled`,{defaultValue:st}),ac=Ro(`effect/References/TracerTimingEnabled`,{defaultValue:st}),oc=Ro(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),sc=Ro(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),cc=Ro(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),lc=Ro(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),uc=Ro(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),dc=Ro(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),fc=(()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),pc=()=>Error.stackTraceLimit,mc=e=>{fc&&(Error.stackTraceLimit=e)},hc=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=pc();mc(3);let n=Error();return mc(t),{...e,captureStackTrace:_c(()=>n.stack)}},gc=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
6
+ `);if(i[e]!==void 0)return n=i[e].trim(),n}},_c=gc(3),vc=class extends fr{fiberId;constructor(e,t=pr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[Qt](e){return Cr(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[Pt](){return Lt(Vt(`${this._tag}:${this.fiberId}`))(It(this.annotations))}},yc=e=>new vc(e),bc=e=>new ur([new vc(e)]),xc=e=>{let t=e.reasons.find(xr);return t?zi(t):Bi(e)},Sc=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return zi(n.error)}return Bi(e)},Cc=e=>{let t=e.reasons.find(Sr);return t?zi(t.defect):Bi(e)},wc=e=>e.reasons.some(Cr),Tc=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?zi(t):Bi(e)},Ec=e=>e.reasons.length>0&&e.reasons.every(Cr),Dc=x(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new ur(Aa(e.reasons,t.reasons));return $t(e,n)?e:n}),Oc=x(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>xr(e)?(n=!0,new mr(t(e.error),e.annotations)):e);return n?hr(r):e}),kc=e=>{let t={Fail:[],Die:[],Interrupt:[]};for(let n=0;n<e.reasons.length;n++)t[e.reasons[n]._tag].push(e.reasons[n]);return t},Ac=e=>{let t=kc(e);return t.Fail.length>0?t.Fail[0].error:t.Die.length>0?t.Die[0].defect:t.Interrupt.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`)},jc=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=pc();mc(1);for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(Mc(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=Lc(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(Mc(i,r[0].annotations,t))}return mc(i),n},Mc=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Nc(e),{cause:e.cause?Mc(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=Fc(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?Ic(e,t):e}n?.includeCauseInStack&&(i.stack=Bc(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else i=new globalThis.Error(e?r===`string`?e:Rn(e):`Unknown error: ${e}`);return i},Nc=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return Rn(e)},Pc=/\((.*)\)/g,Fc=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
7
+ `),a=[r];for(let e=1;e<i.length&&!/(?:Generator\.next|~effect\/Effect)/.test(i[e]);e++)a.push(i[e]);return n?Ic(a.join(`
8
+ `),n):a.join(`
9
+ `)},Ic=(e,t)=>{let n=t?.get(kr.key);return n&&(e=`${e}\n${Rc(n)}`),e},Lc=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(Ar.key);n.push(` at fiber (${t})`),r&&n.push(Rc(r))}return n.join(`
10
+ `)},Rc=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Pc),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
11
+ `)},zc=e=>jc(e).map(Bc).join(`
12
+ `),Bc=e=>e.cause?`${e.stack} {\n${Vc(e.cause,` `)}\n}`:e.stack,Vc=(e,t)=>{let n=e.stack.split(`
13
+ `),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Vc(e.cause,`${t} `)}\n${t}}`),r},Hc=`~effect/Fiber`,Uc={_A:at,_E:at},Wc={id:0},Gc=()=>globalThis[kn],Kc=class{constructor(e,t=!0){this[Hc]=Uc,this.setContext(e),this.id=++Wc.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=[],this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this.runtimeMetrics?.recordFiberStart(this.context)}[Hc];id;interruptible;currentOpCount;_stack;_observers;_exit;_children;_interruptedCause;_yielded;_running;_deferredInterrupt;context;currentScheduler;currentTracerContext;currentSpan;currentLogLevel;minimumLogLevel;currentStackFrame;runtimeMetrics;maxOpsBeforeYield;currentPreventYield;_dispatcher=void 0;get currentDispatcher(){return this._dispatcher??=this.currentScheduler.makeDispatcher()}getRef(e){return Ao(this.context,e)}addObserver(e){return this._exit?(e(this._exit),dt):(this._observers.push(e),()=>{if(this._exit)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)})}interruptUnsafe(e,t){if(this._exit)return;let n=bc(e);this.currentStackFrame&&(n=br(n,wo(kr,this.currentStackFrame))),t&&(n=br(n,t)),this._interruptedCause=this._interruptedCause?Dc(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(nl(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===tr)return;let n=Jc.interruptChildren&&Jc.interruptChildren(this);if(n!==void 0)return this.evaluate(Ll(n,()=>t));this._exit=t,this.runtimeMetrics?.recordFiberEnd(this.context,this._exit);for(let e=0;e<this._observers.length;e++)this._observers[e](t);this._observers.length=0,this._stack.length=0,this._children=void 0,this.context=So()}runLoop(e){let t=globalThis[kn];globalThis[kn]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;){if(this._deferredInterrupt&&(this._deferredInterrupt=!1,i=nl(this._interruptedCause)),this.currentOpCount++,!r&&!this.currentPreventYield&&this.currentScheduler.shouldYield(this)){r=!0;let e=i;i=Ll(sl,()=>e)}if(i=this.currentTracerContext?this.currentTracerContext(i,this):i[Zn](this),i===tr){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return tr}}}catch(e){return At(i,`~effect/Effect/evaluate`)?this.runLoop(Nr(e)):Nr(`Fiber.runLoop: Not a valid effect: ${String(i)}`)}finally{this._running=n,globalThis[kn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,qc;for(;;){let t=this._stack.pop();if(!t)return;let n=t[`~effect/Effect/ensureCont`]&&t[`~effect/Effect/ensureCont`](this);if(n)return n[e]=n,n;if(t[e])return t}}yieldWith(e){return this._yielded=e,tr}children(){return this._children??=new Set}pipe(){return nt(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&yo(t,e))return;let n=this.getRef(Ss);n!==this.currentScheduler&&(this.currentScheduler=n,this._dispatcher=void 0),this.currentSpan=Oo(e,qs),this.currentLogLevel=this.getRef(lc),this.minimumLogLevel=this.getRef(uc),this.currentStackFrame=this.getRef(rc),this.maxOpsBeforeYield=this.getRef(Os),this.currentPreventYield=this.getRef(ks),this.runtimeMetrics=Oo(e,nc);let r=Oo(e,$s);this.currentTracerContext=r?r.context:void 0}get currentSpanLocal(){return this.currentSpan?._tag===`Span`?this.currentSpan:void 0}},qc={[Qn](e,t){return nl(t._interruptedCause)},[$n](e,t){return nl(t._interruptedCause)}},Jc={interruptChildren:void 0},Yc=e=>{if(!e.currentStackFrame)return;let t=new Map;return t.set(Ar.key,e.currentStackFrame),_o(t)},Xc=e=>{let t=e;return t._exit?tl(t._exit):yl(n=>t._exit?n(tl(t._exit)):il(e.addObserver(e=>n(tl(e)))))},Zc=e=>yl(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(tl(r))}return a(),il(()=>i?.())}),Qc=e=>Pr(t=>$c(e,t.id)),$c=x(e=>At(e[0],Hc),(e,t,n)=>Pr(r=>{let i=Yc(r);return i=i&&n?Fo(i,n):i??n,e.interruptUnsafe(t,i),Pl(Xc(e))})),el=e=>Pr(t=>{let n=Yc(t),r=ja();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Pl(Zc(r))}),tl=Or,nl=jr,rl=Mr,il=Er({op:`Sync`,[Zn](e){let t=this[Xn](),n=e.getCont(Qn);return n?n[Qn](t,e):e.yieldWith(Or(t))}}),al=Er({op:`Suspend`,[Zn](e){return this[Xn]()}}),ol=qi({onFailure:rl,onSuccess:tl}),sl=Er({op:`Yield`,[Zn](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Jl)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),cl=tl(S()),ll=e=>al(()=>nl(Gn(e))),ul=e=>Nr(e),dl=e=>al(()=>rl(Gn(e))),fl=tl(void 0),pl=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new uf(e,`An error occurred in Effect.try`):e.catch;return al(()=>{try{return tl(Gn(t))}catch(e){return rl(Gn(()=>n(e)))}})},ml=e=>_l(function(t,n){Gn(()=>e(n)).then(e=>t(tl(e)),e=>t(ul(e)))},e.length!==0),hl=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new uf(e,`An error occurred in Effect.tryPromise`):e.catch;return _l(function(e,r){let i=t=>{try{e(rl(Gn(()=>n(t))))}catch(t){e(ul(t))}};try{Gn(()=>t(r)).then(t=>e(tl(t)),i)}catch(e){i(e)}},t.length!==0)},gl=e=>Pr(t=>e(t.id)),_l=Er({op:`Async`,single:!1,[Zn](e){let t=Gn(()=>this[Xn][0].bind(e.currentScheduler)),n=!1,r=!1,i=this[`~effect/Effect/args`][1]?new AbortController:void 0,a=t(t=>{n||(n=!0,r?e.evaluate(t):r=t)},i?.signal);return r===!1?(r=!0,e._yielded=()=>{n=!0},i===void 0&&a===void 0||e._stack.push(vl(()=>(n=!0,i?.abort(),a??Jl))),tr):r}}),vl=Er({op:`AsyncFinalizer`,[er](e){e.interruptible&&(e.interruptible=!1,e._stack.push(ud))},[$n](e,t){return wc(e)?Ll(this[Xn](),()=>nl(e)):nl(e)}}),yl=e=>_l(e,e.length>=2),bl=yl(dt),xl=(...e)=>al(()=>kl(e.length===1?e[0]():e[1].call(e[0].self))),Sl=(e,...t)=>{let n=t.length===0?function(){return al(()=>kl(e.apply(this,arguments)))}:function(){let n=al(()=>kl(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Cl(e.length,n)},Cl=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),wl=gc(2),Tl=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=pc();mc(2);let i=new globalThis.Error;return mc(r),e?(r,...a)=>El(t,r,i,a,e,n):El(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},El=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self);return Cl(o.length,function(...t){let s=al(()=>{let e=o.apply(this,arguments);return ir(e)?e:kl(e)});for(let e=0;e<r.length;e++)s=r[e](s,...t);if(!ir(s))return s;let c=pc();mc(2);let l=new globalThis.Error;return mc(c),tu(i?Wd(e,a,e=>Gd(s,e)):s,rc,t=>({name:e,stack:wl(()=>l.stack),parent:{name:`${e} (definition)`,stack:wl(()=>n.stack),parent:t}}))})},Dl=(e,...t)=>Cl(e.length,t.length===0?function(){return Ol(()=>e.apply(this,arguments))}:function(){let n=Ol(()=>e.apply(this,arguments));for(let e of t)n=e(n);return n}),Ol=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return tl(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return al(()=>n?(n=!1,Ll(r.value,e=>kl(t,e))):al(()=>kl(e())))}}}}catch(e){return ul(e)}},kl=Er({op:`Iterator`,single:!1,[Qn](e,t){let n=this[Xn][0];for(;;){let r=n.next(e);if(r.done)return tl(r.value);if(!zl(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[Zn](e){return this[Qn](this[Xn][1],e)}}),Al=x(2,(e,t)=>{let n=tl(t);return Ll(e,e=>n)}),jl=e=>Vl(e,C),Ml=x(2,(e,t)=>Ll(e,e=>ir(t)?t:Gn(()=>t(e)))),Nl=x(2,(e,t)=>Ll(e,e=>Al(ir(t)?t:Gn(()=>t(e)),e))),Pl=e=>Ll(e,e=>Jl),Fl=(e,t)=>Pr(n=>yl(r=>{let i=!1,a=new Set,o=e=>{i=!0,r(a.size===0?e:Ll(cd(el(a)),()=>e))},s=0;for(let r of e){if(i)break;let e=s++,c=Cd(n,r,!0,!0,!1);a.add(c),c.addObserver(r=>{a.delete(c);let s=!i;o(r),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}return el(a)})),Il=x(e=>ir(e[1]),(e,t,n)=>Fl([e,t],n)),Ll=x(2,(e,t)=>{let n=Object.create(Rl);return n[Xn]=e,n[Qn]=t.length===1?t:e=>t(e),n}),Rl=Tr({op:`OnSuccess`,[Zn](e){return e._stack.push(this),this[Xn]}}),zl=e=>qn in e,Bl=x(2,(e,t)=>zl(e)?e._tag===`Success`?t(e.value):e:Ll(e,t)),Vl=x(2,(e,t)=>Ll(e,e=>tl(Gn(()=>t(e))))),Hl=x(2,(e,t)=>zl(e)?Yl(e,t):Vl(e,t)),Ul=x(2,(e,t)=>zl(e)?Xl(e,t):bu(e,t)),Wl=x(2,(e,t)=>zl(e)?Zl(e,t):xu(e,t)),Gl=e=>e._tag===`Success`,Kl=e=>e._tag===`Failure`,ql=e=>e._tag===`Failure`?zi(e.cause):Bi(e),Jl=Or(void 0),Yl=x(2,(e,t)=>e._tag===`Success`?Or(t(e.value)):e),Xl=x(2,(e,t)=>{if(e._tag===`Success`)return e;let n=Sc(e.cause);return Wi(n)?e:Mr(t(n.success))}),Zl=x(2,(e,t)=>{if(e._tag===`Success`)return Or(t.onSuccess(e.value));let n=Sc(e.cause);return Wi(n)?e:Mr(t.onFailure(n.success))}),Ql=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Jl:jr(hr(t))},$l=e=>Pr(t=>tl(Po(t.context,e))),eu=x(2,(e,t)=>Pr(n=>{let r=n.context,i=t(r);return r===i?e:(n.setContext(i),Xu(e,()=>{n.setContext(r)}))})),tu=x(3,(e,t,n)=>eu(e,e=>{let r=ko(e,t),i=n(r);return r===i?e:To(e,t,i)})),nu=()=>ru,ru=Pr(e=>tl(e.context)),iu=e=>Pr(t=>e(t.context)),au=x(2,(e,t)=>zl(e)?e:eu(e,Fo(t))),ou=function(){return arguments.length===1?x(2,(e,t)=>su(e,arguments[0],t)):x(3,(e,t,n)=>su(e,t,n)).apply(this,arguments)},su=(e,t,n)=>eu(e,To(t,n)),cu=x(e=>ir(e[0]),(e,t)=>gd({while:st,body:ot(t?.disableYield?e:Ll(e,e=>sl)),step:dt})),lu=x(2,(e,t)=>{let n=Object.create(uu);return n[Xn]=e,n[$n]=t.length===1?t:e=>t(e),n}),uu=Tr({op:`OnFailure`,[Zn](e){return e._stack.push(this),this[Xn]}}),du=x(3,(e,t,n)=>lu(e,e=>{let r=t(e);return Wi(r)?nl(r.failure):Gn(()=>n(r.success,e))})),fu=x(2,(e,t)=>du(e,Sc,e=>t(e))),pu=x(2,(e,t)=>du(e,Cc,t)),mu=x(3,(e,t,n)=>lu(e,e=>{let r=t(e);return Wi(r)?nl(e):Ml(Gn(()=>n(r.success,e)),nl(e))})),hu=x(2,(e,t)=>mu(e,Sc,e=>t(e))),gu=x(e=>ir(e[0]),(e,t,n,r)=>lu(e,e=>{let i=Sc(e);return Wi(i)?nl(i.failure):t(i.success)?Gn(()=>n(i.success)):r?Gn(()=>r(i.success)):nl(e)})),_u=x(e=>ir(e[0]),(e,t,n,r)=>lu(e,e=>{let i=Sc(e);if(Wi(i))return nl(i.failure);let a=t(i.success);return Wi(a)?r?Gn(()=>r(a.failure)):nl(e):Gn(()=>n(a.success))})),vu=x(e=>ir(e[0]),(e,t,n,r)=>gu(e,Array.isArray(t)?e=>At(e,`_tag`)&&t.includes(e._tag):jt(t),n,r)),yu=x(e=>ir(e[0]),(e,t,n)=>{let r;return _u(e,e=>(r??=Object.keys(t),At(e,`_tag`)&&_t(e._tag)&&r.includes(e._tag)?zi(e):Bi(e)),e=>Gn(()=>t[e._tag](e)),n)}),bu=x(2,(e,t)=>fu(e,e=>dl(()=>t(e)))),xu=x(2,(e,t)=>Du(e,{onFailure:e=>dl(()=>t.onFailure(e)),onSuccess:e=>il(()=>t.onSuccess(e))})),Su=e=>fu(e,ul),Cu=x(e=>ir(e[0]),(e,t)=>{if(!t?.log)return Du(e,{onFailure:e=>fl,onSuccess:e=>fl});let n=yf(t.log===!0?void 0:t.log);return Tu(e,{onFailure(e){let r=xc(e);return Wi(r)?nl(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>fl})}),wu=e=>ku(e,{onFailure:Bi,onSuccess:zi}),Tu=x(2,(e,t)=>{let n=Object.create(Eu);return n[Xn]=e,n[Qn]=t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),n[$n]=t.onFailure.length===1?t.onFailure:e=>t.onFailure(e),n}),Eu=Tr({op:`OnSuccessAndFailure`,[Zn](e){return e._stack.push(this),this[Xn]}}),Du=x(2,(e,t)=>Tu(e,{onFailure:e=>{let n=e.reasons.find(xr);return n?Gn(()=>t.onFailure(n.error)):nl(e)},onSuccess:t.onSuccess})),Ou=x(2,(e,t)=>Du(e,{onFailure:e=>il(()=>t.onFailure(e)),onSuccess:e=>il(()=>t.onSuccess(e))})),ku=x(2,(e,t)=>{if(zl(e)){if(e._tag===`Success`)return Or(t.onSuccess(e.value));let n=Sc(e.cause);return Wi(n)?e:Or(t.onFailure(n.success))}return Ou(e,t)}),Au=e=>zl(e)?Or(e):ju(e),ju=Er({op:`Exit`,[Zn](e){return e._stack.push(this),this[Xn]},[Qn](e,t,n){return tl(n??Or(e))},[$n](e,t,n){return tl(n??jr(e))}}),Mu=`~effect/Scope`,Nu=`~effect/Scope/Closeable`,Pu=ro(`effect/Scope`),Fu=(e,t)=>al(()=>Iu(e,t)??fl),Iu=(e,t)=>{if(e.state._tag===`Closed`)return;let n={_tag:`Closed`,exit:t};if(e.state._tag===`Empty`){e.state=n;return}let{finalizers:r}=e.state;if(e.state=n,r.size!==0)return r.size===1?r.values().next().value(t):Ru(e,r,t)},Lu=(e,t)=>Gl(e)?t:lu(t,t=>nl(Dc(e.cause,t))),Ru=Sl(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Gc();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*Au(s(n))):i.push(Cd(o,s(n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Zc(i)),yield*Ql(r)}),zu=(e,t)=>{let n=Wu(t);if(e.state._tag===`Closed`)return n.state=e.state,n;let r={};return Hu(e,r,e=>Fu(n,e)),Hu(n,r,t=>il(()=>Uu(e,r))),n},Bu=(e,t)=>al(()=>e.state._tag===`Closed`?t(e.state.exit):(Hu(e,{},t),fl)),Vu=(e,t)=>Bu(e,ot(t)),Hu=(e,t,n)=>{e.state._tag===`Empty`?e.state={_tag:`Open`,finalizers:new Map([[t,n]])}:e.state._tag===`Open`&&e.state.finalizers.set(t,n)},Uu=(e,t)=>{e.state._tag===`Open`&&e.state.finalizers.delete(t)},Wu=(e=`sequential`)=>({[Nu]:Nu,[Mu]:Mu,strategy:e,state:Gu}),Gu={_tag:`Empty`},Ku=Pu,qu=ou(Pu),Ju=e=>al(()=>{let t=Wu();return Zu(e(t),e=>al(()=>Iu(t,e)??fl))}),Yu=(e,t,n)=>iu(r=>md(i=>Ll(Ku,a=>Nl(n?.interruptible?i(e):e,e=>Bu(a,n=>au(t(e,n),r)))))),Xu=Er({op:`OnExit`,single:!1,[Zn](e){return e._stack.push(this),this[Xn][0]},[er](e){e.interruptible&&this[`~effect/Effect/args`][2]!==!0&&(e._stack.push(ud),e.interruptible=!1)},[Qn](e,t,n){n??=Or(e);let r=this[Xn][1](n);return r?Ll(r,e=>n):n},[$n](e,t,n){n??=jr(e);let r=this[Xn][1](n);return r?Ll(Lu(n,r),e=>n):n}}),Zu=x(2,Xu),Qu=x(2,(e,t)=>Zu(e,e=>t)),$u=x(3,(e,t,n)=>Zu(e,e=>{let r=t(e);return Wi(r)?fl:n(r.success,e)})),ed=x(2,(e,t)=>$u(e,ql,t)),td=x(3,(e,t,n)=>Zu(e,e=>{if(e._tag!==`Failure`)return fl;let r=t(e.cause);return Wi(r)?fl:n(r.success,e.cause)})),nd=x(2,(e,t)=>td(Tc,t)(e)),rd=(e,t,n)=>md(r=>Ll(e,e=>Xu(r(t(e)),t=>n(e,t),!0))),id=x(2,(e,t)=>il(()=>{let n=ps(Yo(t)),r=Number.isFinite(n),i=Id(!1),a=0,o=!1,s,c=Ll(i.await,()=>s);return[Pr(t=>{let l=t.getRef(Yd),u=r?l.currentTimeMillisUnsafe():0;return o||u<a?s??c:(o=!0,i.closeUnsafe(),s=void 0,Zu(e,e=>il(()=>{o=!1,a=l.currentTimeMillisUnsafe()+n,s=e,i.openUnsafe()})))}),il(()=>{a=0,i.closeUnsafe(),s=void 0})]})),ad=x(2,(e,t)=>Vl(id(e,t),e=>e[0])),od=e=>ad(e,is),sd=Pr(e=>nl(bc(e.id))),cd=e=>Pr(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(ud)),e)),ld=Er({op:`SetInterruptible`,[er](e){if(e.interruptible=this[Xn],e._interruptedCause&&e.interruptible)return()=>nl(e._interruptedCause)}}),ud=ld(!0),dd=ld(!1),fd=e=>{if(e.interruptible=!0,e._stack.push(dd),e._interruptedCause)return nl(e._interruptedCause)},pd=e=>Pr(t=>t.interruptible?e:fd(t)??e),md=e=>Pr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(ud),e(pd)):e(at)),hd=(e,t)=>Nt(e)?t?.mode===`result`?_d(e,wu,t):_d(e,at,t):t?.discard?t.mode===`result`?_d(Object.values(e),wu,t):_d(Object.values(e),at,t):al(()=>{let n={};return Al(_d(Object.entries(e),([e,r])=>Vl(t?.mode===`result`?wu(r):r,t=>{Cn(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),gd=Er({op:`While`,[Qn](e,t){return this[Xn].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[Xn].body()):Jl},[Zn](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[Xn].body()):Jl}}),_d=x(e=>typeof e[1]==`function`,(e,t,n)=>al(()=>{let r=n?.concurrency??1,i=r===`unbounded`?1/0:Math.max(1,r);if(i===1)return vd(e,t,n);let a=sa(e),o=a.length;if(o===0)return n?.discard?fl:tl([]);let s=n?.discard?void 0:Array(o),c=xd({f:t,out:s},a,{concurrency:i});return c?Al(c,s):tl(s)})),vd=(e,t,n)=>al(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return Al(gd({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),yd=e=>{let t=e.onItem,n=e.step,r=(e,i,a,o)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!zl(c))return Ll(Au(c),t=>n(e,s,t,a)??r(e,i,a+1,o)??fl);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return(e,i,a)=>{let o=0,s=a?.end??i.length,c=a?.concurrency??1;if(c===1)return r(e,i,0,s);let l=a?.orderedStep===!0&&c>1,u=!1,d,f,p,m=!1,h,g,_=o,v=l?Array(s):void 0,y=e=>{let t=Nr(e);return h=t,u=!0,m=!0,f&&f.size>0?Ll(cd(el(Array.from(f))),()=>t):t},ee=(t,r,a)=>{if(!l)return n(e,t,r,a);if(h)return h;for(v[a]=r;_<s;){let t=v[_];if(t===void 0)return;v[_]=void 0;let r=_++,a=n(e,i[r],t,r);if(a)return a}},b=()=>{let n=!1;for(;!h&&o<s;o++){let r=i[o],a=g??t(e,r,o);if(zl(a)){if(h=ee(r,a,o),h)break}else if(d){g=void 0;let e=Cd(d,a,!0,!0,`inherit`);if(e._exit){if(h=ee(r,e._exit,o),h)break;continue}f.add(e);let t=o;if(e.addObserver(i=>{f.delete(e);try{if(h){if(!m&&i._tag===`Failure`)for(let e of i.cause.reasons)if(e._tag===`Interrupt`)continue;else h._tag===`Failure`?h.cause.reasons.push(e):h=jr(hr([e]))}else{let e=ee(r,i,t);e&&(h=e._tag===`Failure`?jr(hr(e.cause.reasons.slice())):e,b())}if(n){let e=b();e&&p(e)}else u&&f.size===0&&p(h??fl)}catch(e){p(y(e))}}),f.size<c)continue;n=!0,o++;return}else return yl(e=>{d=Gc(),f=new Set,g=a,p=e;let t;try{t=b()}catch(t){return e(y(t))}return t?e(t):al(()=>(h=Jl,m=!0,f?el(f):fl))})}if(u=!0,h){if(f&&f.size>0){let e=Yc(d);f.forEach(t=>t.interruptUnsafe(d.id,e));return}if(p||h._tag===`Failure`)return h}else if(p){if(f)f.size===0&&p(fl);else return Jl}};return b()}},bd=()=>yd,xd=yd({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag===`Failure`)return n;e.out&&(e.out[r]=n.value)}}),Sd=x(e=>Nt(e[0])&&!ir(e[0]),(e,t,n)=>al(()=>{let r=[];return Al(_d(e,(e,n)=>{let i=t(e,n);return typeof i==`boolean`?(i&&r.push(e),fl):Vl(i,t=>{t&&r.push(e)})},{discard:!0,concurrency:n?.concurrency}),r)})),Cd=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Kc(a.context,o);return n?s.evaluate(t):a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0),!r&&!s._exit&&(a.children().add(s),s.addObserver(()=>a._children.delete(s))),s},wd=x(e=>ir(e[0]),(e,t,n)=>Pr(r=>{let i=Cd(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};Hu(t,e,()=>gl(e=>e===i.id?fl:Qc(i))),i.addObserver(()=>Uu(t,e))}else i.interruptUnsafe(r.id,Yc(r))}return tl(i)})),Td=x(e=>ir(e[0]),(e,t)=>Ll(Ku,n=>wd(e,n,t))),Ed=e=>(t,n)=>{let r=new Kc(n?.scheduler?To(e,Ss,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},Dd=Ed(So()),Od=e=>{let t=Ed(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},kd=(e=>{let t=Od(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw Ac(e.cause);return e.value})})(So()),Ad=e=>{let t=Ed(e);return e=>{if(zl(e))return e;let n=new Es(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Nr(new cf(r))}},jd=Ad(So()),Md=(e=>{let t=Ad(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw Ac(n.cause);return n.value}})(So()),Nd=tl(!0),Pd=tl(!1),Fd=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Nd;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let e=0;e<this.waiters.length;e++)this.scheduled.push(this.waiters[e]);return this.waiters=[],Nd}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](Jl)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Jl)}open=Pr(e=>this._isOpen?Pd:(this._isOpen=!0,this.scheduleUnsafe(e)));release=Pr(e=>this._isOpen?Pd:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=yl(e=>this._isOpen?e(fl):(this.waiters.push(e),il(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=il(()=>this.closeUnsafe());whenOpen=e=>Ll(this.await,()=>e);isOpen(){return this._isOpen}},Id=e=>new Fd(e??!1),Ld=BigInt(0),Rd={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:Ld,endTime:Ld,exit:Jl},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},zd=e=>Object.assign(Object.create(Rd),e),Bd=e=>e?Ao(e.annotations,Xs)?e._tag===`Span`?Bd(Oi(e.parent)):S():C(e):S(),Vd=(e,t,n)=>{let r=!e.getRef(ic)||n?.annotations&&Ao(n.annotations,Xs),i=n?.parent===void 0?n?.root?S():Bd(e.currentSpan):C(n.parent),a;if(r)a=zd({name:t,parent:i,annotations:To(n?.annotations??So(),Xs,!0)});else{let r=e.getRef(ec),o=e.getRef(Yd),s=e.getRef(ac),c=e.getRef(oc),l=e.getRef(sc),u=n?.level??e.getRef(Zs),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??So(),links:d,startTime:s?o.currentTimeNanosUnsafe():BigInt(0),kind:n?.kind??`internal`,root:n?.root??w(i),sampled:n?.sampled??(T(i)&&i.value.sampled===!1?!1:!ff(e.getRef(Qs),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},Hd=(e,t)=>(t=typeof t==`function`?t:ut,tu(rc,n=>({name:e,stack:t,parent:n}))),Ud=(e,t,n,r)=>il(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():Ld,t)}),Wd=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return Pr(t=>{let i=Vd(t,e,n),a=t.getRef(Yd),o=t.getRef(ac);return Zu(Gn(()=>r(i)),e=>Ud(i,e,a,o))})},Gd=ou(Js),Kd=function(){let e=ir(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=at;return t._tag===`Span`&&(n=hc(n),r=Hd(t.name,n?.captureStackTrace)),e?Gd(r(arguments[0]),t):e=>Gd(r(e),t)},qd=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=hc(arguments[2]);if(e){let e=arguments[0];return Wd(t,arguments[2],t=>Kd(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Wd(t,r?r(...a):i,t=>Kd(e,t,n))},Jd=(...e)=>Pr(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return fl}),Yd=Ro(`effect/Clock`,{defaultValue:()=>new Zd}),Xd=2**31-1,Zd=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=il(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return ef()}currentTimeNanos=il(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return $d()}monotonicTimeNanos=il(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(ps(e))}sleepMillis(e){return e<=0?sl:Number.isFinite(e)?yl(t=>{let n=e>Xd?this.sleepMillis(e-Xd):fl,r=setTimeout(()=>t(n),Math.min(e,Xd));return il(()=>clearTimeout(r))}):bl}},Qd=BigInt(1e6),$d=function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==`function`)return()=>e.bigint();if(typeof performance<`u`&&typeof performance.now==`function`)return()=>BigInt(Math.round(performance.now()*1e6));let t=BigInt(0);return()=>{let e=BigInt(Date.now())*Qd;return e>t&&(t=e),t}}(),ef=function(){let e=BigInt(1e9),t;return()=>{let n=$d(),r=BigInt(Date.now())*Qd;if(t===void 0)t=r-n;else{let i=t+n;(r>i?r-i:i-r)>e&&(t=r-n)}return t+n}}(),tf=e=>Pr(t=>e(t.getRef(Yd))),nf=e=>tf(t=>t.sleep(Yo(e))),rf=tf(e=>e.currentTimeMillis),af=`~effect/Cause/IllegalArgumentError`,of=class extends Lr(`IllegalArgumentError`){[af]=af;constructor(e){super({message:e})}},sf=`~effect/Cause/AsyncFiberError`,cf=class extends Lr(`AsyncFiberError`){[sf]=sf;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},lf=`~effect/Cause/UnknownError`,uf=class extends Lr(`UnknownError`){[lf]=lf;constructor(e,t){super({message:t,cause:e})}},df=Ro(`effect/Console/CurrentConsole`,{defaultValue:()=>globalThis.console}),ff=_i(hi(fi,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}})),pf=Ro(`effect/Loggers/CurrentLoggers`,{defaultValue:()=>new Set([Sf,Cf])}),mf=Ro(`effect/Logger/LogToStderr`,{defaultValue:ct}),hf={"~effect/Logger":{_Message:at,_Output:at},pipe(){return nt(this,arguments)}},gf=e=>{let t=Object.create(hf);return t.log=e,t},_f=e=>e.replace(/[\s="]/g,`_`),vf=(e,t)=>`${_f(e[0])}=${t-e[1]}ms`,yf=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];cr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?hr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=gr),Pr(r=>{let i=e??r.currentLogLevel;if(ff(r.minimumLogLevel,i))return fl;let a=r.getRef(Yd),o=r.getRef(pf);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return fl})},bf={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};bf.gray,bf.blue,bf.green,bf.yellow,bf.red,bf.bgBrightRed,bf.black;var xf=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,Sf=gf(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(zc(e));let o=t.getTime(),s=n.getRef(dc),c=``;for(let e of s)c+=` ${vf(e,o)}`;let l=n.getRef(cc);Object.keys(l).length>0&&a.push(l);let u=n.getRef(df);(n.getRef(mf)?u.error:u.log)(`[${xf(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Cf=gf(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Yd),a=t.getRef(cc),o=t.currentSpan;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))Cn(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=zc(e)),o.event(Vn(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),wf=cr,Tf=lr,Ef=xr,Df=hr,Of=gr,kf=_r,Af=e=>new mr(e),jf=e=>new vr(e),Mf=yc,Nf=Ec,Pf=Oc,Ff=Dc,If=Ac,Lf=wc,Rf=Tc,zf=zc,Bf=zr,Vf=Ur,Hf=of,Uf=Or,Wf=jr,Gf=Mr,Kf=Jl,qf=Gl,Jf=Kl,Yf={"~effect/Deferred":{_A:at,_E:at},pipe(){return nt(this,arguments)}},Xf=()=>{let e=Object.create(Yf);return e.resumes=void 0,e.effect=void 0,e},Zf=()=>il(()=>Xf()),Qf=e=>yl(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),il(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),$f=x(2,(e,t)=>il(()=>rp(e,t))),ep=e=>il(()=>tp(e)),tp=e=>e.effect!==void 0,np=x(2,(e,t)=>$f(e,Or(t))),rp=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},ip=x(2,(e,t)=>md(n=>Ll(Au(n(e)),e=>$f(t,e)))),ap=Pu,op=Wu,sp=qu,cp=Bu,lp=Vu,up=zu,dp=Fu,fp=`~effect/Layer`,pp=`~effect/Layer/MemoMap`,mp=(e,t)=>(e.observers++,Ml(Bu(t,t=>e.finalizer(t)),e.effect)),hp={[fp]:{_ROut:at,_E:at,_RIn:at},pipe(){return nt(this,arguments)}},gp=e=>{let t=Object.create(hp);return t.build=e,t},_p=e=>gp((t,n)=>{let r=up(n);return Zu(e(t,r),e=>e._tag===`Failure`?dp(r,e):fl)}),vp=e=>{let t=_p((n,r)=>n.getOrElseMemoize(t,r,e));return t},yp=(e,t,n,r)=>{let i=op(),a=Xf(),o={observers:1,effect:Qf(a),finalizer:n=>al(()=>(o.observers--,o.observers===0?(e.map.delete(t),dp(i,n)):fl))};return e.map.set(t,o),Bu(n,o.finalizer).pipe(Ll(()=>r(e,i)),Zu(e=>(o.effect=e,$f(a,e))))},bp=class{get[pp](){return pp}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?mp(n,t):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return al(()=>this.get(e,t)||yp(this,e,t,n))}},xp=()=>new bp,Sp=e=>new bp(e),Cp=class e extends ro()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=Do(t,e);return n?Sp(n):xp()}},wp=x(3,(e,t,n)=>ou(Vl(e.build(t,n),To(Cp,t)),Cp,t)),Tp=x(2,(e,t)=>Pr(n=>wp(e,Cp.forkOrCreate(n.context),t))),Ep=function(){return arguments.length===1?e=>Dp(wo(arguments[0],e)):Dp(wo(arguments[0],arguments[1]))},Dp=e=>gp(ot(tl(e))),Op=function(){return arguments.length===1?e=>kp(arguments[0],e):kp(arguments[0],arguments[1])},kp=(e,t)=>Ap(Vl(t,t=>wo(e,t))),Ap=e=>vp((t,n)=>sp(e,n)),jp=e=>Ap(Al(e,So())),Mp=(e,t,n)=>{let r=up(n,`parallel`);return _d(e,e=>e.build(t,up(r,`sequential`)),{concurrency:e.length}).pipe(Vl(e=>Io(...e)))},Np=(...e)=>_p((t,n)=>Mp(e,t,n)),Pp=(e,t,n)=>_p((r,i)=>Ll(Array.isArray(t)?Mp(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(au(t),Vl(e=>n(e,t))))),Fp=x(2,(e,t)=>Pp(e,t,at)),Ip=x(2,(e,t)=>Pp(e,t,(e,t)=>Fo(t,e))),Lp=rf,Rp=`~effect/time/DateTime`,zp=`~effect/time/DateTime/TimeZone`,Bp={[Rp]:Rp,pipe(){return nt(this,arguments)},[zn](){return this.toString()},toJSON(){return xm(this).toJSON()}},Vp={...Bp,_tag:`Utc`,[Pt](){return Bt(this.epochMilliseconds)},[Qt](e){return qp(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${xm(this).toJSON()})`}},Hp={...Bp,_tag:`Zoned`,[Pt](){return Lt(Bt(this.epochMilliseconds))(Ft(this.zone))},[Qt](e){return qp(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&$t(this.zone,e.zone)},toString(){return`DateTime.Zoned(${Wm(this)})`}},Up={[zp]:zp,[zn](){return this.toString()}},Wp={...Up,_tag:`Named`,[Pt](){return Vt(`Named:${this.id}`)},[Qt](e){return Yp(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},Gp={...Up,_tag:`Offset`,[Pt](){return Vt(`Offset:${this.offset}`)},[Qt](e){return Yp(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${wm(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},Kp=(e,t,n)=>{let r=Object.create(Hp);return r.epochMilliseconds=e,r.zone=t,Object.defineProperty(r,"partsUtc",{value:n,enumerable:!1,writable:!0}),Object.defineProperty(r,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(r,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),r},qp=e=>At(e,Rp),Jp=e=>qp(e[0]),Yp=e=>At(e,zp),Xp=e=>Yp(e)&&e._tag===`Named`,Zp=e=>e._tag===`Utc`,Qp=e=>e._tag===`Zoned`,$p=_n((e,t)=>e.epochMilliseconds===t.epochMilliseconds),em=ui((e,t)=>e.epochMilliseconds<t.epochMilliseconds?-1:+(e.epochMilliseconds>t.epochMilliseconds)),tm=e=>{let t=Object.create(Vp);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},nm=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Hf(`Invalid date`);return tm(t)},rm=e=>{if(qp(e))return e;if(e instanceof Date)return nm(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return nm(new Date(e.epochMilliseconds));let t=new Date(0);return Am(t,e),nm(t)}return typeof e==`string`&&!im(e)?nm(new Date(e+`Z`)):nm(new Date(e))},im=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),am=-864e13+432e5,om=864e13-504e5,sm=(e,t)=>{let n=t?.timeZone;if(n===void 0&&qp(e)&&Qp(e))return e;let r=rm(e);if(r.epochMilliseconds<am||r.epochMilliseconds>om)throw RangeError(`Epoch millis out of range: ${r.epochMilliseconds}`);n===void 0&&typeof e==`object`&&`timeZoneId`in e&&(n=e.timeZoneId);let i;if(n===void 0)i=gm(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(Yp(n))i=n;else if(typeof n==`number`)i=gm(n);else{let e=ym(n);if(w(e))throw new Hf(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?Mm(r.epochMilliseconds,i,t?.disambiguation??`compatible`):Kp(r.epochMilliseconds,i,r.partsUtc)},cm=ki(rm),lm=Vl(Lp,tm),um=e=>tm(e.epochMilliseconds),dm=x(Jp,(e,t,n)=>n?.adjustForTimeZone===!0?Mm(e.epochMilliseconds,t,n?.disambiguation??`compatible`):Kp(e.epochMilliseconds,t,e.partsUtc)),fm=new Map,pm={day:`numeric`,month:`numeric`,year:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},mm=e=>{let t=e.resolvedOptions().timeZone;if(fm.has(t))return fm.get(t);let n=Object.create(Wp);return n.id=t,n.format=e,fm.set(t,n),n},hm=e=>{if(fm.has(e))return fm.get(e);try{return mm(new Intl.DateTimeFormat(`en-US`,{...pm,timeZone:e}))}catch{throw new Hf(`Invalid time zone: ${e}`)}},gm=e=>{let t=Object.create(Gp);return t.offset=e,t},_m=ki(hm),vm=/^(?:GMT|[+-])/,ym=e=>{if(vm.test(e)){let t=Pm(e);return t===null?S():C(gm(t))}return _m(e)},bm=x(Jp,(e,t,n)=>Ai(_m(t),t=>dm(e,t,n))),xm=e=>new Date(e.epochMilliseconds),Sm=e=>{if(e._tag===`Utc`)return new Date(e.epochMilliseconds);if(e.zone._tag===`Offset`)return new Date(e.epochMilliseconds+e.zone.offset);if(e.adjustedEpochMilliseconds!==void 0)return new Date(e.adjustedEpochMilliseconds);let t=e.zone.format.formatToParts(e.epochMilliseconds).filter(e=>e.type!==`literal`),n=new Date(0);return n.setUTCFullYear(Number(t[2].value),Number(t[0].value)-1,Number(t[1].value)),n.setUTCHours(Number(t[3].value),Number(t[4].value),Number(t[5].value),Number(t[6].value)),e.adjustedEpochMilliseconds=n.getTime(),n},Cm=e=>Sm(e).getTime()-Em(e),wm=e=>{let t=Math.abs(e),n=Math.floor(t/36e5),r=Math.round(t%36e5/6e4);return r===60&&(n+=1,r=0),`${e<0?`-`:`+`}${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`},Tm=e=>wm(Cm(e)),Em=e=>e.epochMilliseconds,Dm=e=>({millisecond:e.getUTCMilliseconds(),second:e.getUTCSeconds(),minute:e.getUTCMinutes(),hour:e.getUTCHours(),day:e.getUTCDate(),weekDay:e.getUTCDay(),month:e.getUTCMonth()+1,year:e.getUTCFullYear()}),Om=e=>e._tag===`Utc`?km(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=Lm(e,Dm)),e.partsAdjusted),km=e=>(e.partsUtc===void 0&&(e.partsUtc=Rm(e,Dm)),e.partsUtc),Am=(e,t)=>{if(t.year!==void 0&&e.setUTCFullYear(t.year),t.month!==void 0&&e.setUTCMonth(t.month-1),t.day!==void 0&&e.setUTCDate(t.day),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},jm=864e5,Mm=(e,t,n)=>{if(t._tag===`Offset`)return Kp(e-t.offset,t);let r=Fm(e-jm,e,t),i=Fm(e+jm,e,t);if(r===i)return Kp(e-r,t);let a=r<i,o=r-i;if(a){if(Fm(e-i,e,t)===i)return Kp(e-i,t);let a=Kp(e-r,t);if(e!==Sm(a).getTime())switch(n){case`reject`:{let n=new Date(e).toISOString();throw RangeError(`Gap time: ${n} does not exist in time zone ${t.id}`)}case`earlier`:return Kp(e-i,t);case`compatible`:case`later`:return a}return a}if(Fm(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||Fm(e-r+o,e+o,t)===r)return Kp(e-r,t);if(n===`reject`){let n=new Date(e).toISOString();throw RangeError(`Ambiguous time: ${n} occurs twice in time zone ${t.id}`)}}return Kp(e-i,t)},Nm=/([+-])(\d{2}):(\d{2})$/,Pm=e=>{let t=Nm.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},Fm=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=Pm(r);return i===null?Cm(Kp(t,n)):i},Im=x(Jp,(e,t,n)=>{if(e._tag===`Utc`){let n=xm(e);return t(n),tm(n.getTime())}let r=Sm(e),i=new Date(r.getTime());return t(i),Mm(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),Lm=x(2,(e,t)=>t(Sm(e))),Rm=x(2,(e,t)=>t(xm(e))),zm=(e,t)=>{e.setTime(e.getTime()+t)},Bm=x(2,(e,t)=>Im(e,e=>{if(t.milliseconds&&zm(e,t.milliseconds),t.seconds&&zm(e,t.seconds*1e3),t.minutes&&zm(e,t.minutes*60*1e3),t.hours&&zm(e,t.hours*60*60*1e3),t.days&&e.setUTCDate(e.getUTCDate()+t.days),t.weeks&&e.setUTCDate(e.getUTCDate()+t.weeks*7),t.months){let n=e.getUTCDate();e.setUTCMonth(e.getUTCMonth()+t.months+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}if(t.years){let n=e.getUTCDate(),r=e.getUTCMonth();e.setUTCFullYear(e.getUTCFullYear()+t.years,r+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}})),Vm=x(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return Bm(e,n)}),Hm=e=>xm(e).toISOString(),Um=e=>{let t=Sm(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${Tm(e)}`},Wm=e=>e.zone._tag===`Offset`?Um(e):`${Um(e)}[${e.zone.id}]`;globalThis.Number;var Gm=fi;globalThis.String;var Km=e=>e.toLowerCase(),qm=e=>e.length>0,Jm=`~effect/time/Cron`;function Ym(e){return{tz:e.tz,and:e.and,seconds:sa(e.seconds),minutes:sa(e.minutes),hours:sa(e.hours),days:sa(e.days),months:sa(e.months),weekdays:sa(e.weekdays)}}var Xm={[Jm]:Jm,[Qt](e){return Zm(e)&&hh(this,e)},[Pt](){return ft(Ft(this.tz),Lt(Ft(this.and)),Lt(Gt(sa(this.seconds))),Lt(Gt(sa(this.minutes))),Lt(Gt(sa(this.hours))),Lt(Gt(sa(this.days))),Lt(Gt(sa(this.months))),Lt(Gt(sa(this.weekdays))))},toObject(){return Ym(this)},toString(){return`Cron(${Mn(Ym(this))})`},toJSON(){let e=Ym(this);return e._id=`Cron`,e},[zn](){return this.toJSON()},pipe(){return nt(this,arguments)}},Zm=e=>At(e,Jm),Qm=e=>{let t=Object.create(Xm);t.seconds=eh.seconds(e.seconds??[0]),t.minutes=eh.minutes(e.minutes),t.hours=eh.hours(e.hours),t.days=eh.days(e.days),t.months=eh.months(e.months),t.weekdays=eh.weekdays(e.weekdays),t.and=e.and===!0,t.tz=Ti(e.tz);let n=Array.from(t.seconds),r=Array.from(t.minutes),i=Array.from(t.hours),a=Array.from(t.days),o=Array.from(t.months),s=Array.from(t.weekdays);return t.first={second:n[0]??0,minute:r[0]??0,hour:i[0]??0,day:a[0]??1,month:(o[0]??1)-1,weekday:s[0]??0},t.last={second:n[n.length-1]??59,minute:r[r.length-1]??59,hour:i[i.length-1]??23,day:a[a.length-1]??31,month:(o[o.length-1]??12)-1,weekday:s[s.length-1]??6},t.next={second:nh.next.second(n),minute:nh.next.minute(r),hour:nh.next.hour(i),day:nh.next.day(a),month:nh.next.month(o),weekday:nh.next.weekday(s)},t.prev={second:nh.prev.second(n),minute:nh.prev.minute(r),hour:nh.prev.hour(i),day:nh.prev.day(a),month:nh.prev.month(o),weekday:nh.prev.weekday(s)},t},$m=(e,t,n,r=e=>e)=>i=>{let a=[];for(let o of i){if(!Number.isInteger(o)||o<t||o>n)throw RangeError(`${e} must contain only integers between ${t} and ${n}`);a.push(r(o))}return new Set(xa(a,Gm))},eh={seconds:$m(`seconds`,0,59),minutes:$m(`minutes`,0,59),hours:$m(`hours`,0,23),days:$m(`days`,1,31),months:$m(`months`,1,12),weekdays:$m(`weekdays`,0,7,e=>e===7?0:e)},th=(e,t)=>n=>{let r=Array(e).fill(void 0);if(n.length===0)return r;let i;if(t===`next`){let t=n.length-1;for(let a=e-1;a>=0;a--){for(;t>=0&&n[t]>=a;)i=n[t--];r[a]=i}}else{let t=0;for(let a=0;a<e;a++){for(;t<n.length&&n[t]<=a;)i=n[t++];r[a]=i}}return r},nh={prev:{second:th(60,`prev`),minute:th(60,`prev`),hour:th(24,`prev`),day:th(32,`prev`),month:th(13,`prev`),weekday:th(7,`prev`)},next:{second:th(60,`next`),minute:th(60,`next`),hour:th(24,`next`),day:th(32,`next`),month:th(13,`next`),weekday:th(7,`next`)}},rh=`~effect/time/Cron/CronParseError`,ih=class extends Ms(`CronParseError`){[rh]=rh},ah=(e,t)=>{let n=e.trim().split(/\s+/).filter(qm);if(n.length!==5&&n.length!==6)return Bi(new ih({message:`Invalid number of segments in cron expression`,input:e}));n.length===5&&n.unshift(`0`);let[r,i,a,o,s,c]=n;return Yi({tz:t===void 0||Yp(t)?zi(t):Vi(ym(t),()=>new ih({message:`Invalid time zone in cron expression`,input:t})),seconds:Sh(r,gh),minutes:Sh(i,_h),hours:Sh(a,vh),days:Sh(o,yh),months:Sh(s,bh),weekdays:Sh(c,xh)}).pipe(Ki(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>Qm({tz:e,seconds:t.values,minutes:n.values,hours:r.values,days:i.values,months:a.values,weekdays:o.values,and:(i.wildcard||o.wildcard)&&i.values.size!==0&&o.values.size!==0})))},oh=(e,t)=>Ji(ah(e,t)),sh=(e,t)=>{let n=sm(t,{timeZone:Oi(e.tz)}).pipe(Om);return e.seconds.size!==0&&!e.seconds.has(n.second)||e.minutes.size!==0&&!e.minutes.has(n.minute)||e.hours.size!==0&&!e.hours.has(n.hour)||e.months.size!==0&&!e.months.has(n.month)?!1:e.days.size===0&&e.weekdays.size===0?!0:e.and?(e.days.size===0||e.days.has(n.day))&&(e.weekdays.size===0||e.weekdays.has(n.weekDay)):e.weekdays.size===0?e.days.has(n.day):e.days.size===0?e.weekdays.has(n.weekDay):e.days.has(n.day)||e.weekdays.has(n.weekDay)},ch=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),lh=(e,t)=>dh(e,t,`next`),uh=(e,t)=>dh(e,t,`prev`),dh=(e,t,n)=>{let r=Oi(e.tz),i=sm(t??new Date,{timeZone:r}),a=n===`prev`,o=a?-1:1,s=e[n],c=a?e.last:e.first,l=a?(e,t)=>e<t:(e,t)=>e>t,u=r!==void 0&&Xp(r)&&r.id===`UTC`?dt:e=>{let t=sm(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(Sm),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)};return xm(Im(i,t=>{t.setUTCSeconds(t.getUTCSeconds()+o,0);for(let n=0;n<1e4;n++){if(e.seconds.size!==0){let e=t.getUTCSeconds(),n=s.second[e];if(n===void 0){t.setUTCMinutes(t.getUTCMinutes()+o,c.second),u(t);continue}if(l(n,e)){t.setUTCSeconds(n),u(t);continue}}if(e.minutes.size!==0){let e=t.getUTCMinutes(),n=s.minute[e];if(n===void 0){t.setUTCHours(t.getUTCHours()+o,c.minute,c.second),u(t);continue}if(l(n,e)){t.setUTCMinutes(n,c.second),u(t);continue}}if(e.hours.size!==0){let e=t.getUTCHours(),n=s.hour[e];if(n===void 0){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(c.hour,c.minute,c.second),u(t);continue}if(l(n,e)){t.setUTCHours(n,c.minute,c.second),u(t);continue}}if(e.weekdays.size!==0||e.days.size!==0){if(e.and){let n=e.days.size===0||e.days.has(t.getUTCDate()),r=e.weekdays.size===0||e.weekdays.has(t.getUTCDay());if(!n||!r){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(c.hour,c.minute,c.second),u(t);continue}}else{let n=a?-1/0:1/0,r=a?-1/0:1/0;if(e.weekdays.size!==0){let e=t.getUTCDay(),r=s.weekday[e];n=r===void 0?a?c.weekday-7-e:7-e+c.weekday:r-e}if(e.days.size!==0&&n!==0){let e=t.getUTCDate(),n=s.day[e];if(n===void 0){if(a){let e=new Date(t);e.setUTCDate(0);let n=s.day[e.getUTCDate()];if(n===void 0&&(e.setUTCDate(0),n=s.day[e.getUTCDate()]),n===void 0)throw Error(`Unable to find cron date`);e.setUTCDate(n),r=(e.getTime()-t.getTime())/864e5}else r=ch(t)-e+c.day}else r=!a&&n>ch(t)?ch(t)-e+c.day:n-e}let i=a?Math.max(n,r):Math.min(n,r);if(i!==0){t.setUTCDate(t.getUTCDate()+i),t.setUTCHours(c.hour,c.minute,c.second),u(t);continue}}}if(e.months.size!==0){let n=t.getUTCMonth()+1,r=s.month[n],i=n=>{let r=ch(new Date(Date.UTC(t.getUTCFullYear(),n+1,0)));return e.days.size!==0&&e.weekdays.size===0?a?s.day[r]??r:c.day:a?r:1};if(r===void 0){t.setUTCFullYear(t.getUTCFullYear()+o),t.setUTCMonth(c.month,i(c.month)),t.setUTCHours(c.hour,c.minute,c.second),u(t);continue}if(l(r,n)){let e=r-1;t.setUTCMonth(e,i(e)),t.setUTCHours(c.hour,c.minute,c.second),u(t);continue}}return}throw Error(`Unable to find cron date`)}))},fh=_n((e,t)=>$t(e.tz,t.tz)&&e.and===t.and&&mh(e.seconds,t.seconds)&&mh(e.minutes,t.minutes)&&mh(e.hours,t.hours)&&mh(e.days,t.days)&&mh(e.months,t.months)&&mh(e.weekdays,t.weekdays)),ph=xn(yn()),mh=(e,t)=>ph(sa(e),sa(t)),hh=x(2,(e,t)=>fh(e,t)),gh={min:0,max:59},_h={min:0,max:59},vh={min:0,max:23},yh={min:1,max:31},bh={min:1,max:12,aliases:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12}},xh={min:0,max:7,normalize:e=>e===7?0:e,aliases:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}},Sh=(e,t)=>{let n=new Set,r=e.split(`,`),i=Ch(r[0]),a=i[0]===`*`,o=t.normalize??(e=>e),s=a&&(i[1]===void 0||i[1]===1)?dt:e=>{n.add(o(e))};for(let n=0;n<r.length;n++){let a=r[n],[o,c]=n===0?i:Ch(a);if(c!==void 0){if(!Number.isInteger(c))return Bi(new ih({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return Bi(new ih({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return Bi(new ih({message:`Expected step value to be less than or equal to ${t.max}`,input:e}))}if(o===`*`){if(n===0&&(c===void 0||c===1))continue;for(let e=t.min;e<=t.max;e+=c??1)s(e)}else{let[n,r]=wh(o,t.aliases);if(!Number.isInteger(n))return Bi(new ih({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return Bi(new ih({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(r===void 0)for(let e=n;e<=(c===void 0?n:t.max);e+=c??1)s(e);else{if(!Number.isInteger(r))return Bi(new ih({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return Bi(new ih({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return Bi(new ih({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return zi({values:n,wildcard:a})},Ch=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),Eh.test(n)?Number(n):NaN]}return[e,void 0]},wh=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[Th(e,t),void 0]:[Th(e.slice(0,n),t),Th(e.slice(n+1),t)]};function Th(e,t){return t?.[Km(e)]??(Eh.test(e)?Number(e):NaN)}var Eh=/^\d+$/,Dh=x(2,(e,t)=>du(e,jh,e=>t(e))),Oh=e=>e.reasons.some(kh),kh=e=>e._tag===`Fail`&&Bf(e.error),Ah=e=>{let t,n=!1;for(let r of e.reasons)kh(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Bi(e):n?Bi(Df(e.reasons.filter(e=>!kh(e)))):zi(t)},jh=e=>{let t=Ah(e);return Wi(t)?t:zi(t.success.value)},Mh=e=>{let t=Ah(e);return Wi(t)?Wf(t.failure):Uf(t.success.value)},Nh=x(2,(e,t)=>Tu(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Ah(e);return Wi(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Ph=`~effect/Schedule`,Fh=Ro(`effect/Schedule/CurrentMetadata`,{defaultValue:ot({input:void 0,output:void 0,duration:rs,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),Ih={[Ph]:{_Out:at,_In:at,_Env:at},pipe(){return nt(this,arguments)}},Lh=e=>At(e,Ph),Rh=e=>{let t=Object.create(Ih);return t.step=e,t},zh=()=>{let e=0,t,n;return(r,i)=>{n===void 0&&(n=r);let a=r-n,o=t===void 0?0:r-t;return t=r,{input:i,attempt:++e,start:n,now:r,elapsed:a,elapsedSincePrevious:o}}},Bh=e=>Rh(Vl(e,e=>{let t=zh();return(n,r)=>e(t(n,r))})),Vh=e=>lu(e.step,e=>tl(()=>nl(e))),Hh=e=>tf(t=>Vl(Vh(e),e=>{let n=zh();return r=>al(()=>{let i=t.currentTimeMillisUnsafe();return Ll(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,Al(nf(t),a)})})})),Uh=(e,t=2)=>{let n=ps(Yo(e));return Bh(tl(e=>{let r=ss(n*t**(e.attempt-1));return tl([r,r])}))},Wh=e=>Rh(Vl(Vh(e),e=>(t,n)=>Nh(e(t,n),{onSuccess:e=>tl([n,e[1]]),onFailure:nl,onDone:()=>Vf(n)}))),Gh=e=>{let t=Yo(e);return Bh(tl(e=>tl([e.attempt-1,t])))},Kh=x(2,(e,t)=>Rh(Vl(Vh(e),e=>{let n=zh();return(r,i)=>Ll(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return Ll(ir(s)?s:tl(s),t=>t?tl(e):Vf(a))})}))),qh=Gh(rs),Jh=(e,t,n)=>Ju(r=>Ll(n?.local?wp(t,xp(),r):Tp(t,r),t=>au(e,t))),Yh=x(e=>ir(e[0]),(e,t,n)=>bo(t)?au(e,t):Jh(e,Array.isArray(t)?Np(...t):t,n)),Xh=x(3,(e,t,n)=>Ll(Hh(t),t=>{let r=Fh.defaultValue(),i,a=fu(al(()=>ou(e,Fh,r)),e=>(i=e,Ll(t(e),e=>(r=e,a))));return Dh(a,e=>Gn(()=>n(i,e)))})),Zh=x(2,(e,t)=>Xh(e,typeof t==`function`?t(at):Lh(t)?t:$h(t),rl)),Qh=Wh(qh),$h=e=>{let t=e.schedule?Wh(e.schedule):Qh;return e.while&&(t=Kh(t,({input:t})=>{let n=e.while(t);return ir(n)?n:tl(n)})),e.until&&(t=Kh(t,({input:t})=>{let n=e.until(t);return ir(n)?Vl(n,e=>!e):tl(!n)})),e.times!==void 0&&(t=Kh(t,({attempt:t})=>tl(t<=e.times))),t},eg=ir,tg=hd,ng=_d,rg=ml,ig=hl,D=tl,ag=cl,og=al,sg=il,cg=fl,lg=bl,O=xl,ug=rl,dg=nl,fg=ll,pg=ul,mg=pl,hg=Pr,gg=ol,k=Ll,_g=Ml,vg=Nl,yg=wu,bg=Au,xg=Vl,Sg=Al,Cg=jl,wg=Pl,Tg=fu,Eg=vu,Dg=yu,Og=lu,kg=pu,Ag=bu,jg=Su,Mg=hu,Ng=Zh,Pg=Cu,Fg=nf,Ig=Fl,Lg=Il,Rg=Sd,zg=Ou,Bg=Tu,Vg=nu,Hg=iu,Ug=Yh,Wg=au,Gg=$l,Kg=eu,qg=ou,Jg=Yu,Yg=rd,Xg=Qu,Zg=ed,Qg=Zu,$g=od,e_=sd,t_=nd,n_=cd,r_=md,i_=cu,A=Jd,a_=Wd,o_=qd,s_=Kd,c_=Td,l_=Dd,u_=Ed,d_=kd,f_=Md,p_=jd,m_=Sl,j=Tl,h_=yf(`Warn`),g_=yf(`Error`),M=yf(`Info`),N=yf(`Debug`),__=Hl,v_=Ul,y_=Wl,b_=Bl,x_=Dl;function S_(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function C_(e){return t=>S_(t)?.[e]}var w_=`~structural`,T_=`~sentinels`,E_=`~constructor`,D_=C_(`brands`),O_=pt(e=>{let t=S_(e)?.identifier;return typeof t==`string`?t:e.getExpected(O_)}),k_=Symbol(),A_=Uf,j_=A_(k_),M_=A_(k_),N_=e=>e===k_?S():C(e),P_=e=>e._tag===`None`?j_:A_(e.value),F_=`~effect/SchemaIssue/Issue`;function I_(e){return At(e,F_)&&e[F_]===F_}function L_(e){return Object.hasOwn(e,`input`)}var R_=class{[F_]=F_;constructor(e,t){t?.reportInput===!0&&e!==k_&&(this.input=e)}},z_=class extends R_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},B_=class extends R_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},V_=class extends R_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},H_=class extends R_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},U_=class extends R_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},W_=class extends R_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},G_=class extends R_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},K_=class extends R_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function q_(e,t,n,r,i){return new W_(e,[new V_([t],n)],r,i)}var J_=class extends R_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},Y_=class extends R_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},X_=class extends R_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function Z_(e,t,n){if(I_(e))return e;if(typeof e==`string`)return new K_({message:e},t,n);let r=typeof e.issue==`string`?new K_({message:e.issue},t,n):e.issue;return new V_(e.path,r)}function Q_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new K_(void 0,t,n):Z_(e,t,n)}function $_(e,t,n,r){return Array.isArray(t)?pa(t)?t.length===1?Z_(t[0],n,r):new W_(e,Na(t,e=>Z_(e,n,r)),n,r):void 0:Q_(t,n,r)}var ev=e=>{let t=dv(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return av(O_(e.ast),e);case`InvalidValue`:{let t=iv(e);if(t!==void 0)return av(t,e);let n=rv(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=rv(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=rv(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},tv=e=>dv(e.issue)??dv(e);function nv(e){return t=>({issues:ov(t,[],e?.leafHook??ev,e?.checkHook??tv)})}function rv(e){return L_(e)?Mn(e.input):void 0}function iv(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function av(e,t){let n=rv(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function ov(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return ov(e.issue,t,n,r);let a=iv(e.issue);return[{path:t,message:a===void 0?av(sv(e.filter),e):av(a,e.issue)}]}case`Encoding`:return ov(e.issue,t,n,r);case`Pointer`:return ov(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>ov(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:dv(e)??av(O_(e.ast),e)}]:e.issues.flatMap(e=>ov(e,t,n,r));default:return[{path:t,message:n(e)}]}}function sv(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>sv(e)).join(` & `)}}function cv(){return e=>uv(e,``)}var lv=cv();function uv(e,t){let n;switch(e._tag){case`Filter`:{let r=tv(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return uv(e.issue,t);let r=iv(e.issue);n=r===void 0?av(sv(e.filter),e):av(r,e.issue)}break}case`Encoding`:return uv(e.issue,t);case`Pointer`:return uv(e.issue,t+Fn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>uv(e,t)).join(`
14
+ `);n=dv(e)??av(O_(e.ast),e);break;default:n=ev(e)}return t?`${n}\n at ${t}`:n}function dv(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return dv(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function fv(e){let t;for(let n of e.reasons){if(!Ef(n)||!I_(n.error))return;t??=n.error}return t}function pv(e,t){let n=fv(e);if(n===void 0)throw Error(t,{cause:e});return n}var mv=qp,hv=Zp,gv=$p,_v=em,vv=nm,yv=rm,bv=cm,xv=lm,Sv=um,Cv=_m,wv=bm,Tv=xm,Ev=Sm,Dv=Em,Ov=Vm,kv=Hm,Av=Wm,jv=class e extends it{run;constructor(e){super(),this.run=e}map(t){return new e((e,n)=>this.run(e,n).pipe(__(Ai(t))))}compose(t){return Fv(this)?t:Fv(t)?this:new e((e,n)=>this.run(e,n).pipe(b_(e=>t.run(e,n))))}};function Mv(e){return new jv((t,n)=>ug(e(t,n)))}function Nv(e){return Mv((t,n)=>{let r={message:e(t)};return T(t)?new J_(r,t.value,n):new J_(r)})}var Pv=new jv(D);function Fv(e){return e.run===Pv.run}function Iv(){return Pv}function Lv(e){return new jv((t,n)=>w(t)?ag:e(t.value,n))}function Rv(e){return Bv(Ai(e))}function zv(e){return Lv((t,n)=>e(t,n).pipe(__(C)))}function Bv(e){return new jv(t=>D(e(t)))}function Vv(){return new jv(()=>ag)}function Hv(e){return new jv(t=>{let n=Fi(t,wt);return T(n)?D(n):__(e,C)})}function Uv(){return Rv(globalThis.String)}function Wv(){return Rv(globalThis.Number)}function Gv(){return Rv(globalThis.BigInt)}function Kv(e){return Lv((t,n)=>mg({try:()=>C(JSON.parse(t,e?.reviver)),catch:()=>new K_({expected:`a valid JSON string`},t,n)}))}function qv(e){return Lv((t,n)=>mg({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return C(n)},catch:()=>new K_({expected:`a JSON-serializable value`},t,n)}))}function Jv(){return Rv(Fs)}function Yv(){return zv((e,t)=>v_(gg(Is(e)),()=>new K_({expected:`a valid Base64 string`},e,t)))}var Xv=`~effect/SchemaTransformation/Transformation`,Zv=class e{[Xv]=Xv;_tag=`Transformation`;decode;encode;constructor(e,t){this.decode=e,this.encode=t}flip(){return new e(this.encode,this.decode)}compose(t){return new e(this.decode.compose(t.decode),t.encode.compose(this.encode))}};function Qv(e){return At(e,Xv)&&e[Xv]===Xv}var $v=e=>Qv(e)?e:new Zv(e.decode,e.encode);function ey(e){return new Zv(zv(e.decode),zv(e.encode))}function ty(e){return new Zv(Rv(e.decode),Rv(e.encode))}function ny(e){return new Zv(Bv(e.decode),Bv(e.encode))}var ry=new Zv(Iv(),Iv());function iy(){return ry}var ay=new Zv(Wv(),Uv()),oy=new Zv(Gv(),Uv()),sy=e=>Ot(e)&&typeof e.message==`string`,cy=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:fy(e.cause)}):Error(e.message);return typeof e.name==`string`&&e.name!==`Error`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t},ly=e=>{try{let t=Rn(e);return t===void 0?Mn(e):JSON.parse(t)}catch{return Mn(e)}},uy=(e,t,n)=>{let r={name:e.name,message:typeof e.message==`string`?e.message:``};return t?.includeStack&&typeof e.stack==`string`&&(r.stack=e.stack),!t?.excludeCause&&e.cause!==void 0&&(r.cause=n(e.cause)),r},dy=e=>{let t=new WeakSet,n=r=>{if(Mt(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=uy(r,e,n);return t.delete(r),i}return ly(r)};return n},fy=e=>sy(e)?cy(e):e,py=e=>ty({decode:fy,encode:dy(e)});function my(){return ty({decode:Ei,encode:Di})}function hy(){return ny({decode:C,encode:Mi})}var gy=ey({decode:(e,t)=>URL.canParse(e)?D(new URL(e)):ug(new K_({expected:`a valid URL string`},e,t)),encode:e=>D(e.href)}),_y=new Zv(Yv(),Jv());function vy(e){return new Zv(Kv(e??{}),qv(e))}var yy=ey({decode:(e,t)=>E(bv(e),{onNone:()=>ug(new K_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>D(Sv(e))}),encode:e=>D(kv(e))});function by(e){return t=>t._tag===e}var xy=by(`Declaration`),Sy=by(`Null`),Cy=by(`Void`),wy=by(`Never`),Ty=by(`Literal`),Ey=by(`UniqueSymbol`),Dy=by(`Arrays`),Oy=by(`Objects`),ky=by(`Union`),Ay=by(`Suspend`),jy=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},My={},Ny=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Py=`~effect/Schema`,Fy=class{[Py]=Py;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},Iy=class e extends Fy{_tag=`Declaration`;typeParameters;run;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o}getParser(){let e;return(t,n)=>t===k_?j_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(t,n,r){let i=Zb(this.typeParameters,t);return i===this.typeParameters&&n===this.checks&&r===this.encodingChecks?this:new e(i,this.run,this.annotations,n,void 0,this.context,r)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},Ly=new class extends Fy{_tag=`Null`;getParser(){return mx(this,null)}getExpected(){return`null`}},Ry=class extends Fy{_tag=`Undefined`;getParser(){return mx(this,void 0)}toCodecJson(){return zb(this,[zy])}getExpected(){return`undefined`}},zy=new jy(Ly,new Zv(Rv(()=>void 0),Rv(()=>null))),By=new Ry,Vy=new class extends Fy{_tag=`Void`;getParser(){let e=A_(void 0);return t=>t===k_?j_:e}toCodecJson(){return zb(this,[zy])}getExpected(){return`void`}},Hy=new class extends Fy{_tag=`Never`;getParser(){return hx(this,Et)}getExpected(){return`never`}},Uy=new class extends Fy{_tag=`Unknown`;getParser(){return hx(this,Dt)}getExpected(){return`unknown`}},Wy=class extends Fy{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${Mn(e)}`);this.literal=e}getParser(){return mx(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Gy(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Gy(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Gy(e){let t=globalThis.String(e.literal);return zb(e,[new jy(new Wy(t),new Zv(Rv(()=>e.literal),Rv(()=>t)))])}var Ky=new class extends Fy{_tag=`String`;getParser(){return hx(this,_t)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Dx(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},qy=class extends Fy{_tag=`Number`;getParser(){return hx(this,vt)}matchKey(e,t){return this._match(yx,e,t)}matchPart(e,t){return this._match(vx,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Dx(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Jy(this.checks,`effect/schema/isFinite`)||Jy(this.checks,`effect/schema/isInt`))?this:zb(this,[Pb])}toCodecStringTree(){return this.toCodecJson()===this?zb(this,[Sx]):zb(this,[Cx])}getExpected(){return`number`}};function Jy(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Jy(e.checks,t))}var Yy=new qy,Xy=new class extends Fy{_tag=`Boolean`;getParser(){return hx(this,yt)}getExpected(){return`boolean`}},Zy=new class extends Fy{_tag=`BigInt`;getParser(){return hx(this,bt)}matchPart(e,t){if(!wx.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Dx(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return zb(this,[Ex])}getExpected(){return`bigint`}},Qy=class e extends Fy{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(ox(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(ox(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}return x_(function*(e,c){if(e===k_)return k_;if(!Array.isArray(e))return yield*ug(new G_(n,e,c));r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)})));let l=e.length,u={ast:n,getParser:s,input:e,len:l,tailThreshold:Math.max(a,l-o),output:new globalThis.Array(l),issues:void 0,options:c},d=$y(u,e,{concurrency:eb(c?.concurrency)?.concurrency,end:n.rest.length===0?a:Math.max(l,a+o)});if(d&&(yield*d),n.rest.length===0&&l>a)for(let t=a;t<=l-1;t++){let r=new U_(n,e[t],c),i=new V_([t],r);if(c.errors===`all`)u.issues?u.issues.push(i):u.issues=[i];else return yield*ug(new W_(n,[i],e,c))}return u.issues?yield*ug(new W_(n,u.issues,e,c)):u.output})}_rebuild(t,n,r){let i=Zb(this.elements,t),a=Zb(this.rest,t);return i===this.elements&&a===this.rest&&n===this.checks&&r===this.encodingChecks?this:new e(this.isMutable,i,a,this.annotations,n,void 0,this.context,r)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}},$y=bd()({onItem(e,t,n){let r=n<e.len?t:k_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step(e,t,n,r){if(n._tag===`Failure`)return tb(e,e.ast,r,n);let i=n===M_?t:n[Xn];if(i!==k_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(ox(t.ast))return;let n=new V_([r],new H_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Gf(new W_(e.ast,[n],e.input,e.options))}}}),eb=e=>(e=e===`unbounded`?1/0:e??1,e>1?{concurrency:e}:void 0),tb=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=fv(r.cause);if(i===void 0)return Wf(Pf(r.cause,r=>new W_(t,[new V_([n],r)],e.input,e.options)));let a=new V_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Gf(new W_(t,[a],e.input,e.options))},nb=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function rb(e,t,n=My){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(gx(ux(t)))}var ib=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ab(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ab);default:return!1}}function ob(e){return ab(e)&&ab(ux(e))}var sb=class{parameter;type;constructor(e,t){if(!ob(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,ox(t)&&!px(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},cb=class e extends Fy{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o;let s=e.map(e=>e.name).filter((e,t,n)=>n.indexOf(e)!==t);if(s.length>0)throw Error(`Duplicate identifiers: ${JSON.stringify(s)}. ts(2300)`)}getParser(e,t=e){let n=this,r=[];for(let e of n.propertySignatures)r.push(e.name);let i=r.length,a=n.indexSignatures.length,o=i&&a?new Set(r):void 0;if(!i&&!a)return hx(n,Tt);let s,c,l=(e,t,r,a,s)=>{if(s._tag===`Failure`)return tb(e,n,t,s)??Kf;let c=s===M_?a:s[Xn];if(r!==k_&&c!==k_){if(i&&(o.has(t)||o.has(r)))return Kf;Cn(e.out,r,c)}return Kf},u=(e,t,r,i)=>{if(!i){let n=r.parserKey(t,e.options);if(!zl(n))return k(bg(n),n=>u(e,t,r,n));i=n}if(i._tag===`Failure`)return tb(e,n,t,i)??Kf;let a=i===M_?t:i[Xn],o=e.input[t],s=r.parserValue(o,e.options);return zl(s)?l(e,t,a,o,s):k(bg(s),n=>l(e,t,a,o,n))},d=(e,t,n)=>{let r=e.input[t],i=n.parserValue(r,e.options);return zl(i)?l(e,t,t,r,i):k(bg(i),n=>l(e,t,t,r,n))},f=a?bd()({onItem:(e,[t,n])=>u(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return x_(function*(l,p){if(l===k_)return k_;if(typeof l!=`object`||!l||Array.isArray(l))return yield*ug(new G_(n,l,p));s||(s=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),c=a?n.indexSignatures.map(n=>({is:n,parserKey:e(gx(n.parameter)),parserValue:t(n.type)})):void 0);let m=l,h={},g={ast:n,input:m,out:h,issues:void 0,options:p},_=p.errors===`all`,v=p.onExcessProperty===`error`,y=p.onExcessProperty===`preserve`,ee;if(!a&&(v||y)){o??=new Set(r),ee=Reflect.ownKeys(m);for(let e=0;e<ee.length;e++){let t=ee[e];if(!o.has(t)){if(v){let e=new U_(n,m[t],p),r=new V_([t],e);if(_){g.issues?g.issues.push(r):g.issues=[r];continue}return yield*ug(new W_(n,[r],l,p))}Cn(h,t,m[t])}}}let b=eb(p?.concurrency);if(i){let e=lb(g,s,b);e&&(yield*e)}if(a&&!b)for(let e=0;e<a;e++){let t=c[e],n=t.is.parameter===Ky?d:u,r=t.is.parameter===Ky?Object.keys(m):rb(m,t.is.parameter,p);for(let e=0;e<r.length;e++){let i=n(g,r[e],t);if(!zl(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(f){let e=ja();for(let t=0;t<a;t++){let n=c[t],r=rb(m,n.is.parameter,p);for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=f(g,e,b);t&&(yield*t)}if(g.issues)return yield*ug(new W_(n,g.issues,l,p));if(p.propertyOrder===`original`){let e=(ee??Reflect.ownKeys(m)).concat(r),t={};for(let n of e)Object.hasOwn(h,n)&&Cn(t,n,h[n]);return t}return h})}_rebuild(t,n,r,i){let a=Zb(this.propertySignatures,e=>{let n=t(e.type);return n===e.type?e:new ib(e.name,n)}),o=Zb(this.indexSignatures,e=>{let r=n(e.parameter),i=t(e.type);return r===e.parameter&&i===e.type?e:new sb(r,i)});return a===this.propertySignatures&&o===this.indexSignatures&&r===this.checks&&i===this.encodingChecks?this:new e(a,o,this.annotations,r,void 0,this.context,i)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}},lb=bd()({onItem(e,t){if(!Object.hasOwn(e.input,t.name))return t.parser(k_,e.options);let n=e.input[t.name];return Cn(e.out,t.name,n),t.parser(n,e.options)},step(e,t,n){if(n._tag===`Failure`)return tb(e,e.ast,t.name,n);if(n===M_)return;let r=n[Xn];if(r!==k_)Cn(e.out,t.name,r);else if(delete e.out[t.name],!ox(t.type)){let n=new V_([t.name],new H_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Gf(new W_(e.ast,[n],e.input,e.options))}}});function ub(e,t){return e?t?[...e,...t]:e:t}function db(e,t,n){return new cb(Reflect.ownKeys(e).map(t=>new ib(t,e[t].ast)),[],n,t)}function fb(e){return e.ast}function pb(e,t=void 0){return new Qy(!1,e.map(e=>e.ast),[],void 0,t)}function mb(e,t,n){return new Cb(e.map(fb),t,void 0,n)}var hb=mt(e=>{for(;;){if(Ay(e))return Uy;let t=e.encoding;if(!t)return e.recur?.(hb,at)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==at))return Uy;e=t[t.length-1].to}});function gb(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(gb)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function _b(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[T_];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!ox(t)){if(Ty(t))return[{key:e.name,literal:t.literal}];if(Ey(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!ox(e)){if(Ty(e))return[{key:t,literal:e.literal}];if(Ey(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>_b(hb(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return _b(e.thunk())}}var vb=new WeakMap,yb=Object.freeze([]);function bb(e){let t=vb.get(e);if(t)return t;let n,r=0,i,a,o=!0;for(let t=0;t<e.length;t++){let s=e[t],c=hb(s);if(wy(c))continue;if(o){if(Ty(c)||Ey(c)){a??=new Map;let e=Ty(c)?c.literal:c.symbol,t=a.get(e);t||a.set(e,t=[]),t.push(s)}else o=!1}let l=_b(c);if(l.length){n??=new Map,r++;for(let{key:e,literal:r}of l){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=gb(c);for(let n of e)(i[n]??=[]).push(t)}}if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??yb;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=i;for(let[t,n]of i)a.set(t,Object.freeze(Array.from(n,t=>e[t])));t=(t,n)=>{if(kt(t)){let i=Object.hasOwn(t,r)?t[r]:void 0;if(i!==void 0)return a.get(i)??yb;if(n)return e}return yb}}else if(n){let a;for(let e of n)(!a||e[1][0].size>a[1][0].size)&&e[1][1].size===r&&(a=e);t=(t,r)=>{let o=i?.[t===null?`null`:Array.isArray(t)?`array`:typeof t]??yb;if(!kt(t))return o.map(t=>e[t]);let s=new Set(o),c;if(a){let[n,[i]]=a,l=Object.hasOwn(t,n),u=l?t[n]:void 0;if(l&&(!r||u!==void 0)){let t=i.get(u);if(!t)return o.map(t=>e[t]);for(let e of t)s.add(e);c=n}}if(c===void 0)for(let[e,[i,a]]of n){let n=Object.hasOwn(t,e),o=n?t[e]:void 0;if(n&&(!r||o!==void 0)){let e=i.get(o);if(e)for(let t of e)s.add(t)}else if(r)for(let e of a)s.add(e)}for(let[e,[i,a]]of n){if(e===c)continue;let n=Object.hasOwn(t,e),o=n?t[e]:void 0;if(n&&(!r||o!==void 0)){let e=i.get(o);for(let t of s)a.has(t)&&!e?.has(t)&&s.delete(t)}}return Array.from(s).sort((e,t)=>e-t).map(t=>e[t])}}else t=t=>(i?.[t===null?`null`:Array.isArray(t)?`array`:typeof t]??yb).map(t=>e[t]).filter(xb(t));return vb.set(e,t),t}function xb(e){return t=>{let n=hb(t);return n._tag===`Literal`?n.literal===e:n._tag!==`UniqueSymbol`||n.symbol===e}}function Sb(e,t,n=!1){return bb(t)(e,n)}var Cb=class e extends Fy{_tag=`Union`;types;mode;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.mode=t,this.encodingChecks=o}getParser(e,t){let n=this;return(r,i)=>{if(r===k_)return j_;let a=Sb(r,n.types,t!==void 0);if(a.length===1){let t=e(a[0])(r,i);return t._tag===`Success`?t:zl(t)?wb(n,t.cause,r,i):Og(t,e=>wb(n,e,r,i))}let o={ast:n,compile:e,input:r,out:void 0,successes:n.mode===`oneOf`?[]:void 0,issues:void 0,options:i},s=eb(i?.concurrency),c=Tb(o,a,s?{...s,orderedStep:!0}:void 0);return c?b_(c,e=>o.out===M_?D(r):o.out?o.out:ug(new Y_(n,o.issues??[],r,i))):o.out?o.out:ug(new Y_(n,o.issues??[],r,i))}}_rebuild(t,n,r){let i=Zb(this.types,t);return i===this.types&&n===this.checks&&r===this.encodingChecks?this:new e(i,this.mode,this.annotations,n,void 0,this.context,r)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=ux(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Ty);if(t.length>0)return`${Db(n.isMutable)}[ ${t.map(t=>e(t)+Ob(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Ty(e.type));if(t.length>0)return`{ ${t.map(t=>`${Db(t.type.context?.isMutable)}${Pn(t.name)}${Ob(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function wb(e,t,n,r){let i=fv(t);return i?Gf(new Y_(e,[i],n,r)):Wf(t)}var Tb=bd()({onItem(e,t){return e.compile(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=fv(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(t),Gf(new X_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(t);else return Kf}}}),Eb=new Cb([new Wy(`Infinity`),new Wy(`-Infinity`),new Wy(`NaN`)],`anyOf`);function Db(e){return e?``:`readonly `}function Ob(e){return e?`?`:``}var kb=class e extends it{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(t){return new e(this.run,{...this.annotations,...t},this.aborted)}abort(){return new e(this.run,this.annotations,!0)}and(e,t){return new Ab([this,e],t)}},Ab=class e extends it{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(t){return new e(this.checks,{...this.annotations,...t})}and(t,n){return new e([this,t],n)}};function jb(e,t,n=!1){return new kb((t,n,r)=>$_(n,e(t,n,r),t,r),t,n)}function Mb(e){return jb(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitrary:{constraint:{noInfinity:!0,noNaN:!0}},...e})}var Nb=Ub(Yy,[Mb()]),Pb=new jy(new Cb([Nb,Eb],`anyOf`),new Zv(Wv(),Rv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Fb(e,t){let n=e.source,r=new globalThis.RegExp(n,e.flags);return jb(e=>(r.lastIndex=0,r.test(e)),{expected:`a string matching the RegExp ${n}`,representation:{id:`effect/schema/isPattern`,payload:{source:n,flags:e.flags}},toJsonSchema:()=>({pattern:n}),arbitrary:{constraint:{patterns:[e.source]}},...t})}function Ib(e,t){let n=Object.getOwnPropertyDescriptors(e);return t(n),Object.create(Object.getPrototypeOf(e),n)}var Lb=new WeakMap;function Rb(e){return Lb.get(e)??e}function zb(e,t){return e.encoding===t?e:Ib(e,e=>{e.encoding.value=t})}function Bb(e,t){if(e.context===t)return e;let n=Rb(e);if(n.context===t)return n;let r=Ib(e,e=>{e.context.value=t});return Lb.set(r,n),r}function Vb(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Hb(e,ua(e.checks.slice(0,-1),n.annotate(t)))}return Ib(e,e=>{e.annotations.value={...e.annotations.value,...t}})}function Hb(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Ib(e,e=>{e.checks.value=t})}function Ub(e,t){return Hb(e,ub(e.checks,t))}function Wb(e,t){let n=t(e.to);return n===e.to?e:new jy(n,e.transformation)}function Gb(e,t){let n=e,r=n[n.length-1],i=Wb(r,t);return i===r?e:ua(e.slice(0,e.length-1),i)}function Kb(e){return t=>t.encoding?zb(t,Gb(t.encoding,e)):t}function qb(e,t){return Kb(e=>Bb(e,t))(e)}function Jb(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:zb(r,Gb(r.encoding,n))}return e(r)}return mt(n)}function Yb(e,t,n){let r=new jy(e,t);return zb(n,n.encoding?[...n.encoding,r]:[r])}function Xb(e,t){let n=D_(e);return Vb(e,{brands:n?[...n,t]:[t]})}function Zb(e,t){let n=!1,r=Array(e.length);for(let i=0;i<e.length;i++){let a=e[i],o=t(a);o!==a&&(n=!0),r[i]=o}return n?r:e}function Qb(e,t){return Bb(e,e.context?new Ny(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Ny(!1,!1,void 0,t))}var $b=mt(e=>ex(Bb(e,e.context?e.context.isOptional===!1?new Ny(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Ny(!0,!1)))),ex=Kb($b),tx=pt(e=>$b(new Cb([e,By],`anyOf`)));function nx(e,t){let n=new jy(Uy,new Zv(Hv(t),Iv()));return Bb(e,e.context?new Ny(e.context.isOptional,e.context.isMutable,n,e.context.annotations):new Ny(!1,!1,n))}function rx(e,t,n){return Yb(e,n,t)}function ix(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:St(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function ax(e,t){let{literals:n,parameters:r}=ix(e);return new cb(n.map(e=>new ib(e,t)),r.map(e=>new sb(e,t)))}function ox(e){return e.context?.isOptional??!1}function sx(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(sx)}function cx(e){function t(e){return sx(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return fa(n)?n:void 0}var lx=mt(e=>{if(e.encoding)return lx(zb(e,void 0));let t=e,n=t.recur?.(lx)??t,r=n.encodingChecks;if(r){let t=n===e?r:Dy(n)||Oy(n)||xy(n)&&n.typeParameters.length>0?cx(r):void 0;return Ib(n,e=>{e.encodingChecks.value=void 0,e.checks.value=ub(n.checks,t)})}return n}),ux=mt(e=>lx(fx(e)));function dx(e,t){let n=t,r=n.length,i=n[r-1],a=[new jy(fx(zb(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new jy(fx(n[e-1].to),n[e].transformation.flip()));let o=fx(i.to);return o.encoding?zb(o,[...o.encoding,...a]):zb(o,a)}var fx=pt(e=>{if(e.encoding)return dx(e,e.encoding);let t=e;return t.flip?.(fx)??t.recur?.(fx)??t});function px(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(px);default:return!1}}function mx(e,t){let n=A_(t);return(r,i)=>r===k_?j_:r===t?n:ug(new G_(e,r,i))}function hx(e,t){return(n,r)=>n===k_?j_:t(n)?M_:ug(new G_(e,n,r))}var gx=Jb(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(gx)}}),_x=Jb(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(_x)}}),vx=new globalThis.RegExp(`^${nb}$`),yx=new globalThis.RegExp(`^(?:${nb}|Infinity|-Infinity|NaN)$`);function bx(e){return Fb(vx,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:vx.source}),...e})}var xx=Ub(Ky,[bx()]),Sx=new jy(xx,ay),Cx=new jy(new Cb([xx,Eb],`anyOf`),ay),wx=new globalThis.RegExp(`^-?\\d+$`);function Tx(e){return Fb(wx,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:wx.source}),...e})}var Ex=new jy(Ub(Ky,[Tx({expected:`a string representing a bigint`})]),oy);function Dx(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Dx(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new z_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Ox(e){if(!xy(e))return;let t=e.annotations?.[E_];return Ct(t)?t(e.typeParameters):void 0}var kx=C_;function Ax(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function jx(e){return e===void 0||typeof e==`string`}function Mx(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function Nx(e){return Mx(e,Ax)}var Px=new Iy([],()=>(e,t,n)=>Nx(e)?M_:ug(new G_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Rx,toArbitrary:()=>e=>e.jsonValue()}),Fx=new jy(Px,iy()),Ix=new jy(new Cb([new Qy(!1,[],[Px]),new cb([],[new sb(Ky,Px)])],`anyOf`),iy());function Lx(e){return Mx(e,jx)}var Rx=new jy(new Iy([],()=>(e,t,n)=>Lx(e)?M_:ug(new G_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),iy()),zx=`~effect/collections/MutableHashMap`,Bx={[zx]:zx,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${Mn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:Bn(Array.from(this))}},[zn](){return this.toJSON()},pipe(){return nt(this,arguments)}},Vx=()=>{let e=Object.create(Bx);return e.backing=new Map,e.buckets=new Map,e},Hx=x(2,(e,t)=>{if(e.backing.has(t))return C(e.backing.get(t));if(Wx(t))return S();let n=Ux.get(e);if(n!==void 0)return e.backing.has(n)?C(e.backing.get(n)):S();let r=Ft(t),i=e.buckets.get(r);return i===void 0?S():Kx(e,i,t)}),Ux=new WeakMap,Wx=e=>typeof e!=`object`&&typeof e!=`function`,Gx=e=>e.backing.values(),Kx=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if($t(n,t[r])){let i=t[r];return Ux.set(n,i),C(e.backing.get(i))}return S()},qx=x(2,(e,t)=>T(Hx(e,t))),Jx=x(3,(e,t,n)=>{if(e.backing.has(t)||Wx(t))return e.backing.set(t,n),e;let r=Ux.get(e);if(r!==void 0&&e.backing.has(r))return e.backing.set(r,n),e;let i=Ft(t),a=e.buckets.get(i);return a===void 0?(e.buckets.set(i,[t]),e.backing.set(t,n),e):(r=Yx(a,t),r===void 0&&(a.push(t),r=t),e.backing.set(r,n),e)}),Yx=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if($t(t,e[n]))return Ux.set(t,e[n]),e[n]},Xx=x(2,(e,t)=>{if(Wx(t))return e.backing.delete(t),e;let n=Ux.get(e)??t,r=Ft(n),i=e.buckets.get(r);if(i===void 0)return e;for(let t=0,r=i.length;t<r;t++){let r=i[t];if(r===n||$t(n,r)){e.backing.delete(r),i.splice(t,1);break}}return i.length===0&&e.buckets.delete(r),e}),Zx=Xc,Qx=Qc,$x=$c,eS=el,tS=Id,nS=`~effect/MutableRef`,rS={[nS]:nS,...nr,toJSON(){return{_id:`MutableRef`,current:Bn(this.current)}}},iS=e=>{let t=Object.create(rS);return t.current=e,t},aS=x(2,(e,t)=>(e.current=t,e)),oS=Symbol.for(`effect/MutableList/Empty`),sS=()=>({head:void 0,tail:void 0,length:0}),cS=()=>({array:[],mutable:!0,offset:0,next:void 0}),lS=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=cS(),e.tail=e.tail.next):e.head=e.tail=cS(),e.tail.array.push(t),e.length++},uS=e=>{e.head=e.tail=void 0,e.length=0},dS=e=>{if(!e.head)return oS;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length&&(e.head.next?e.head=e.head.next:uS(e)),t},fS=`~effect/Queue`,pS=`~effect/Queue/Enqueue`,mS=`~effect/Queue/Dequeue`,hS={_A:at,_E:at},gS={[fS]:hS,[pS]:hS,[mS]:hS,...nr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:xS(this)}}},_S=e=>Pr(t=>{let n=Object.create(gS);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=sS(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},tl(n)}),vS=(e,t)=>al(()=>{if(e.state._tag!==`Open`)return SS;if(e.messages.length>=e.capacity)switch(e.strategy){case`dropping`:return SS;case`suspend`:return e.capacity<=0&&e.state.takers.size>0?(lS(e.messages,t),wS(e),CS):ES(e,t);case`sliding`:return dS(e.messages),lS(e.messages,t),CS}return lS(e.messages,t),TS(e),CS}),yS=e=>al(()=>bS(e)??Ml(OS(e),yS(e))),bS=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=dS(e.messages);return DS(e),Or(t)}if(e.capacity<=0&&e.state.offers.size>0){e.capacity=1,DS(e),e.capacity=0;let t=dS(e.messages);return DS(e),Or(t)}},xS=e=>e.state._tag===`Done`?0:e.messages.length,SS=Or(!1),CS=Or(!0),wS=e=>{if(e.scheduleRunning=!1,e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(e.state.takers.delete(t),t(Jl),e.messages.length===0)break}},TS=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>wS(e),0))},ES=(e,t)=>yl(n=>{if(e.state._tag!==`Open`)return n(SS);let r={_tag:`Single`,message:t,resume:n};return e.state.offers.add(r),il(()=>{e.state._tag===`Open`&&e.state.offers.delete(r)})}),DS=e=>{if(e.state._tag===`Done`)return Oh(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(kS(e,e.state.exit),Oh(e.state.exit.cause));let t=e.capacity-e.messages.length;for(let n of e.state.offers)if(t===0)break;else if(n._tag===`Single`)lS(e.messages,n.message),t--,n.resume(CS),e.state.offers.delete(n);else{for(;n.offset<n.remaining.length;n.offset++){if(t===0)return!1;lS(e.messages,n.remaining[n.offset]),t--}n.resume(Or([])),e.state.offers.delete(n)}return!1},OS=e=>yl(t=>e.state._tag===`Done`?t(e.state.exit):(e.state.takers.add(t),il(()=>{e.state._tag!==`Done`&&e.state.takers.delete(t)}))),kS=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},AS=e=>new MS(e),jS=(e,t,n)=>yl(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),il(()=>{e.waiters.delete(i)})}),MS=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=al(()=>this.free<e?jS(this,e,t):(this.taken+=e,tl(e)));return t}takeIfAvailable(e){return al(()=>this.free<e?tl(!1):(this.taken+=e,tl(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Pr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),fl))}release(e){return Pr(t=>tl(this.releaseUnsafe(t,e)))}get releaseAll(){return Pr(e=>tl(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>md(n=>{let r=al(()=>this.free<e?Ll(n(jS(this,e,fl)),()=>r):(this.taken+=e,Xu(n(t),()=>{this.releaseUnsafe(Gc(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>md(n=>this.free<e?cl:(this.taken+=e,Xu(n(jl(t)),()=>{this.releaseUnsafe(Gc(),e)},!0)))}},NS=e=>il(()=>new MS(e)),PS={"~effect/Channel":{_Env:at,_InErr:at,_InElem:at,_OutErr:at,_OutElem:at},pipe(){return nt(this,arguments)}},FS=e=>{let t=Object.create(PS);return t.transform=(t,n)=>Og(e(t,n),e=>D(dg(e))),t},IS=(e,t)=>FS((n,r)=>k(zS(e)(n,r),e=>t(e,r))),LS=e=>FS((t,n)=>e),RS=e=>FS(m_(function*(t,n){let r=up(n),i=e=>dp(r,Mh(e));return Zg(yield*Zg(e(t,n,r),i),i)})),zS=e=>e.transform,BS=e=>FS((t,n)=>og(()=>zS(e())(t,n))),VS=e=>LS(D(ug(e))),HS=e=>FS((t,n)=>US({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),US=e=>{let t=e.readable.getReader(),n=e.exit??iS(void 0),r=og(()=>n.current?n.current:Bg(ig({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??dg(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Vf():D(Ma(t))}));return Sg(lp(e.scope,e.releaseLockOnEnd?sg(()=>t.releaseLock()):rg(()=>t.cancel().catch(dt))),r)},WS=x(2,(e,t)=>IS(e,e=>sg(()=>{let n=0;return xg(e,e=>t(e,n++))}))),GS=x(2,(e,t)=>IS(e,e=>D(k(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return pa(i)?D(i):k(e,n)})))),KS=x(2,(e,t)=>FS((n,r)=>k(zS(e)(n,r),e=>zS(t)(e,r)))),qS=x(2,(e,t)=>RS((n,r,i)=>cp(i,t).pipe(_g(zS(e)(n,r))))),JS=x(2,(e,t)=>qS(e,e=>t)),YS=(e,t,n)=>og(()=>{let r=op();return Dh(k(zS(e)(Vf(),r),t),n||D).pipe(Qg(e=>dp(r,e)))}),XS=x(2,(e,t)=>FS((n,r)=>xg(Wg(zS(e)(n,r),t),Wg(t)))),ZS=x(2,(e,t)=>YS(e,e=>i_(k(e,t),{disableYield:!0}))),QS=e=>og(()=>{let t=S();return YS(e,e=>e.pipe(Cg,k(e=>(t=e,Vf()))),()=>D(t))}),$S=(e,t)=>zS(e)(Vf(),t);function eC(e){let t=fC(gC,lx(e.ast));return(e,n)=>t(e,n?.disableChecks?n?.parseOptions?{...n.parseOptions,disableChecks:!0}:{disableChecks:!0}:n?.parseOptions)}function tC(e){let t=eC(e);return(e,n)=>{let r=p_(t(e,n));return qf(r)?C(r.value):(pv(r.cause,`Option adapter can only return none for schema issues`),S())}}function nC(e){let t=eC(e);return(e,n)=>{let r=p_(t(e,n));if(qf(r))return r.value;let i=pv(r.cause,`Constructor adapter can only throw schema issues`);throw Error(`Schema validation failed`,{cause:i})}}function rC(e){return iC(e.ast)}function iC(e){let t=pC(dC(lx(e)));return e=>{let n=t(e,My);return qf(n)?!0:(pv(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}function aC(e,t){let n=dC(e.ast);return t===void 0?n:(e,r)=>n(e,lC(t,r))}function oC(e,t){return mC(aC(e,t))}var sC=oC;function cC(e,t){let n=dC(fx(e.ast));return t===void 0?n:(e,r)=>n(e,lC(t,r))}var lC=(e,t)=>t?{...e,...t}:e,uC=e=>e===k_?ug(new K_):D(e);function dC(e){return fC(hC,e)}function fC(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??My);return a===M_?D(r):zl(a)?a[`~effect/Effect/args`]===k_?uC(k_):a:b_(a,uC)}}function pC(e){return(t,n)=>p_(e(t,n))}function mC(e){let t=pC(e);return(e,n)=>{let r=t(e,n);return qf(r)?C(r.value):(pv(r.cause,`Option adapter can only return none for schema issues`),S())}}var hC=pt(e=>xC(e,hC)),gC=pt(e=>xC(e,gC,vC)),_C=pt(e=>xC(e,gC,vC,e.context?.constructorDefault));function vC(e){return e.context?.constructorDefault?_C(e):gC(e)}function yC(e,t,n,r){let i;if(zl(e)&&e._tag===`Success`){let a=N_(e===M_?t:e[Xn]);i=n._tag===`Transformation`?n.decode.run(a,r):n.decode(A_(a),r)}else i=n._tag===`Transformation`?b_(e,e=>n.decode.run(N_(e),r)):n.decode(__(e,N_),r);return zl(i)&&i._tag===`Success`?P_(i[Xn]):b_(i,P_)}function bC(e,t){let n;return(r,i)=>r===k_?j_:e.isConstructed(r)?M_:yC((n??=t(e.link.to))(r,i),r,e.link.transformation,i)}function xC(e,t,n,r){let i=n?Ox(e):void 0,a=i?bC(i,t):e.getParser(t,n),o=e.checks,s=r?e.encoding?[...e.encoding,r]:[r]:e.encoding,c=e.encodingChecks,l=(o?o[o.length-1].annotations:e.annotations)?.parseOptions;if(!s&&!o&&!c)return l?(e,t)=>a(e,lC(t,l)):a;let u,d=(t,n)=>{let r=a(t,n);if(c&&!n.disableChecks){if(zl(r)){if(r._tag===`Success`){let i=r===M_?t:r[Xn];if(t!==k_&&i!==k_){let i=Dx(c,t,void 0,e,n);i&&(r=ug(new W_(e,i,t,n)))}}}else r=k(r,r=>{if(t!==k_&&r!==k_){let r=Dx(c,t,void 0,e,n);if(r)return ug(new W_(e,r,t,n))}return D(r)})}if(o&&!n.disableChecks){if(zl(r)){if(r._tag===`Success`){let i=r===M_?t:r[Xn];if(i===k_)return r;let a=Dx(o,i,void 0,e,n);a&&(r=ug(new W_(e,a,i,n)))}}else r=k(r,t=>{if(t!==k_){let r=Dx(o,t,void 0,e,n);if(r)return ug(new W_(e,r,t,n))}return D(t)})}return r};return s?(n,r)=>{l&&(r=lC(r,l));let i=u??=s.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=s.length-1;e>=0;e--)if(o=yC(o,a,s[e].transformation,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[Xn],o=t(a,r)):o=b_(o,e=>{let n=t(e,r);return n===M_?A_(e):n})}if(o._tag===`Success`){let e=o[Xn],t=d(e,r);return t===M_?o:t}return o=Og(o,t=>fg(()=>Pf(t,t=>new B_(e,t,n,r)))),b_(o,e=>{let t=d(e,r);return t===M_?A_(e):t})}:l?(e,t)=>d(e,lC(t,l)):d}var SC=`~effect/Schema/Schema`,CC={[SC]:SC,pipe(){return nt(this,arguments)},annotate(e){return this.rebuild(Vb(this.ast,e))},annotateKey(e){return this.rebuild(Qb(this.ast,e))},check(...e){return this.rebuild(Ub(this.ast,e))}};function wC(e,t){function n(){}let r=Object.defineProperties(Object.setPrototypeOf(n,CC),Object.getOwnPropertyDescriptors({...t}));return r.ast=e,r.rebuild=e=>wC(e,t),r.makeEffect=eC(r),r.make=nC(r),r.makeOption=tC(r),r}var TC=x(2,(e,t)=>({...e,...t})),EC=x(2,(e,t)=>OC(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),DC=e=>e;function OC(e,t){let n={};for(let r of Reflect.ownKeys(e)){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;let i=t(r,e[r]);if(i){let[e,t]=i;Cn(n,e,t)}}return n}var kC=x(2,(e,t)=>e===void 0?void 0:t(e)),AC=new WeakMap,jC=e=>{if(AC.has(e))return AC.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},MC=`~effect/data/Redacted`,NC=e=>At(e,MC),PC=(e,t)=>{let n=Object.create(FC);return t?.label&&(n.label=t.label),AC.set(n,e),n},FC={[MC]:{_A:e=>e},label:void 0,...nr,toJSON(){return this.toString()},toString(){return`<redacted${_t(this.label)?`:`+this.label:``}>`},[Pt](){return Ft(AC.get(this))},[Qt](e){return NC(e)&&$t(AC.get(this),AC.get(e))}},IC=jC,LC=e=>_n((t,n)=>e(IC(t),IC(n))),RC=SC;function zC(){return(e,t,n)=>aw(new Iy(e.map(fb),e=>t(e.map(e=>aw(e))),n))}function BC(e,t){return zC()([],()=>(t,n,r)=>e(t)?D(t):ug(new G_(n,t,r)),t)}var VC=`~effect/SchemaError/SchemaError`,HC=class extends Ms(`SchemaError`){[VC]=VC;constructor(e){super({issue:e})}get message(){return lv(this.issue)}toString(){return`SchemaError(${this.message})`}};function UC(e){return At(e,VC)&&e[VC]===VC}function WC(e){return qf(e)?e.value:{issues:[{message:zf(e.cause)}]}}function GC(e,t){let n=aC(e),r={errors:`all`,...t?.parseOptions},i=nv(t),a=e=>{let t=new Es(`sync`),a=l_(zg(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?WC(o):new Promise(e=>{a.addObserver(t=>{e(WC(t))})})};if(`~standard`in e){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}var KC=rC;function qC(e,t){let n=aC(e,t);return(e,t)=>JC(n(e,t))}function JC(e){return Og(e,e=>fg(()=>Pf(e,e=>new HC(e))))}var YC=qC;function XC(e,t){let n;for(let r of e.reasons){if(!Ef(r)||!UC(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function ZC(e){let t=p_(e);if(qf(t))return t.value;throw XC(t.cause,`Sync adapter can only throw schema errors`)}var QC=oC,$C=sC;function ew(e,t){let n=qC(e,t);return(e,t)=>ZC(n(e,t))}function tw(e,t){let n=cC(e,t);return(e,t)=>JC(n(e,t))}var nw=tw;function rw(e,t){let n=tw(e,t);return(e,t)=>ZC(n(e,t))}var iw=rw,aw=wC;function ow(e){return At(e,RC)&&e[RC]===RC}var sw=DC(e=>aw($b(e.ast),{schema:e})),cw=DC(e=>{let t=kw(e);return aw(tx(e.ast),{schema:t})}),lw=DC(e=>aw(lx(e.ast),{schema:e})),uw=DC(e=>aw(ux(e.ast),{schema:e}));function dw(e){let t=aw(new Wy(e),{literal:e,transform(n){return t.pipe(Aw(dw(n),{decode:Rv(()=>n),encode:Rv(()=>e)}))}});return t}var fw=aw(Hy),pw=aw(Uy),mw=aw(Ly),hw=aw(By),P=aw(Ky),gw=aw(Yy),_w=aw(Xy),vw=aw(Zy),yw=aw(Vy);function bw(e,t){return aw(e,{fields:t,mapFields(e,t){let n=e(this.fields);return bw(db(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function F(e){return bw(db(e,void 0),e)}var xw=e=>typeof e==`symbol`?e:globalThis.String(e);function Sw(e){return function(t){let n={},r=Object.create(null),i=Object.create(null),a=new Set;for(let o of Reflect.ownKeys(t.fields)){let s=uw(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=xw(l);if(a.has(u))throw new globalThis.Error(`Duplicate encoded keys: ${Pn(l)}`);a.add(u),Cn(n,l,s),c&&(r[o]=l,i[l]=o)}return F(n).pipe(Aw(t,ty({decode:EC(i),encode:EC(r)})))}}function Cw(e,t){return aw(ax(e.ast,t.ast),{key:e,value:t})}function ww(e,t){return aw(e,{elements:t,mapElements(e,t){let n=e(this.elements);return ww(pb(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Tw(e){return ww(pb(e),e)}var I=DC(e=>aw(new Qy(!1,[],[e.ast]),{value:e})),Ew=DC(e=>aw(new Qy(!1,[e.ast],[e.ast]),{value:e}));function Dw(e,t){return aw(e,{members:t,mapMembers(e,t){let n=e(this.members);return Dw(mb(n,this.ast.mode,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function L(e,t){return Dw(mb(e,t?.mode??`anyOf`,void 0),e)}function Ow(e){let t=e.map(dw);return aw(mb(t,`anyOf`,void 0),{literals:e,members:t,mapMembers(e){return L(e(this.members))},pick(e){return Ow(e)},transform(e){return L(t.map((t,n)=>t.transform(e[n])))}})}var R=DC(e=>L([e,mw])),kw=DC(e=>L([e,hw]));function z(e){return t=>aw(Xb(t.ast,e),{schema:t,identifier:e})}function Aw(e,t){return n=>aw(rx(n.ast,e.ast,t?$v(t):iy()),{from:n,to:e})}function jw(e,t){return n=>t?Aw(n,t)(e):Aw(n)(e)}function Mw(e){return t=>aw(nx(t.ast,e),{schema:t})}function Nw(e){return Og(e,e=>fg(()=>Pf(e,e=>e.issue)))}function Pw(e,t){let n=t?.encodingStrategy===`omit`?Vv():Iv();return t=>sw(uw(t)).pipe(Aw(t,{decode:Hv(Nw(e)),encode:n}))}function Fw(e,t){return n=>lw(n).pipe(Pw(e,t),jw(sw(n)))}function Iw(e){return dw(e).pipe(Mw(D(e)))}function Lw(e,t){return F({_tag:Iw(e),...t})}function Rw(e,t){return BC(t=>t instanceof e,t)}function zw(){return(e,t)=>new jy(e.ast,$v(t))}var Bw=jb;function Vw(e,t){let n=e.source,r=e.flags,i=r===``?`new RegExp(${Mn(n)})`:`new RegExp(${Mn(n)}, ${Mn(r)})`;return Fb(e,{toCode:()=>({runtime:`Schema.isPattern(${i})`}),...t})}var Hw=aw(Nb),Uw=Mb;function Ww(e){let t=_i(e.order),n=e.formatter??Mn;return(r,i)=>Bw(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitrary:{constraint:{ordered:{order:e.order,minimum:r,exclusiveMinimum:!0}}},...e.annotate?.(r),...i})}function Gw(e){let t=yi(e.order),n=e.formatter??Mn;return(r,i)=>Bw(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitrary:{constraint:{ordered:{order:e.order,minimum:r}}},...e.annotate?.(r),...i})}function Kw(e){let t=yi(e.order),n=_i(e.order),r=vi(e.order),i=gi(e.order),a=e.formatter??Mn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return Bw(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitrary:{constraint:{ordered:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}}}},...e.annotate?.(o),...s})}}function qw(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${Mn(e)}`);return e}var Jw=Ww({order:fi,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:qw(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${Mn(e)})`})})}),Yw=Gw({order:fi,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:qw(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${Mn(e)})`})})}),Xw=Kw({order:fi,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:qw(e.minimum),maximum:qw(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${Mn(e.minimum)}, maximum: ${Mn(e.maximum)}, exclusiveMinimum: ${Mn(t)}, exclusiveMaximum: ${Mn(n)} })`})}}});function Zw(e){return Bw(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`}),toCode:()=>({runtime:`Schema.isInt()`}),arbitrary:{constraint:{integer:!0}},...e})}var B=gw.check(Zw());function Qw(e,t){return e=Math.max(0,Math.floor(e)),Bw(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:t})=>t===`array`?{minItems:e}:{minLength:e},toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[w_]:!0,arbitrary:{constraint:{minLength:e}},...t})}function $w(e){return Qw(1,e)}function eT(e,t){return e=Math.max(0,Math.floor(e)),Bw(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`array`?{maxItems:e}:{maxLength:e},toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[w_]:!0,arbitrary:{constraint:{maxLength:e}},...t})}function tT(e){return Bw(e=>La(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitrary:{constraint:{unique:!0}},...e})}var V=P.check($w());function nT(e){return aw(zC()([e],([e])=>(t,n,r)=>bi(t)?w(t)?ag:y_(aC(e)(t.value,r),{onSuccess:C,onFailure:e=>q_(n,`value`,e,t,r)}):ug(new G_(n,t,r)),{representation:{id:`effect/schema/Option`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Option(${e[0].runtime})`,Type:`Option.Option<${e[0].Type}>`,importDeclarations:[`import * as Option from "effect/Option"`]}),expected:`Option`,toCodec:([e])=>zw()(L([F({_tag:dw(`Some`),value:e}),F({_tag:dw(`None`)})]),ty({decode:e=>e._tag===`None`?S():C(e.value),encode:e=>T(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}})),toArbitrary:([e])=>(t,n)=>{let r=t.constant(S());return yT(t,n,r,t.oneof(r,e.arbitrary.map(C)))},toEquivalence:([e])=>Ii(e),toFormatter:([e])=>E({onNone:()=>`none()`,onSome:t=>`some(${e(t)})`})}).ast,{value:e})}function rT(e){return R(e).pipe(Aw(nT(lw(e)),my()))}function iT(e){return sw(e).pipe(Aw(nT(lw(e)),hy()))}function aT(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:aC(dw(n));return aw(zC()([e],([e])=>(t,n,r)=>NC(t)?b_(a===void 0?cg:v_(a(t.label,r),e=>new V_([`label`],e)),()=>y_(aC(e)(IC(t),r),{onSuccess:()=>t,onFailure:()=>new W_(n,[new V_([`value`],new K_(void 0,t,r))],t,r)})):ug(new G_(n,t,r)),{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${Mn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>zw()(e,{decode:Rv(e=>PC(e,{label:n})),encode:r?Nv(e=>`Cannot serialize Redacted`+(T(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Rv(IC)}),toArbitrary:([e])=>()=>({arbitrary:e.arbitrary.map(e=>PC(e,{label:n})),terminal:e.terminal?.map(e=>PC(e,{label:n}))}),toFormatter:()=>globalThis.String,toEquivalence:([e])=>LC(e)}).ast,{value:e})}function oT(e,t){return Aw(aT(lw(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:Rv(e=>PC(e,{label:t?.label})),encode:t?.disallowEncode?Nv(e=>`Cannot encode Redacted`+(T(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Rv(IC)})(e)}function sT(e,t){return aw(zC()([e,t],([e,t])=>(n,r,i)=>{if(!Tf(n))return ug(new G_(r,n,i));switch(n._tag){case`Fail`:return y_(aC(e)(n.error,i),{onSuccess:Af,onFailure:e=>q_(r,`error`,e,n,i)});case`Die`:return y_(aC(t)(n.defect,i),{onSuccess:jf,onFailure:e=>q_(r,`defect`,e,n,i)});case`Interrupt`:return D(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>zw()(L([F({_tag:dw(`Fail`),error:e}),F({_tag:dw(`Die`),defect:t}),F({_tag:dw(`Interrupt`),fiberId:kw(Hw)})]),ty({decode:e=>{switch(e._tag){case`Fail`:return Af(e.error);case`Die`:return jf(e.defect);case`Interrupt`:return Mf(e.fiberId)}},encode:at})),toArbitrary:([e,t])=>cT(e,t),toEquivalence:([e,t])=>lT(e,t),toFormatter:([e,t])=>uT(e,t)}).ast,{error:e,defect:t})}function cT(e,t){return(n,r)=>{let i=n.constant(Mf());return yT(n,r,i,n.oneof(i,n.integer({min:1}).map(Mf),e.arbitrary.map(e=>Af(e)),t.arbitrary.map(e=>jf(e))))}}function lT(e,t){return(n,r)=>{if(n._tag!==r._tag)return!1;switch(n._tag){case`Fail`:return e(n.error,r.error);case`Die`:return t(n.defect,r.defect);case`Interrupt`:return n.fiberId===r.fiberId}}}function uT(e,t){return n=>{switch(n._tag){case`Fail`:return`Fail(${e(n.error)})`;case`Die`:return`Die(${t(n.defect)})`;case`Interrupt`:return`Interrupt`}}}function dT(e,t){return aw(zC()([e,t],([e,t])=>{let n=I(sT(e,t));return(e,t,r)=>wf(e)?y_(aC(n)(e.reasons,r),{onSuccess:Df,onFailure:n=>q_(t,`failures`,n,e,r)}):ug(new G_(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>zw()(I(sT(e,t)),ty({decode:Df,encode:({reasons:e})=>e})),toArbitrary:([e,t])=>fT(e,t),toEquivalence:([e,t])=>pT(e,t),toFormatter:([e,t])=>mT(e,t)}).ast,{error:e,defect:t})}function fT(e,t){return(n,r)=>{let i=cT(e,t)(n,r);return yT(n,r,n.constant(Of),n.array(i.arbitrary).map(Df))}}function pT(e,t){let n=xn(lT(e,t));return(e,t)=>n(e.reasons,t.reasons)}function mT(e,t){let n=uT(e,t);return e=>`Cause([${e.reasons.map(n).join(`, `)}])`}var hT=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),gT=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},_T=[];function vT(e){let t=hT(e),n=_T[t];if(n!==void 0)return n;let r=tE.pipe(Aw(pw,py(gT(t))));return _T[t]=r,r}function yT(e,t,n,r){return{arbitrary:n===void 0||t.recursion===void 0?r:e.oneof(t.recursion,n,r),terminal:n}}globalThis.RegExp;var bT=P.annotate({expected:`a string that will be decoded as a URL`}),xT=Rw(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>zw()(bT,gy),toArbitrary:()=>e=>e.webUrl().map(e=>new globalThis.URL(e)),toEquivalence:()=>(e,t)=>e.toString()===t.toString()}),ST=bT.pipe(Aw(xT,gy));function CT(e,t,n){let r={...t};if(e?.minimum!==void 0){let t=n===void 0?e.minimum:n(e.minimum),i=e.exclusiveMinimum?new globalThis.Date(t.getTime()+1):t;(r.min===void 0||i.getTime()>r.min.getTime())&&(r.min=i)}if(e?.maximum!==void 0){let t=n===void 0?e.maximum:n(e.maximum),i=e.exclusiveMaximum?new globalThis.Date(t.getTime()-1):t;(r.max===void 0||i.getTime()<r.max.getTime())&&(r.max=i)}return r}var wT=P.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function TT(e,t){return wT.pipe(Aw(e,vy(t)))}var ET=TT(pw);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var DT=P.annotate({expected:`a string that will be decoded as a finite number`}).pipe(Aw(Hw,ay)),OT=P.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),kT=Rw(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>zw()(OT,_y),toArbitrary:()=>e=>e.uint8Array()}),AT=BC(e=>mv(e)&&hv(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecJson:()=>zw()(P,yy),toArbitrary:()=>(e,t)=>e.date(CT(t?.constraint?.ordered?.order===_v?t.constraint.ordered:void 0,{noInvalidDate:!0},Tv)).map(e=>vv(e)),toFormatter:()=>e=>e.toString(),toEquivalence:()=>gv}),jT=P.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(Aw(AT,yy)),MT=globalThis.Symbol.for(`immer-draftable`),NT={};function PT(e,t,n,r,i){let a=LT(n,t,r),o=IT(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===NT?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:NT,value:i}})}static[RC]=RC;get[o](){return o}static[MT]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return nt(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return new this(e,t)}static makeOption(e,t){return tC(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Vb(this.ast,e))}static annotateKey(e){return this.rebuild(Qb(this.ast,e))}static check(...e){return this.rebuild(Ub(this.ast,e))}static extend(e){return(t,r)=>{let a=RT(t)?t:F(t),o={...n.fields,...a.fields},s=db(o,n.ast.checks,{identifier:e});return PT(this,e,bw(Ub(s,a.ast.checks),o),r,i)}}static mapFields(e,t){return n.mapFields(e,t)}};return i!==void 0&&Object.assign(s.prototype,i(t)),s}function FT(e){return new Zv(Rv(t=>new e(t,{"~payload":{token:NT,value:t}})),Iv())}function IT(e){return`~effect/Schema/Class/${e}`}function LT(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=IT(t),o=e=>e instanceof i||At(e,a),s=FT(i);return r=Aw(aw(new Iy([e.ast],()=>(e,t,n)=>o(e)?D(e):ug(new G_(t,e,n)),{identifier:t,[E_]:([e])=>({isConstructed:o,link:new jy(e,s)}),toCodec:([e])=>new jy(e.ast,s),toArbitrary:([e])=>()=>({arbitrary:e.arbitrary.map(e=>new i(e)),terminal:e.terminal?.map(e=>new i(e))}),toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[T_]:_b(e.ast),...n})),s)(e)}}function RT(e){return ow(e)}var H=e=>(t,n)=>PT(As,e,RT(t)?t:F(t),n,e=>({toString(){return`${e}(${Mn({...this})})`}})),U=e=>(t,n,r)=>{let i=RT(n)?n.mapFields(e=>({_tag:Iw(t),...e}),{unsafePreserveChecks:!0}):Lw(t,n);return H(e??t)(i,r)},zT=e=>(t,n)=>PT(Ir,e,RT(t)?t:F(t),n,e=>({name:e})),BT=e=>(t,n,r)=>{let i=RT(n)?n.mapFields(e=>({_tag:Iw(t),...e}),{unsafePreserveChecks:!0}):Lw(t,n);return zT(e??t)(i,r)};function VT(e){return aw(HT(e.ast),{schema:e})}var HT=Jb(e=>{let t=qT(e,HT),n=e.context;return t===e||n===void 0?t:qb(t,UT(n))});function UT(e){return e.constructorDefault===void 0?e:new Ny(e.isOptional,e.isMutable,void 0,e.annotations)}function WT(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function GT(e){return t=>{let n=new Map;for(let e=0;e<t.length;e++)n.set(ux(t[e]),e);let r=[...t].sort((t,r)=>{t=ux(t),r=ux(r);let i=e(t),a=e(r);return i===a?n.get(t)-n.get(r):i-a});return r.some((e,n)=>e!==t[n])?r:t}}var KT=GT(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function qT(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Ct(n))return zb(e,[Fx]);let r=n(e.typeParameters.map(e=>wC(ux(e))));return r===void 0?e:zb(e,[Wb(r,t)])}case`Unknown`:return zb(e,[Fx]);case`ObjectKeyword`:return zb(e,[Ix]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return WT(e),e.recur(t,_x);case`Union`:{let n=KT(e.types);return n===e.types?e.recur(t):new Cb(n,e.mode,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}function JT(e){return aw(eE(e.ast),{schema:e})}var YT=GT(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function XT(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>aw(t(ux(e)))),i=e.annotations?.toCodecStringTree;if(Ct(i)){let n=i(r);return n===void 0?e:zb(e,[Wb(n,t)])}let a=e.annotations?.toCodecJson,o=Ct(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(Ct(s)?s(r):void 0);return c===void 0?n(e):zb(e,[Wb(c,t)])}case`Null`:return zb(e,[ZT]);case`Boolean`:return zb(e,[QT]);case`Unknown`:case`ObjectKeyword`:return zb(e,[Rx]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return WT(e),e.recur(t,_x);case`Union`:{let n=YT(e.types);return n===e.types?e.recur(t):new Cb(n,e.mode,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}var ZT=new jy(new Wy(`null`),new Zv(Rv(()=>null),Rv(()=>`null`))),QT=new jy(new Cb([new Wy(`true`),new Wy(`false`)],`anyOf`),new Zv(Rv(e=>e===`true`),Uv())),$T=new Zv(Rv(e=>typeof e==`string`?[e]:e),Iv()),eE=Jb(e=>{let t=XT(e,eE,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?qb(t,UT(e.context)):t},{stopAt:e=>e.transformation===$T}),tE=aw(Vb(Px,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),nE=Cw(P,tE),rE=e=>()=>{let t=YC(Ew(e));return FS((e,n)=>D(k(e,e=>t(e))))},iE=`~effect/Stream`,aE={_R:at,_E:at,_A:at},oE={[iE]:aE,pipe(){return nt(this,arguments)}},sE=e=>{let t=Object.create(oE);return t.channel=e,t},cE=`~effect/Stream`,lE=e=>At(e,cE),uE=sE,dE=(e,t)=>uE(FS((n,r)=>k($S(e.channel,r),e=>t(e,r)))),fE=e=>e.channel,pE=e=>uE(BS(()=>e().channel)),mE=e=>uE(VS(e)),hE=e=>uE(HS(e)),gE=x(2,(e,t)=>pE(()=>{let n=0;return uE(WS(e.channel,Na(e=>t(e,n++))))})),_E=x(2,(e,t)=>uE(GS(fE(e),t))),vE=x(2,(e,t)=>uE(KS(e.channel,t))),yE=x(e=>lE(e[0]),(e,t)=>pE(()=>{let n=new TextDecoder(t?.encoding);return gE(e,e=>n.decode(e,{stream:!0}))})),bE=x(2,(e,t)=>uE(JS(e.channel,t))),xE=x(2,(e,t)=>uE(XS(e.channel,t))),SE=e=>xg(QS(e.channel),Ai(ga(0))),CE=x(2,(e,t)=>ZS(e.channel,t)),wE=x(e=>lE(e[0]),(e,t,n)=>{let r,i,a=tS(!1);return new ReadableStream({start(n){i=l_(Wg(CE(e,e=>a.whenOpen(sg(()=>{a.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0}))),t)),i.addObserver(e=>{e._tag===`Failure`?n.error(If(e.cause)):n.close()})},pull(){return new Promise(e=>{r=e,a.openUnsafe()})},cancel(){if(i)return d_(wg(Qx(i)))}},n?.strategy)}),TE=x(e=>lE(e[0]),(e,t)=>xg(Vg(),n=>wE(e,n,t))),EE=BigInt(1024);EE*EE*EE*EE*EE;var DE=ro(`effect/Crypto`),OE=`~effect/FiberMap`,kE=e=>At(e,OE),AE={[OE]:OE,[Symbol.iterator](){return this.state._tag===`Closed`?ea():this.state.backing[Symbol.iterator]()},...nr,toJSON(){return{_id:`FiberMap`,state:this.state}}},jE=(e,t)=>{let n=Object.create(AE);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},ME=()=>Jg(sg(()=>jE(Vx(),Xf())),e=>og(()=>{let t=e.state;return t._tag===`Closed`?cg:(e.state={_tag:`Closed`},eS(Gx(t.backing)).pipe(ip(e.deferred)))})),NE=-1,PE=ys(xs(Rf,bs(NE))),FE=x(e=>kE(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(NE);return}let i=Hx(e.state.backing,t);if(i._tag===`Some`){if(r?.onlyIfMissing===!0){n.interruptUnsafe(NE);return}if(i.value===n)return;i.value.interruptUnsafe(NE)}Jx(e.state.backing,t,n),n.addObserver(i=>{if(e.state._tag===`Closed`)return;let a=Hx(e.state.backing,t);T(a)&&n===a.value&&Xx(e.state.backing,t),Jf(i)&&(r?.propagateInterruption===!0?!PE(i.cause):!Nf(i.cause))&&rp(e.deferred,i)})}),IE=x(2,(e,t)=>e.state._tag===`Closed`?S():Hx(e.state.backing,t)),LE=x(2,(e,t)=>og(()=>D(IE(e,t)))),RE=x(2,(e,t)=>e.state._tag!==`Closed`&&qx(e.state.backing,t)),zE=x(2,(e,t)=>sg(()=>RE(e,t))),BE=x(2,(e,t)=>og(()=>{if(e.state._tag===`Closed`)return cg;let n=Hx(e.state.backing,t);return n._tag===`None`?cg:$x(n.value,NE)})),VE=function(){let e;return()=>(e===void 0&&(e=l_(e_)),e)}(),HE=function(){let e=arguments[0];if(eg(arguments[2]))return UE(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>UE(e,t,r,n)},UE=(e,t,n,r)=>hg(i=>{if(e.state._tag===`Closed`)return e_;if(r?.onlyIfMissing===!0&&RE(e,t))return sg(VE);let a=u_(i.context)(n);return FE(e,t,a,r),D(a)}),WE={"~effect/match/Match/Matcher":{_input:at,_filters:at,_remaining:at,_result:at,_return:at,_args:at},_tag:`TypeMatcher`,add(e){return GE(this.select,[...this.cases,e])},pipe(){return nt(this,arguments)}};function GE(e,t){let n=Object.create(WE);return n.select=e,n.cases=t,n}var KE=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),qE=x(2,(e,t)=>YE(t)(GE(at,[]))(e)),JE=e=>t=>{let n=KE(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},YE=(e=>t=>{let n=JE(e)(t);return e=>QE(n(e))})(`_tag`),XE=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?zi(t.evaluate(r,...n)):Bi(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return zi(t.evaluate(r,...n))}return Bi(r)}},ZE=`effect/match/Match/exhaustive: absurd`,QE=e=>{let t=XE(e);if(Ui(t)){if(Gi(t))return t.success;throw Error(ZE)}return(...e)=>{let n=t(...e);if(Gi(n))return n.success;throw Error(ZE)}},$E=qE,eD={"~effect/Ref":{_A:at},...nr,toJSON(){return{_id:`Ref`,ref:this.ref}}},tD=e=>{let t=Object.create(eD);return t.ref=iS(e),t},nD=e=>sg(()=>tD(e)),rD=e=>sg(()=>e.ref.current),iD=x(2,(e,t)=>sg(()=>aS(e.ref,t))),aD=x(2,(e,t)=>sg(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),oD=x(2,(e,t)=>sg(()=>{e.ref.current=t(e.ref.current)})),sD=x(2,(e,t)=>sg(()=>e.ref.current=t(e.ref.current))),cD=`~effect/SynchronizedRef`,lD={...nr,[cD]:cD,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},uD=e=>{let t=Object.create(lD);return t.semaphore=AS(1),t.backing=tD(e),t},dD=e=>sg(()=>uD(e)),fD=e=>e.backing.ref.current,pD=x(2,(e,t)=>e.semaphore.withPermit(og(()=>xg(t(fD(e)),([t,n])=>(e.backing.ref.current=n,t))))),mD=P.check(Vw(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(z(`RepositoryName`)),hD=P.check(Vw(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(z(`RepositoryRevision`)),gD=P.check(Vw(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(z(`CommitSha`)),_D=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),vD=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},yD=e=>e.toLowerCase(),bD=V.pipe(z(`EventId`)),xD=V.pipe(z(`DedupKey`)),SD=class extends H(`Event`)({id:bD,dedupKey:xD,payload:tE,receivedAt:AT}){},CD=V.pipe(z(`LoopName`)),wD=[`none`,`required`],TD=Ow(wD),ED=[`write`,`read`],DD=Ow(ED),OD=class extends U(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{}){},kD=class extends U(`CancelReason/Superseded`)(`Superseded`,{by:bD}){},AD=class extends U(`CancelReason/Revoked`)(`Revoked`,{}){},jD=L([OD,kD,AD]),MD=class extends U(`RunState/Pending`)(`Pending`,{}){},ND=class extends U(`RunState/Waiting`)(`Waiting`,{}){},PD=class extends U(`RunState/Queued`)(`Queued`,{}){},FD=class extends U(`RunState/Running`)(`Running`,{}){},ID=class extends U(`RunState/Succeeded`)(`Succeeded`,{}){},LD=class extends U(`RunState/Failed`)(`Failed`,{}){},RD=class extends U(`RunState/Canceled`)(`Canceled`,{reason:jD}){},zD=L([MD,ND,PD,FD]),BD=L([...zD.members,ID,LD,RD]),VD=L([MD,ND,PD]),HD=L([MD,PD]),UD=KC(zD),WD=KC(VD),GD=KC(HD),KD=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:UD(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),qD=()=>(...e)=>e,JD=qD()(`Pending`,`Waiting`,`Queued`,`Running`),YD=qD()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),XD=qD()(`Pending`,`Waiting`,`Queued`),ZD=e=>new ND,QD=e=>new PD,$D=e=>new FD,eO=e=>new ID,tO=e=>new LD,nO=e=>new FD,rO=e=>new RD({reason:new OD}),iO=(e,t)=>new RD({reason:new kD({by:t})}),aO=e=>new RD({reason:new AD}),oO=V.pipe(z(`RunId`)),sO=class extends H(`Run`)({id:oO,eventId:bD,loop:CD,state:BD,openedAt:AT}){},cO=P.check(Vw(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(z(`CelTypeReference`)),lO=P.check(Vw(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),uO=P.check(Vw(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),dO=e=>Bw(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),fO=class extends H(`@usine/expression/ObjectField`)({name:lO,type:cO,nullable:_w.pipe(Mw(D(!1)))}){},pO=class extends H(`@usine/expression/ObjectType`)({name:uO,fields:I(fO).check(dO(`Expected unique CEL object-field names`))}){},mO=class extends H(`@usine/expression/Variable`)({name:lO,type:cO}){},hO=class extends H(`@usine/expression/Environment`)({types:I(pO).check(dO(`Expected unique CEL object-type names`)),variables:I(mO).check(dO(`Expected unique CEL variable names`))}){},gO=P.check(Vw(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(z(`ExpressionSource`)),_O=B.check(Yw(0)),vO=Ow([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);L([class extends BT(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:gO,code:vO,message:V,position:nT(_O)}){},class extends BT(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:gO,message:V}){}]),L([P,gw,vw,_w,mw]);var yO=class extends ro()(`@usine/expression/ExpressionEngine`){},bO=V.pipe(z(`InstancePath`)),xO=Ow([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),SO=class extends BT(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:bO,stage:xO,expression:iT(gO),message:V}){};L([SO,class extends BT(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:bO,stage:xO,message:V}){}]);var CO=P.check(Vw(/\S/u,{message:`Expected a non-blank model ID`})).pipe(z(`ModelId`)),wO=Ow([`claude`,`codex`,`pi`]),TO=Ow([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),EO=class extends H(`Agent/BrainSpec`)({harness:wO,model:CO,effort:TO}){},DO=P.check(Vw(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(z(`AgentName`)),OO=P.check(Vw(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(z(`AgentPersona`)),kO=class extends H(`Agent`)({name:DO,brain:EO,parentModel:rT(CO),parentEffort:iT(TO),persona:OO}){},AO=(e,t)=>Ci([e.parentModel,t]),jO=(e,t)=>xi(Ci([e.parentEffort,t]),()=>e.brain.effort),MO=class extends U(`StepResult/Commit`)(`Commit`,{sha:gD,summary:V}){},NO=class extends U(`StepResult/PullRequest`)(`PullRequest`,{number:B.check(Yw(1)),url:ST}){},PO=Ow([`issue-comment`,`review`,`review-comment`]),FO=class extends U(`StepResult/Comment`)(`Comment`,{url:ST,kind:PO,at:iT(jT)}){},IO=L([MO,NO,FO]),LO=class extends H(`StepResult`)({message:V,facts:I(IO)}){},RO=V.pipe(z(`StepName`)),zO=class extends H(`Step`)({runId:oO,name:RO,result:nT(LO)}){},BO=P.check(Vw(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(z(`WorkerName`)),VO=Ow([`local`,`exe.dev`,`ssh`]),HO=P.check(Vw(/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$/u,{message:`Expected a GitHub bot login: <slug>[bot]`})).pipe(z(`BotLogin`)),UO=P.check(Vw(/^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/u,{message:`Expected an SSH destination: a host name or address, optionally prefixed by a user`})).pipe(z(`SshDestination`)),WO=B.check(Xw({minimum:1,maximum:65535})).pipe(z(`SshPort`)),GO=P.check(Vw(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(z(`SshIdentityFile`)),KO=P.check(Vw(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(z(`WorkerRoot`)),qO=P.check(Vw(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u,{message:`Expected a lowercase DNS domain`})).pipe(z(`GatewayDomain`)),JO=B.check(Xw({minimum:1,maximum:65535})).pipe(z(`GatewayAdminPort`)),YO=Ow([`anthropic`]),XO=Ow([`api-key`,`subscription`]),ZO=V.pipe(z(`AgentSessionId`)),QO=B.check(Yw(0)).pipe(z(`TokenCount`)),$O=B.check(Yw(1)),ek=$O.pipe(z(`ChildSessionBudget`)),tk=$O.pipe(z(`ChildSessionCount`)),nk=L([class extends U(`Agent/ParentSession`)(`ParentSession`,{id:ZO,agent:DO,brain:EO}){},class extends U(`Agent/ChildSession`)(`ChildSession`,{id:ZO,parentId:ZO,agent:DO,brain:EO,gatewayCredential:iT(XO).pipe(Mw(D(S())))}){}]),rk=V.pipe(z(`HarnessSessionId`)),ik=class extends H(`Agent/HarnessSession`)({id:rk,cwd:V}){},ak=class extends U(`Agent/SessionStarted`)(`SessionStarted`,{session:nk,harnessSession:iT(ik).pipe(Mw(D(S())))}){},ok=class extends U(`Agent/TextOutput`)(`TextOutput`,{session:nk,text:V}){},sk=class extends U(`Agent/ToolStarted`)(`ToolStarted`,{session:nk,callId:V,tool:V,input:tE}){},ck=class extends U(`Agent/ToolFinished`)(`ToolFinished`,{session:nk,callId:V,tool:V,output:tE,isError:_w}){},lk=class extends U(`Agent/SessionFinished`)(`SessionFinished`,{session:nk}){},uk=class extends U(`Agent/SessionIdle`)(`SessionIdle`,{session:nk}){},dk=class extends U(`Agent/SessionResumed`)(`SessionResumed`,{session:nk}){},fk=Hw.check(Yw(0)).pipe(z(`UsdAmount`)),pk=class extends U(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:nk,totalTokens:QO,costUsd:iT(fk).pipe(Mw(D(S())))}){},mk=Ow([`apiKeys`,`claudePlan`,`chatgptPlan`]),hk=(e,t)=>{switch(e.harness){case`claude`:return Li(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},gk=e=>$E(e,{ParentSession:({brain:e})=>hk(e,S()),ChildSession:({brain:e,gatewayCredential:t})=>hk(e,t)}),_k=class extends H(`Agent/RateLimitWindow`)({usedPercent:gw,windowDurationMinutes:rT(gw),resetsAt:rT(jT)}){},vk=class extends H(`Agent/RateLimitsSnapshot`)({limitId:rT(P),limitName:rT(P),primary:rT(_k),secondary:rT(_k)}){},yk=class extends U(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:nk,pool:mk,rateLimits:vk}){},bk=$O.pipe(z(`ProviderRetries`)),xk=L([ak,ok,sk,ck,yk,lk,uk,dk,pk,class extends U(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:nk,message:V,retries:bk}){},class extends U(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:nk,retries:bk}){}]),Sk=class extends BT(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:P,cause:vT()}){},Ck=class extends BT(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:P,cause:vT()}){},wk=class extends BT(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:P}){},Tk=class extends BT(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:V}){},Ek=class extends BT(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:V}){},Dk=Ow([`wall-clock`,`tokens`]),Ok=L([Sk,Ck,wk,Tk,Ek,class extends BT(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:Dk}){},class extends BT(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:ek,attemptedChildren:tk}){}]),kk=KC(Sk),Ak=class extends U(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},jk=class extends U(`AttemptOutcome/Failed`)(`Failed`,{failure:Ok}){},Mk=class extends U(`AttemptOutcome/Canceled`)(`Canceled`,{}){},Nk=L([Ak,jk,Mk]),Pk=V.pipe(z(`SalvageRef`)),Fk=(e,t)=>Pk.make(`usine/salvage/${_D(e)}/${t}`),Ik=class extends U(`AttemptSalvage/Pushed`)(`Pushed`,{ref:Pk,commit:gD}){},Lk=L([Ik,class extends U(`AttemptSalvage/Retained`)(`Retained`,{path:V,commit:rT(gD),message:P}){}]),Rk=P.check(Vw(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(z(`OperatorLogin`)),zk=class extends U(`AttemptStart/Event`)(`Event`,{}){},Bk=class extends U(`AttemptStart/Retry`)(`OperatorRetry`,{operator:rT(Rk)}){},Vk=class extends U(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:rT(Rk)}){},Hk=class extends U(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},Uk=class extends U(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},Wk=L([Bk,Vk]),Gk=L([zk,Bk,Vk,Hk,Uk]),Kk=V.pipe(z(`AttemptId`)),qk=B.check(Yw(1)).pipe(z(`AttemptNumber`)),Jk=P.check(Vw(/\S/u,{message:`Expected non-blank task text`})).pipe(z(`AttemptTask`)),Yk=class extends H(`AttemptContext`)({task:Jk,agent:kO,parentModel:rT(CO)}){},Xk=class extends H(`Attempt`)({id:Kk,runId:oO,stepName:RO,worker:BO,number:qk,brain:EO,task:Jk,agent:DO,operatorIntervened:_w,parentModel:rT(CO),startedAt:AT,outcome:nT(Nk),endedAt:nT(AT),salvage:nT(Lk),start:nT(Gk).pipe(Mw(D(S()))),reattachedAt:nT(AT).pipe(Mw(D(S()))),comments:I(FO).pipe(Mw(D([])))}){},Zk=class extends H(`AttemptWindow`)({attemptId:Kk,startedAt:AT,endedAt:nT(AT)}){},Qk=e=>T(e.outcome)&&w(e.endedAt)?S():C(new Zk({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),$k=e=>{let t=Dv(e.startedAt);return t-t%1e3},eA=(e,t)=>E(e.endedAt,{onNone:()=>!0,onSome:e=>t<=Dv(e)}),tA=(e,t)=>{let n=Dv(t);return $k(e)<=n&&eA(e,n)},nA=(e,t)=>eA(e,$k(t))&&eA(t,$k(e)),rA=class extends H(`AttemptWindows`)({own:nT(Zk),overlapping:I(Zk)}){},iA=e=>kk(e.failure)&&e.number<e.maxAutoAttempts,aA=V.pipe(z(`ItemKey`)),oA=B.check(Yw(1)).pipe(z(`ItemNumber`)),sA=B.check(Yw(1)).pipe(z(`CycleLimit`)),cA=B.check(Yw(0)).pipe(z(`CycleGeneration`)),lA=sA.make(3),uA=B.check(Yw(0)).pipe(z(`CycleCount`)),dA=class extends H(`LoopCycleCount`)(F({loop:CD,admitted:uA,completed:uA}).check(Bw(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`})).annotate({parseOptions:{onExcessProperty:`error`}})){},fA=bD.pipe(z(`CycleBudgetAskId`)),pA=class extends H(`CycleBudgetAsk`)(F({id:fA,itemKey:aA,repository:mD,loop:CD,limit:sA,counts:Ew(dA)}).check(Bw(({loop:e,limit:t,counts:n})=>new Set(n.map(e=>e.loop)).size===n.length&&n.some(n=>n.loop===e&&n.admitted>=t),{message:`Expected unique participating loops, including the exhausted loop at its limit`})).annotate({parseOptions:{onExcessProperty:`error`}})){get completedCycles(){return uA.make(Math.max(...this.counts.map(({completed:e})=>e)))}},mA=B.check(Yw(1)).pipe(z(`AttemptChannelSequence`)),hA=[`inbound`,`outbound`],gA=Ow(hA),_A=class extends H(`AttemptChannel/RunSpec`)({attemptId:Kk,repository:mD,revision:hD,baseCommit:gD,payload:tE,task:Jk,agent:kO,parentModel:rT(CO),maxChildren:ek,parentEffort:TO,resume:rT(Ik),conflictingSalvage:rT(Ik).pipe(Pw(D(null)),Mw(D(S()))),preparedAt:rT(jT).pipe(Pw(D(null))),botLogin:rT(HO).pipe(Pw(D(null)))}){},vA=class extends U(`AttemptChannel/Started`)(`Started`,{parentModel:CO,conflictingSalvage:rT(Ik).pipe(Pw(D(null)),Mw(D(S())))}){},yA=class extends U(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:xk}){},bA=class extends U(`AttemptChannel/Final`)(`Final`,{result:LO}){},xA=class extends U(`AttemptChannel/Failed`)(`Failed`,{failure:Ok}){},SA=class extends U(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},CA=class extends U(`AttemptChannel/Steer`)(`Steer`,{message:V}){},wA=class extends U(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},TA=class extends U(`AttemptChannel/Cancel`)(`Cancel`,{}){},EA=class extends U(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:V}){},DA=class extends U(`AttemptChannel/Release`)(`Release`,{}){},OA=L([CA,wA,EA,DA]),kA=L([OA,TA]),AA=class extends U(`AttemptChannel/ParentTarget`)(`Parent`,{}){},jA=class extends U(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:ZO}){},MA=L([AA,jA]),NA=class extends H(`AttemptChannel/Intervention`)({operator:V,target:MA,action:OA}){},PA=class extends H(`AttemptChannel/InterventionState`)({held:_w,paused:_w,queued:_w.pipe(Pw(D(!1)),Mw(D(!1)))}){},FA=class extends U(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:mA,intervention:NA,state:PA}){},IA=class extends U(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:mA,intervention:NA,message:V}){},LA=class extends U(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:BO,lastAnsweredAt:jT,reason:V}){},RA=class extends U(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:BO,lastAnsweredAt:jT}){};L([LA,RA]);var zA=L([vA,yA,bA,xA,SA,FA,IA,LA,RA]),BA={version:dw(7),attemptId:Kk,sequence:mA,sentAt:jT},VA=class extends U(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{...BA,payload:zA}){},HA=class extends U(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{...BA,target:MA.pipe(Pw(D({_tag:`Parent`}))),operator:V,payload:kA}){},UA=L([VA,HA]),WA=[`ui`,`github-ask`],GA=Ow(WA),KA=class extends H(`ApprovalSource`)(F({channel:GA,approver:rT(Rk)}).check(Bw(({channel:e,approver:t})=>e!==`github-ask`||T(t),{message:`Expected an approver for a GitHub ask approval`})).annotate({parseOptions:{onExcessProperty:`error`}})){},qA=class extends H(`RunApproval`)({approvedAt:AT,source:nT(KA)}){},JA=class e extends ro()(`@usine/engine/internal/RunDatabase`){static layer=t=>Ep(e)(t)},YA=class extends BT(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:oO}){},XA=class extends BT(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:oO,operation:Ow([`approve`,`retry`,`resolveFailure`,`runAgain`]),state:P}){},ZA=class extends BT(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:oO,openRunId:oO,message:V}){},QA=class extends BT(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:P,cause:vT()}){},$A=class extends BT(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:Kk,cause:vT()}){},ej=L([YA,XA,ZA,QA]),tj=class extends BT(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:oO,attemptId:Kk,message:V}){},nj=class extends BT(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:BO,running:B.check(Yw(0))}){};L([YA,XA,ZA,QA,$A,tj]);var rj=class extends H(`@usine/engine/Submission`)({event:SD,itemKey:aA,loop:CD,step:RO,approval:TD,permissions:DD.pipe(Pw(D(`write`)),Mw(D(`write`))),cycleLimit:nT(sA).pipe(Fw(D(C(lA))),Mw(D(C(lA)))),cycleGeneration:cA.pipe(Pw(D(cA.make(0))),Mw(D(cA.make(0)))),repository:mD,revision:hD,task:Jk,agent:kO,parentModel:nT(CO)}){},ij=`@usine/engine/DurableRun`,aj=j(`Submission.runIdFor`)(function*(e){let t=yield*(yield*DE).digest(`SHA-256`,new TextEncoder().encode(`${ij}-${e.event.dedupKey}`)).pipe(jg);return oO.make(Ls(t.subarray(0,16)))}),oj=(e,t,n)=>{let r=xD.make(JSON.stringify([`reopened`,n,t]));return new rj({...e,event:new SD({...e.event,id:bD.make(r),dedupKey:r})})},sj=class extends U(`@usine/engine/Claimed`)(`Claimed`,{eventId:bD,runId:oO}){},cj=class extends U(`@usine/engine/Queued`)(`Queued`,{eventId:bD}){},lj=[`superseded`,`revoked`],uj=Ow(lj),dj=class extends U(`@usine/engine/Ignored`)(`Ignored`,{eventId:bD,reason:uj}){},fj=class extends U(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:bD,runId:oO}){},pj=class extends U(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:bD,ask:pA}){},mj=L([sj,cj,fj,dj,pj]),hj=new class extends H(`@usine/engine/RetryRequest`)({requestedBy:nT(Rk),amendment:nT(Yk)}){}({requestedBy:S(),amendment:S()}),gj=class extends H(`RunAgain`)(F({from:oO,requestedBy:rT(Rk)}).annotate({parseOptions:{onExcessProperty:`error`}})){},_j=B.check(Yw(1)).pipe(z(`TranscriptSequence`)),vj=Ow([3,4]),yj=F({...VA.fields,version:vj}),bj=F({_tag:dw(`InboundEnvelope`),version:vj,attemptId:Kk,sequence:mA,sentAt:jT,payload:L([CA,wA])}),xj=Ow([5,6]),Sj=L([UA,F({...VA.fields,version:xj}),F({...HA.fields,version:xj}),yj,bj]),Cj=class extends H(`@usine/engine/TranscriptEntry`)({sequence:_j,attemptId:Kk,direction:gA,envelope:Sj,receivedAt:AT}){},wj=class extends U(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:Kk}){},Tj=class extends U(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:Kk}){},Ej=class extends U(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:Kk}){},Dj=class extends U(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:Kk,after:_j,limit:B.check(Yw(1))}){},Oj=class extends U(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:Kk,before:nT(_j),limit:B.check(Yw(1))}){};L([wj,Tj,Ej,Dj,Oj]);var kj=class extends H(`@usine/engine/RunSnapshot`)({event:SD,itemKey:aA,run:sO,step:zO,attempts:I(Xk),resolvedFailureAttemptId:nT(Kk),closedAt:nT(AT),approval:nT(qA),runAgain:nT(gj),repository:mD,revision:hD,task:Jk,agent:kO,parentModel:nT(CO),permissions:DD}){},Aj=class extends H(`@usine/engine/RunEvent`)({runId:oO,event:SD}){},jj=class extends H(`@usine/engine/RunEvidence`)({snapshot:kj,transcript:I(Cj)}){},Mj=class extends H(`@usine/engine/RunSummary`)({itemKey:aA,run:sO,step:zO,attempts:I(Xk),resolvedFailureAttemptId:nT(Kk),closedAt:nT(AT),approval:nT(qA),runAgain:nT(gj),repository:mD,task:Jk,agent:kO}){},Nj=class extends H(`@usine/engine/WorkerAttempts`)(F({worker:BO,attempts:B.check(Yw(1)),running:B.check(Yw(0))}).check(Bw(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},Pj=class extends H(`@usine/engine/LoopSighting`)({loop:CD,itemKey:aA,event:nT(bD),run:nT(oO),suppressedBy:nT(oO)}){},Fj=B.check(Yw(0)).pipe(z(`ProjectionRevision`));H(`@usine/engine/RunAgainRequest`)({step:RO,approval:TD,cycleLimit:nT(sA),permissions:DD,context:Yk,requestedBy:nT(Rk)});var Ij=L([sj,pj]),Lj=(e,t,n)=>{let r=xD.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new rj({event:new SD({id:bD.make(r),dedupKey:r,payload:e.event.payload,receivedAt:n.receivedAt}),itemKey:e.itemKey,loop:e.run.loop,step:t.step,approval:t.approval,permissions:t.permissions,cycleLimit:t.cycleLimit,cycleGeneration:n.generation,repository:e.repository,revision:e.revision,task:t.context.task,agent:t.context.agent,parentModel:t.context.parentModel})},Rj=class extends H(`@usine/engine/StepExecution`)({attempt:Xk,event:SD,run:sO,step:zO,repository:mD,revision:hD,task:Jk,agent:kO,parentModel:nT(CO),permissions:DD,resume:nT(Ik),reattach:_w.pipe(Mw(D(!1)))}){},zj=class extends ro()(`@usine/engine/StepExecutor`){},Bj=Symbol.for(`drizzle:ViewBaseConfig`),W=Symbol.for(`drizzle:entityKind`);function G(e,t){if(e instanceof t)return!0;if(e&&typeof e==`object`){for(let n=Object.getPrototypeOf(e)?.constructor,r=t[W];n;n=Object.getPrototypeOf(n))if(W in n&&n[W]===r)return!0}return!1}function Vj(e,t){if(t&&typeof t==`object`){for(let n=Object.getPrototypeOf(t)?.constructor;n;n=Object.getPrototypeOf(n))if(W in n&&e.includes(n[W]))return!0}return!1}var Hj=Symbol.for(`drizzle:OriginalColumn`),Uj=e=>e;Uj.isNoop=!0;var Wj=class{static[W]=`Column`;codec;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;isAlias;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.isAlias=!1,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue=Uj;mapToDriverValue=Uj;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[Hj](){return this}},Gj=class extends Error{static[W]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},Kj=Symbol.for(`drizzle:Name`),qj=Symbol.for(`drizzle:Schema`),Jj=Symbol.for(`drizzle:Columns`),Yj=Symbol.for(`drizzle:ExtraConfigColumns`),Xj=Symbol.for(`drizzle:OriginalName`),Zj=Symbol.for(`drizzle:BaseName`),Qj=Symbol.for(`drizzle:IsAlias`),$j=Symbol.for(`drizzle:ExtraConfigBuilder`),eM=Symbol.for(`drizzle:IsDrizzleTable`),K=class{static[W]=`Table`;static Symbol={Name:Kj,Schema:qj,OriginalName:Xj,Columns:Jj,ExtraConfigColumns:Yj,BaseName:Zj,IsAlias:Qj,ExtraConfigBuilder:$j};[Kj];[Xj];[qj];[Jj];[Yj];[Zj];[Qj]=!1;[eM]=!0;[$j]=void 0;constructor(e,t,n){this[Kj]=this[Xj]=e,this[qj]=t,this[Zj]=n}};function tM(e){return e[Kj]}var nM=Symbol.for(`drizzle:IsDrizzleView`),rM=class{static[W]=`View`;[Bj];[nM]=!0;get[Kj](){return this[Bj].name}get[qj](){return this[Bj].schema}get[Qj](){return this[Bj].isAlias}get[Xj](){return this[Bj].originalName}get[Jj](){return this[Bj].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[Bj]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},iM=class{static[W]=`Subquery`;get[Kj](){return this._.alias}get[qj](){}get[Xj](){return this._.alias}get[Qj](){return!1}get[Jj](){return this._.selectedFields}constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},aM=class extends iM{static[W]=`WithSubquery`};function oM(e){return e!=null&&typeof e.getSQL==`function`}var sM=class{value;static[W]=`StringChunk`;constructor(e){this.value=e}getSQL(){return new q([this])}},q=class e{queryChunks;static[W]=`SQL`;decoder=uM;shouldInlineParams=!1;_usedTables;get usedTables(){if(this._usedTables)return this._usedTables;this._usedTables=[];for(let e=0;e<this.queryChunks.length;++e){let t=this.queryChunks[e];if(G(t,K)){let e=t[K.Symbol.Schema];this._usedTables.push(e===void 0?t[K.Symbol.Name]:e+`.`+t[K.Symbol.Name])}}return this._usedTables}constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return this.buildQueryFromSourceParams(this.queryChunks,e)}buildQueryFromSourceParams(e,t){let n=[],r=[],i=t.tagged?[]:void 0;if(this.collectSQL(e,t,t.paramStartIndex||{value:0},t.inlineParams||this.shouldInlineParams,n,r,i),i===void 0)return{sql:n.join(``),params:r};let a=Array(i.length);for(let e=0;e<i.length;++e){let t=e+1<i.length?i[e+1]:n.length,r=``;for(let a=i[e];a<t;++a)r+=n[a];a[e]=r}return{sql:n.join(``),params:r,_sql:Object.assign(a,{raw:a})}}collectSQL(t,n,r,i,a,o,s){let{escapeName:c,escapeParam:l,codecs:u,invokeSource:d}=n;for(let f=0;f<t.length;++f){s!==void 0&&s.push(a.length);let p=t[f];if(G(p,sM))a.push(p.value);else if(G(p,e))this.collectSQL(p.queryChunks,n,r,i||p.shouldInlineParams,a,o,void 0);else if(G(p,cM))a.push(c(p.value));else if(p!==void 0){if(G(p,Wj)){let e=p.name;if(d===`indexes`){a.push(c(e));continue}let t=d===`mssql-check`?void 0:p.table[K.Symbol.Schema];a.push(p.isAlias?c(p.name):p.table[Qj]||t===void 0?c(p.table[K.Symbol.Name])+`.`+c(e):c(t)+`.`+c(p.table[K.Symbol.Name])+`.`+c(e))}else if(G(p,fM)){if(G(p.value,e)){let e=p.value;this.collectSQL(e.queryChunks,n,r,i||e.shouldInlineParams,a,o,void 0);continue}let t=u&&G(p.encoder,Wj);if(G(p.value,mM)){let e=l(r.value++,p);p.codec=t?e=>u.apply(p.encoder,`normalizeParam`,e):void 0,a.push(t?u.apply(p.encoder,`castParam`,e):e),o.push(p);continue}let s;if(p.value===null)s=p.value;else{if(s=p.encoder.mapToDriverValue.isNoop?p.value:p.encoder.mapToDriverValue(p.value),G(s,e)){let e=s;this.collectSQL(e.queryChunks,n,r,i||e.shouldInlineParams,a,o,void 0);continue}t&&(s=u.apply(p.encoder,`normalizeParam`,s))}if(i){a.push(this.mapInlineParam(s,n));continue}let c=l(r.value++,s);a.push(t?u.apply(p.encoder,`castParam`,c):c),o.push(s)}else if(G(p,mM))a.push(l(r.value++,p)),o.push(p);else if(G(p,K)){let e=p[K.Symbol.Schema],t=p[K.Symbol.Name];if(d===`mssql-view-with-schemabinding`){a.push(c(e===void 0?`dbo`:e)+`.`+c(t));continue}a.push(e===void 0||p[Qj]?c(t):c(e)+`.`+c(t))}else if(G(p,rM)){let e=p[Bj].schema,t=p[Bj].name;a.push(e===void 0||p[Bj].isAlias?c(t):c(e)+`.`+c(t))}else if(G(p,e.Aliased)&&p.fieldAlias!==void 0)a.push((p.origin===void 0?``:c(p.origin)+`.`)+c(p.fieldAlias));else if(G(p,iM)){if(p._.isWith){a.push(c(p._.alias));continue}let e=p._.sql;a.push(`(`),this.collectSQL(e.queryChunks,n,r,i||e.shouldInlineParams,a,o,void 0),a.push(`) `+c(p._.alias))}else if(typeof p==`function`&&`enumName`in p){if(`schema`in p&&p.schema){a.push(c(p.schema)+`.`+c(p.enumName));continue}a.push(c(p.enumName))}else if(oM(p)){let e=p.getSQL(),t=i||e.shouldInlineParams;if(p.shouldOmitSQLParens?.()){this.collectSQL(e.queryChunks,n,r,t,a,o,void 0);continue}a.push(`(`),this.collectSQL(e.queryChunks,n,r,t,a,o,void 0),a.push(`)`)}else if(Array.isArray(p)){a.push(`(`);let e=[void 0];for(let t=0;t<p.length;++t)t>0&&a.push(`, `),e[0]=p[t],this.collectSQL(e,n,r,i,a,o,void 0);a.push(`)`)}else i?a.push(this.mapInlineParam(p,n)):(a.push(l(r.value++,p)),o.push(p))}}}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}nullable(){return this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},cM=class{value;static[W]=`Name`;brand;constructor(e){this.value=e}getSQL(){return new q([this])}};function lM(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var uM={mapFromDriverValue:e=>e};uM.mapFromDriverValue.isNoop=!0;var dM={mapToDriverValue:e=>e};dM.mapToDriverValue.isNoop=!0,{...uM,...dM};var fM=class{value;encoder;codec;static[W]=`Param`;brand;constructor(e,t=dM,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new q([this])}};function J(e,...t){let n=t.length>0||e.length>0&&e[0]!==``,r=n?e.length+t.length:e.length-1,i=Array(r<0?0:r),a=0;n&&(i[a++]=new sM(e[0]));for(let n=0;n<t.length;++n){let r=t[n];i[a++]=r,i[a++]=new sM(e[n+1])}return new q(i)}(function(e){function t(){return new q([])}e.empty=t;function n(e){return new q(e)}e.fromList=n;function r(e){return new q([new sM(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new q(e.slice());let r=Array(n*2-1);for(let i=0,a=0;i<n;++i)r[a++]=e[i],i<n-1&&(r[a++]=t);return new q(r)}e.join=i;function a(e){return new cM(e)}e.identifier=a;function o(e){return new mM(e)}e.placeholder=o;function s(e,t){return new fM(e,t)}e.param=s;function c(e){let t=pM(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function pM(e){let t=pM.encodeInput(e);return t.length?`/*${t}*/`:``}(function(e){function t(e,t){let r;if(typeof e==`object`&&typeof t==`object`)r=n({...e,...t});else if(e&&t)r=[n(e),n(t)].filter(e=>e.length).join(`,`);else if(t)r=n(t);else if(e)r=n(e);else return``;return r.length?`/*${r}*/`:``}e.merge=t;function n(e){if(typeof e==`string`)return e.length?i(e):e;let t=[];for(let[n,i]of Object.entries(e)){if(i==null||i===``)continue;let e=r(n),a=r(String(i));t.push(`${e}='${a}'`)}return t.length?t.sort().join(`,`):``}e.encodeInput=n;function r(e){return encodeURIComponent(e).replace(/'/g,`\\'`)}e.sanitizeObjectElement=r;function i(e){return e.replace(/\/\*/g,`/ *`).replace(/\*\//g,`* /`)}e.sanitizeStringInput=i})(pM||={}),(function(e){class t{sql;fieldAlias;static[W]=`SQL.Aliased`;isSelectionField=!1;origin;constructor(e,t){this.sql=e,this.fieldAlias=t}getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(q||={});var mM=class{name;static[W]=`Placeholder`;constructor(e){this.name=e}getSQL(){return new q([this])}};Wj.prototype.getSQL=function(){return new q([this])},iM.prototype.getSQL=function(){return new q([this])};var hM=class{table;ignoreColumnAlias;static[W]=`ColumnTableAliasProxyHandler`;constructor(e,t){this.table=e,this.ignoreColumnAlias=t}get(e,t){return t===`table`?this.table:t===`isAlias`&&this.ignoreColumnAlias?!1:t===Hj&&!this.ignoreColumnAlias?()=>e:e[t]}},gM=class{view;selection;ignoreColumnAlias;static[W]=`ViewSelectionAliasProxyHandler`;constructor(e,t,n){this.view=e,this.selection=t,this.ignoreColumnAlias=n}get(e,t){let n=e[t];return G(n,Wj)?new Proxy(n,new hM(this.view,this.ignoreColumnAlias)):G(n,iM)||G(n,q)||G(n,q.Aliased)||oM(n)||typeof n!=`object`||!n?n:new Proxy(n,this)}},_M=class{alias;replaceOriginalName;ignoreColumnAlias;static[W]=`TableAliasProxyHandler`;constructor(e,t,n){this.alias=e,this.replaceOriginalName=t,this.ignoreColumnAlias=n}get(e,t){if(t===K.Symbol.IsAlias)return!0;if(t===K.Symbol.Name||this.replaceOriginalName&&t===K.Symbol.OriginalName)return this.alias;if(t===Bj)return{...e[Bj],name:this.alias,isAlias:!0,selectedFields:new Proxy(e[Bj].selectedFields,new gM(new Proxy(e,this),e[Bj].selectedFields,this.ignoreColumnAlias))};if(t===K.Symbol.Columns){let t=e[K.Symbol.Columns];if(!t)return t;if(G(e,rM))return new Proxy(e[K.Symbol.Columns],new gM(new Proxy(e,this),e[K.Symbol.Columns],this.ignoreColumnAlias));let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new hM(new Proxy(e,this),this.ignoreColumnAlias))}),n}let n=e[t];return G(n,Wj)?new Proxy(n,new hM(new Proxy(e,this),this.ignoreColumnAlias)):n}},vM=class{subquery;alias;static[W]=`SubquerySelectionAliasProxyHandler`;constructor(e,t){this.subquery=e,this.alias=t}get(e,t){let n=e[t];if(G(n,Wj))return new Proxy(n,new hM(this.subquery,!0));if(G(n,q.Aliased)){let e=n.clone();return e.isSelectionField=!0,e.origin=this.alias,e}return n}},yM=class{alias;static[W]=`SubqueryAliasProxyHandler`;constructor(e){this.alias=e}get(e,t,n){if(t===K.Symbol.IsAlias)return!0;if(t===K.Symbol.Name)return this.alias;if(t===K.Symbol.OriginalName)return e._.alias;if(t!==K.Symbol.Schema)return t===`_`?{...e._,alias:this.alias,isWith:!0,selectedFields:new Proxy(e._.selectedFields,new vM(n,this.alias))}:t===K.Symbol.Columns?new Proxy(e._.selectedFields,new vM(n,this.alias)):e[t]}},bM=class{alias;static[W]=`ColumnAliasProxyHandler`;constructor(e){this.alias=e}get(e,t){return t===`isAlias`?!0:t===`name`?this.alias:t===`keyAsName`?!1:t===Hj?()=>e:e[t]}};function xM(e,t){return G(e,iM)?new Proxy(e,new yM(t)):new Proxy(e,new _M(t,!1,!1))}function SM(e,t){return new Proxy(e,new bM(t))}Wj.prototype.as=function(e){return SM(this,e)};function CM(e){return e[Hj]()}var wM=[fM[W],mM[W],Wj[W],K[W],rM[W]];function TM(e,t){return lM(t)&&!oM(e)&&!(e instanceof fM||e instanceof mM||e instanceof Wj||e instanceof K||e instanceof rM)&&!Vj(wM,e)?new fM(e,t):e}var EM=(e,t,n)=>new q([e,t,TM(n,e)]),DM=new sM(` = `),Y=(e,t)=>EM(e,DM,t),OM=new sM(` <> `),kM=(e,t)=>EM(e,OM,t),AM=new sM(`((`),jM=new sM(`))`),MM=new sM(`) and (`),NM=new sM(`) or (`),PM=(e,t)=>{let n=Array(e.length*2+1),r=e.length-1;n[0]=AM;for(let i=0;i<r;i++)n[i*2+1]=e[i],n[i*2+2]=t;return n[r*2+1]=e[r],n[r*2+2]=jM,new q(n)};function FM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new q(t):PM(t,MM)}function IM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new q(t):PM(t,NM)}function LM(e){if(e)return G(e,q)?J`not (${e})`:J`not ${e}`}var RM=new sM(` > `),zM=(e,t)=>EM(e,RM,t),BM=new sM(` >= `),VM=(e,t)=>EM(e,BM,t),HM=new sM(` < `),UM=(e,t)=>EM(e,HM,t),WM=new sM(` <= `),GM=(e,t)=>EM(e,WM,t),KM=new sM(` in `);function qM(e,t){return Array.isArray(t)?t.length===0?new q([new sM(`1 = 0`)]):new q([e,KM,t.map(t=>TM(t,e))]):EM(e,KM,t)}var JM=new sM(` not in `);function YM(e,t){return Array.isArray(t)?t.length===0?new q([new sM(`1 = 1`)]):new q([e,JM,t.map(t=>TM(t,e))]):EM(e,JM,t)}function XM(e){return J`(${e} is null)`}function ZM(e){return J`(${e} is not null)`}function QM(e){return J`exists ${e}`}function $M(e){return J`not exists ${e}`}function eN(e,t,n){return J`${e} between ${TM(t,e)} and ${TM(n,e)}`}function tN(e,t,n){return J`${e} not between ${TM(t,e)} and ${TM(n,e)}`}function nN(e,t){return J`${e} like ${t}`}function rN(e,t){return J`${e} not like ${t}`}function iN(e,t){return J`${e} ilike ${t}`}function aN(e,t){return J`${e} not ilike ${t}`}function oN(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=TM(t,e),r=J`${Array.isArray(n)?new fM(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${TM(t,e)}`}function sN(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=TM(t,e),r=J`${Array.isArray(n)?new fM(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${TM(t,e)}`}function cN(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=TM(t,e),r=J`${Array.isArray(n)?new fM(n):n}`;return J`${e} && ${r}`}return J`${e} && ${TM(t,e)}`}function lN(e){return J`${e} asc`}function uN(e){return J`${e} desc`}function dN(e,t){let n=Array(t.length);for(let r=0;r<t.length;++r){let i=t[r],a=[];for(let t=0;t<e.length;++t){let n=e[t].path;n.length>1&&n[0]===i&&a.push(t)}n[r]={key:i,leaves:a}}return n}var fN=Object.getPrototypeOf(()=>null).constructor;function pN(e,t){let n=[],r=[];r.push(`const [ ${e.map((e,t)=>`c${t}`).join(`, `)} ] = rows[i];`);let i={},a=new Set(t??[]),o=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:a,path:s,codec:c,arrayDimensions:l}=e[t],u,d,f;switch(a){case`Column`:u=r,f=`field: decoder${t}`;break;case`SQL`:u=r.decoder,f=`field: { decoder: decoder${t} }`;break;case`Subquery`:u=r._.sql.decoder,f=`field: { _: { sql: { decoder: decoder${t} } } }`;break;default:u=r.sql.decoder,f=`field: { sql: { decoder: decoder${t} } }`}d=`decoder${t}.mapFromDriverValue`,u.mapFromDriverValue.isNoop&&(d=``),d?n.push(`const { ${f}${c?`, codec: codec${t}`:``} } = columns[${t}];`):c&&n.push(`const { codec: codec${t} } = columns[${t}];`);let p=`c${t}`,m=p;c&&(m=`codec${t}(${m}, ${l})`),d&&(m=`${d}(${m})`),o[t]=p===m?`${p}`:`${p} === null ? ${p} : ${m}`,s.length>1&&(i[s[0]]??=[]).push(p)}r.push(`mapped[i] = {`);let s=[];for(let t=0;t<e.length;++t){let{path:n}=e[t],c=n.map(e=>JSON.stringify(e)),l=o[t],u=n.slice(0,-1),d=0;for(;d<s.length&&d<u.length&&s[d]===u[d];)d++;for(let e=s.length-1;e>=d;--e)r.push(`${` `.repeat(e+1)}},`);for(let e=d;e<u.length;++e){let t=e===0&&a.has(n[0]);r.push(`${` `.repeat(e+1)}${c[e]}: ${t?`${i[n[0]].map(e=>`${e} === null`).join(` && `)} ? null : {`:`{`}`)}s=u,r.push(`${` `.repeat(n.length)}${c[n.length-1]}: ${l},`)}for(let e=s.length-1;e>=0;--e)r.push(`${` `.repeat(e+1)}},`);return r.push(`};`),`${n.length?`${n.join(`
15
+ `)}\n\t`:``}for (let i = 0; i < length; ++i) {
16
+ ${r.join(`
17
+ `)}
18
+ }`}function mN(e,t){let n=`\t"use strict";
19
+ const { columns } = this;
20
+ const { length } = rows;
21
+ const mapped = new Array(length);
22
+ ${pN(e,t)}
23
+ return mapped;
24
+ //# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new fN(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function hN(e,t){let n=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:i,codec:a,arrayDimensions:o}=e[t],s;switch(i){case`Column`:s=r;break;case`SQL`:s=r.decoder;break;case`Subquery`:s=r._.sql.decoder;break;default:s=r.sql.decoder}let c;c=s.mapFromDriverValue.isNoop?a?e=>a(e,o):void 0:a?e=>s.mapFromDriverValue(a(e,o)):e=>s.mapFromDriverValue(e),n[t]=c}let r=t?.length?dN(e,t):void 0;return(t=>{let{length:i}=t,a=Array(i);for(let o=0;o<i;++o){let i=t[o],s={};for(let t=0;t<e.length;++t){let{path:r}=e[t],a=s;for(let e=0;e<r.length;++e){let o=r[e];if(e<r.length-1)o in a||(a[o]={}),a=a[o];else{let e=n[t],r=i[t];a[o]=r===null?null:e?e(r):r}}}if(r)for(let e=0;e<r.length;++e){let{key:t,leaves:n}=r[e],a=!0;for(let e=0;e<n.length;++e)if(i[n[e]]!==null){a=!1;break}a&&(s[t]=null)}a[o]=s}return a})}function gN(e,t,n,r=[]){let i=Object.entries(e);for(let e=0;e<i.length;++e){let[a,o]=i[e];if(typeof a!=`string`)return r;let s=t?[...t,a]:[a];if(G(o,Wj))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(G(o,q)){let e=_N(o);r.push(e?{path:s,field:o,fieldType:`SQL`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL`})}else if(G(o,q.Aliased)){let e=_N(o);r.push(e?{path:s,field:o,fieldType:`SQL.Aliased`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL.Aliased`})}else if(G(o,iM)){let e,t=Object.values(o._.selectedFields)[0],i;G(t,Wj)?(e=t,i=t):G(t,q)?(e=_N(t),i=t.decoder):(e=_N(t),i=t.sql.decoder),i&&(o._.sql.decoder=i),r.push(e?{path:s,field:o,fieldType:`Subquery`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`Subquery`})}else G(o,K)?gN(o[K.Symbol.Columns],s,n,r):gN(o,s,n,r)}return r}function _N(e){let t=e.getSQL();if(G(t.decoder,Wj))return t.decoder}function vN(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function yN(e){return e[K.Symbol.Columns]}function bN(e){return G(e,iM)?e._.alias:G(e,rM)?e[Bj].name:G(e,q)?void 0:e[K.Symbol.IsAlias]?e[K.Symbol.Name]:e[K.Symbol.BaseName]}function xN(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;var SN={and:FM,between:eN,eq:Y,exists:QM,gt:zM,gte:VM,ilike:iN,inArray:qM,arrayContains:oN,arrayContained:sN,arrayOverlaps:cN,isNull:XM,isNotNull:ZM,like:nN,lt:UM,lte:GM,ne:kM,not:LM,notBetween:tN,notExists:$M,notLike:rN,notIlike:aN,notInArray:YM,or:IM,sql:J},CN={sql:J,asc:lN,desc:uN};function wN(e,t,n,r=!1,i=!1,a=!0){let o=t?1:e.length,s=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let o;switch(t){case`Column`:o=e;break;case`SQL`:o=e.decoder;break;case`SQL.Aliased`:o=e.sql.decoder;break;case`Subquery`:o=i??uM;break;case`Nested`:o=uM;break;default:o=e.getSQL().decoder}return a&&e.mapFromJsonValue?t=>e.mapFromJsonValue(t):o.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>o.mapFromDriverValue(n(e,r)):e=>o.mapFromDriverValue(e)});for(let a=0;a<o;++a){let o=t?e:e[a];for(let e=0;e<n.length;++e){let t=n[e];if(t.selection){if(o[t.key]===null)continue;if(r){if(o[t.key]=JSON.parse(o[t.key]),o[t.key]===null)continue}else i&&typeof o[t.key]==`string`&&(o[t.key]=JSON.parse(o[t.key]));if(t.isArray){wN(o[t.key],!1,t.selection,!1,i);continue}wN(o[t.key],!0,t.selection,!1,i);continue}if(o[t.key]===null)continue;let a=s[e];a&&(o[t.key]=a(o[t.key]))}}return e}function TN(e,t,n,r=!1,i=!1){let a=t?1:e.length,o=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let a;switch(t){case`Column`:a=e;break;case`SQL`:a=e.decoder;break;case`SQL.Aliased`:a=e.sql.decoder;break;case`Subquery`:a=i??uM;break;case`Nested`:a=uM;break;default:a=e.getSQL().decoder}return a.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>a.mapFromDriverValue(n(e,r)):e=>a.mapFromDriverValue(e)}),s=Array(a);for(let c=0;c<a;++c){let a=t?e:e[c],l={};for(let e=0;e<n.length;++e){let t=n[e],s=a[e];if(t.selection){if(s===null){l[t.key]=null;continue}if(r){if(s=JSON.parse(s),s===null){l[t.key]=null;continue}}else i&&typeof s==`string`&&(s=JSON.parse(s));t.isArray?wN(s,!1,t.selection,!1,i):wN(s,!0,t.selection,!1,i),l[t.key]=s;continue}if(s===null){l[t.key]=null;continue}let c=o[e];l[t.key]=c?c(s):s}s[c]=l}return t?s[0]:s}function EN({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?TN(t?o[0]:o,t,e,n,r):wN(t?o[0]:o,t,e,n,r,i))}function DN(e,t,n,r,i,a,o,s,c){let l=[],u=[],d=!1,f=e.map(()=>`c${s.n++}`),p=e.map((e,t)=>c?f[t]:`${JSON.stringify(e.key)}: ${f[t]}`);l.push(c?`let [ ${p.join(`, `)} ] = ${t};`:`let { ${p.join(`, `)} } = ${t};`);for(let[t,{field:c,fieldType:p,key:m,codec:h,isArray:g,selection:_,arrayDimensions:v,subqueryDecoder:y}]of e.entries()){let e=`${n}[${t}]`,ee=JSON.stringify(m),b=f[t];if(_){r?(l.push(`if (${b} !== null) ${b} = JSON.parse(${b});`),d=!0):i&&(l.push(`if (typeof ${b} === 'string') ${b} = JSON.parse(${b});`),d=!0);let t=`s${s.n++}`,n=o.length;if(o.push(`const { selection: ${t} } = ${e};`),g){let e=`j${s.n++}`,r=DN(_,`${b}[${e}]`,t,!1,i,!0,o,s,!1);if(r.hasWork){d=!0,l.push(`if (${b} !== null) {`),l.push(`\tfor (let ${e} = 0; ${e} < ${b}.length; ++${e}) {`);for(let e of r.bodyStmts)l.push(`\t\t${e}`);l.push(`\t\t${b}[${e}] = ${r.literal};`),l.push(` }`),l.push(`}`)}else o.splice(n,1)}else{let e=DN(_,b,t,!1,i,!0,o,s,!1);if(e.hasWork){d=!0,l.push(`if (${b} !== null) {`);for(let t of e.bodyStmts)l.push(`\t${t}`);l.push(`\t${b} = ${e.literal};`),l.push(`}`)}else o.splice(n,1)}u.push(`${ee}: ${b}`);continue}let te=``,ne=``,re=!1;switch(p){case`Column`:if(a&&c.mapFromJsonValue){re=!0;let e=s.n++;ne=`field: dec${e}`,te=`dec${e}.mapFromJsonValue`}else if(!c.mapFromDriverValue.isNoop){let e=s.n++;ne=`field: dec${e}`,te=`dec${e}.mapFromDriverValue`}break;case`SQL`:if(a&&c.decoder.mapFromJsonValue){re=!0;let e=s.n++;ne=`field: { decoder: dec${e} }`,te=`dec${e}.mapFromJsonValue`}else if(!c.decoder.mapFromDriverValue.isNoop){let e=s.n++;ne=`field: { decoder: dec${e} }`,te=`dec${e}.mapFromDriverValue`}break;case`SQL.Aliased`:if(a&&c.sql.decoder.mapFromJsonValue){re=!0;let e=s.n++;ne=`field: { sql: { decoder: dec${e} } }`,te=`dec${e}.mapFromJsonValue`}else if(!c.sql.decoder.mapFromDriverValue.isNoop){let e=s.n++;ne=`field: { sql: { decoder: dec${e} } }`,te=`dec${e}.mapFromDriverValue`}break;case`Subquery`:if(a&&y?.mapFromJsonValue){re=!0;let e=s.n++;ne=`subqueryDecoder: dec${e}`,te=`dec${e}.mapFromJsonValue`}else if(y&&!y.mapFromDriverValue.isNoop){let e=s.n++;ne=`subqueryDecoder: dec${e}`,te=`dec${e}.mapFromDriverValue`}break;case`Nested`:break;default:{let t=c.getSQL();if(a&&t.decoder.mapFromJsonValue){re=!0;let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),te=`dec${t}.mapFromJsonValue`}else if(!t.decoder.mapFromDriverValue.isNoop){let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),te=`dec${t}.mapFromDriverValue`}}}let ie=``;if(!re&&h&&(ie=`codec${s.n++}`),ne||ie){let t=[];ne&&t.push(ne),ie&&t.push(`codec: ${ie}`),o.push(`const { ${t.join(`, `)} } = ${e};`)}if(te||ie){d=!0;let e=b;ie&&(e=`${ie}(${e}, ${v})`),te&&(e=`${te}(${e})`),u.push(`${ee}: ${b} === null ? null : ${e}`)}else u.push(`${ee}: ${b}`)}return{bodyStmts:l,literal:`{ ${u.join(`, `)} }`,hasWork:d}}function ON({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=DN(e,`row`,`selection`,n,r,!a&&i,o,{n:0},!!a),c=[];c.push(` "use strict";
25
+ const { selection } = this;`);for(let e of o)c.push(`\t${e}`);if(a){if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\treturn ${s.literal};`)}else{c.push(` const { length } = rows;`),c.push(` const mapped = new Array(length);`),c.push(` for (let i = 0; i < length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\tmapped[i] = ${s.literal};`),c.push(` }`),c.push(` return mapped;`)}}else if(!s.hasWork)c.push(t?` return rows[0];`:` return rows;`);else if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\trows[0] = ${s.literal};`),c.push(` return rows[0];`)}else{c.push(` for (let i = 0; i < rows.length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\trows[i] = ${s.literal};`),c.push(` }`),c.push(` return rows;`)}c.push(` //# sourceURL=drizzle:jit-relational-query-mapper`);let l=c.join(`
26
+ `);return Object.assign(new fN(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function kN(e,t){let n=e[Jj][t];return n?G(n,Wj)?n:G(n,q.Aliased)?J`${e}.${J.identifier(n.fieldAlias)}`:J`${e}.${J.identifier(t)}`:J`${e}.${J.identifier(t)}`}function AN(e,t){if(t===RN)return;if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);if(typeof t!=`object`||G(t,mM))return Y(e,t);let n=Object.entries(t);if(!n.length)return;let r=[];for(let[t,i]of n)if(i!==RN){if(i===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`NOT`:{let t=AN(e,i);if(!t)continue;r.push(LM(t));continue}case`OR`:if(!i.length)throw Error(`Unexpected empty array in filters' 'OR' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);r.push(IM(...i.map(t=>AN(e,t))));continue;case`AND`:if(!i.length)throw Error(`Unexpected empty array in filters' 'AND' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);r.push(FM(...i.map(t=>AN(e,t))));continue;case`isNotNull`:case`isNull`:if(!i)continue;r.push(SN[t](e));continue;case`in`:r.push(SN.inArray(e,i));continue;case`notIn`:r.push(SN.notInArray(e,i));continue;default:r.push(SN[t](e,i));continue}}if(r.length)return FM(...r)}function jN(e,t,n={},r={},i,a=0){if(t===RN)return;if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);let o=Object.entries(t);if(!o.length)return;let s=[];for(let[t,c]of o)if(c!==RN){if(c===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`RAW`:{let t=typeof c==`function`?c(e,SN):c.getSQL();if(t===RN)continue;s.push(t);continue}case`OR`:if(!c.length)throw Error(`Unexpected empty array in filters' 'OR' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);s.push(IM(...c.map(t=>jN(e,t,n,r,i,a))));continue;case`AND`:if(!c.length)throw Error(`Unexpected empty array in filters' 'AND' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);s.push(FM(...c.map(t=>jN(e,t,n,r,i,a))));continue;case`NOT`:{let t=jN(e,c,n,r,i,a);if(!t)continue;s.push(LM(t));continue}default:{if(Object.prototype.hasOwnProperty.call(e[Jj],t)&&e[Jj][t]){let n=AN(kN(e,t),c);n&&s.push(n);continue}let o=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!o)throw new Gj({message:`Unknown relational filter field: "${t}"`});i&&(IN(i,o.targetTable),IN(i,o.throughTable));let l=xM(o.targetTable,`f${a}`),u=o.throughTable?xM(o.throughTable,`ft${a}`):void 0,d=r[o.targetTableName],f=typeof c==`boolean`,p=f?void 0:jN(l,c,d.relations,r,i,a+1);if(!f&&!p)continue;let{filter:m,joinCondition:h}=FN(o,e,l,u),g=FM(m,p),_=u?J`(select * from ${LN(l)} inner join ${LN(u)} on ${h}${J` where ${g}`.if(g)})`:J`(select * from ${LN(l)}${J` where ${g}`.if(g)})`;g&&s.push((c?QM:$M)(_))}}}return FM(...s)}function MN(e,t){if(typeof t==`function`){let n=t(e,CN);return n?G(n,q)?n:Array.isArray(n)?n.length?J.join(n.map(e=>G(e,q)?e:lN(e)),new sM(`, `)):void 0:G(n,Wj)?lN(n):void 0:void 0}let n=Object.entries(t).filter(([e,t])=>t);if(n.length)return J.join(n.map(([t,n])=>(n===`asc`?lN:uN)(kN(e,t))),new sM(`, `))}function NN(e,t,n,r){let i=[],a=[];for(let[o,s]of Object.entries(t)){let t=typeof s==`function`?s(e,{sql:SN.sql}):s;if(!t)continue;let c=t.getSQL(),l=n?_N(c):void 0,u=l&&(!r||!l.jsonSelectIdentifier)?J`${n.apply(l,r?`castInJson`:`cast`,J`(${c})`)} as ${J.identifier(o)}`:J`(${c}) as ${J.identifier(o)}`;u.decoder=c.decoder,i.push(u),a.push(l&&(!r||!l.mapFromJsonValue)?{key:o,field:u,fieldType:`SQL`,codec:n.get(l,r?`normalizeInJson`:`normalize`),arrayDimensions:l.dimensions}:{key:o,field:u,fieldType:`SQL`})}return{sql:i.length?J.join(i,new sM(`, `)):void 0,selection:a}}function PN({_:{column:e,key:t}}){return J.identifier(G(e,Wj)?e.name:G(e,q.Aliased)?e.fieldAlias:t)}function FN(e,t,n,r){if(e.through){let i=e.sourceColumns.map((n,i)=>{let a=e.through.source[i];return Y(J`${t}.${PN(n)}`,J`${r}.${PN(a)}`)}),a=e.targetColumns.map((t,i)=>{let a=e.through.target[i];return Y(J`${r}.${PN(a)}`,J`${n}.${PN(t)}`)});return{filter:FM(jN(e.isFilterReversed?t:n,e.where),...i),joinCondition:FM(...a)}}return{filter:FM(...e.sourceColumns.map((r,i)=>{let a=e.targetColumns[i];return Y(J`${t}.${PN(r)}`,J`${n}.${PN(a)}`)}),jN(e.isFilterReversed?t:n,e.where))}}function IN(e,t){if(!t||!G(t,iM))return;let n=t._.alias,r=e.get(n);if(r&&r._.sql!==t._.sql)throw new Gj({message:`Different subqueries with the same alias "${n}" are used in a single relational query - make sure every subquery in schema has a unique alias`});e.set(n,t)}function LN(e){return J`${e[Qj]?J`${J`${J.identifier(e[qj]??``)}.`.if(e[qj])}${J.identifier(e[Xj])} as ${e}`:e}`}var RN=Symbol.for(`drizzle:EmptyFilter`),zN=class{static[W]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default(e){return this.$defaultFn(e)}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate(e){return this.$onUpdateFn(e)}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e,t){this.config.name===``&&(this.config.name=t(e))}},BN=class extends rM{static[W]=`SQLiteViewBase`},VN={},HN={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},UN={cast:`castArray`,castArray:`castArray`,castInJson:`castArrayInJson`,castArrayInJson:`castArrayInJson`,castParam:`castArrayParam`,castArrayParam:`castArrayParam`,normalize:`normalizeArray`,normalizeArray:`normalizeArray`,normalizeInJson:`normalizeArrayInJson`,normalizeArrayInJson:`normalizeArrayInJson`,normalizeParam:`normalizeParamArray`,normalizeParamArray:`normalizeParamArray`},WN=class{resolveTypes;codecs;static[W]=`CodecsCollection`;constructor(e,t=VN){this.resolveTypes=e,this.codecs=t}get(e,t,n){let r=n??e.codec;if(!r)return;let i=e.dimensions?UN[t]:HN[t];return this.codecs[r]?.[i]}apply(e,t,n,r){let i=r??e.codec;if(!i)return n;let a=e.dimensions?UN[t]:HN[t],o=this.codecs[i]?.[a];return o?a===`castParam`||a===`castArrayParam`?o(n,e,e.dimensions):o(n,e.dimensions):n}},GN={int:`integer`,int2:`integer`,int8:`integer`,tinyint:`integer`,smallint:`integer`,mediumint:`integer`,bool:`integer:boolean`,boolean:`integer:boolean`,float:`real`,double:`real`,"double precision":`real`,decimal:`numeric`,character:`text`,varchar:`text`,"varying character":`text`,nchar:`text`,"native character":`text`,nvarchar:`text`,clob:`text`,json:`text:json`};function KN(e){return GN[e]??e}var qN=typeof Buffer>`u`?new TextEncoder:void 0,JN=qN?e=>qN.encode(e):e=>Buffer.from(e),YN={integer:{integer:`integer`,"integer:boolean":`integer`,"integer:timestamp":`integer`,"integer:timestamp_ms":`integer`,real:`integer`,text:`integer`,"text:json":`integer`,blob:`integer`,"blob:json":`integer`,"blob:bigint":`integer`,numeric:`integer`,"numeric:number":`integer`,"numeric:bigint":`integer`},"integer:boolean":{integer:`integer:boolean`,"integer:boolean":`integer:boolean`,"integer:timestamp":`integer:boolean`,"integer:timestamp_ms":`integer:boolean`,real:`integer:boolean`,text:`integer:boolean`,"text:json":`integer:boolean`,blob:`integer:boolean`,"blob:json":`integer:boolean`,"blob:bigint":`integer:boolean`,numeric:`integer:boolean`,"numeric:number":`integer:boolean`,"numeric:bigint":`integer:boolean`},"integer:timestamp":{integer:`integer:timestamp`,"integer:boolean":`integer:timestamp`,"integer:timestamp":`integer:timestamp`,"integer:timestamp_ms":`integer:timestamp`,real:`integer:timestamp`,text:`integer:timestamp`,"text:json":`integer:timestamp`,blob:`integer:timestamp`,"blob:json":`integer:timestamp`,"blob:bigint":`integer:timestamp`,numeric:`integer:timestamp`,"numeric:number":`integer:timestamp`,"numeric:bigint":`integer:timestamp`},"integer:timestamp_ms":{integer:`integer:timestamp_ms`,"integer:boolean":`integer:timestamp_ms`,"integer:timestamp":`integer:timestamp_ms`,"integer:timestamp_ms":`integer:timestamp_ms`,real:`integer:timestamp_ms`,text:`integer:timestamp_ms`,"text:json":`integer:timestamp_ms`,blob:`integer:timestamp_ms`,"blob:json":`integer:timestamp_ms`,"blob:bigint":`integer:timestamp_ms`,numeric:`integer:timestamp_ms`,"numeric:number":`integer:timestamp_ms`,"numeric:bigint":`integer:timestamp_ms`},real:{integer:`real`,"integer:boolean":`real`,"integer:timestamp":`real`,"integer:timestamp_ms":`real`,real:`real`,text:`real`,"text:json":`real`,blob:`real`,"blob:json":`real`,"blob:bigint":`real`,numeric:`real`,"numeric:number":`real`,"numeric:bigint":`real`},text:{integer:`text`,"integer:boolean":`text`,"integer:timestamp":`text`,"integer:timestamp_ms":`text`,real:`text`,text:`text`,"text:json":`text`,blob:`text`,"blob:json":`text`,"blob:bigint":`text`,numeric:`numeric`,"numeric:number":`text`,"numeric:bigint":`text`},"text:json":{integer:`text:json`,"integer:boolean":`text:json`,"integer:timestamp":`text:json`,"integer:timestamp_ms":`text:json`,real:`text:json`,text:`text:json`,"text:json":`text:json`,blob:`text:json`,"blob:json":`blob:json`,"blob:bigint":`text:json`,numeric:`text:json`,"numeric:number":`text:json`,"numeric:bigint":`text:json`},blob:{integer:`blob`,"integer:boolean":`blob`,"integer:timestamp":`blob`,"integer:timestamp_ms":`blob`,real:`blob`,text:`blob`,"text:json":`blob`,blob:`blob`,"blob:json":`blob`,"blob:bigint":`blob`,numeric:`blob`,"numeric:number":`blob`,"numeric:bigint":`blob`},"blob:json":{integer:`blob:json`,"integer:boolean":`blob:json`,"integer:timestamp":`blob:json`,"integer:timestamp_ms":`blob:json`,real:`blob:json`,text:`blob:json`,"text:json":`blob:json`,blob:`blob:json`,"blob:json":`blob:json`,"blob:bigint":`blob:json`,numeric:`blob:json`,"numeric:number":`blob:json`,"numeric:bigint":`blob:json`},"blob:bigint":{integer:`blob:bigint`,"integer:boolean":`blob:bigint`,"integer:timestamp":`blob:bigint`,"integer:timestamp_ms":`blob:bigint`,real:`blob:bigint`,text:`blob:bigint`,"text:json":`blob:bigint`,blob:`blob:bigint`,"blob:json":`blob:bigint`,"blob:bigint":`blob:bigint`,numeric:`blob:bigint`,"numeric:number":`blob:bigint`,"numeric:bigint":`blob:bigint`},numeric:{integer:`numeric`,"integer:boolean":`numeric`,"integer:timestamp":`numeric`,"integer:timestamp_ms":`numeric`,real:`numeric`,text:`numeric`,"text:json":`numeric`,blob:`numeric`,"blob:json":`numeric`,"blob:bigint":`numeric`,numeric:`numeric`,"numeric:number":`numeric`,"numeric:bigint":`numeric`},"numeric:number":{integer:`numeric:number`,"integer:boolean":`numeric:number`,"integer:timestamp":`numeric:number`,"integer:timestamp_ms":`numeric:number`,real:`numeric:number`,text:`numeric:number`,"text:json":`numeric:number`,blob:`numeric:number`,"blob:json":`numeric:number`,"blob:bigint":`numeric:number`,numeric:`numeric:number`,"numeric:number":`numeric:number`,"numeric:bigint":`numeric:number`},"numeric:bigint":{integer:`numeric:bigint`,"integer:boolean":`numeric:bigint`,"integer:timestamp":`numeric:bigint`,"integer:timestamp_ms":`numeric:bigint`,real:`numeric:bigint`,text:`numeric:bigint`,"text:json":`numeric:bigint`,blob:`numeric:bigint`,"blob:json":`numeric:bigint`,"blob:bigint":`numeric:bigint`,numeric:`numeric:bigint`,"numeric:number":`numeric:bigint`,"numeric:bigint":`numeric:bigint`}};function XN(e,t){return YN[e]?.[t]}var ZN=class{static[W]=`SQLiteForeignKeyBuilder`;reference;_onUpdate;_onDelete;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new QN(e,this)}},QN=class{table;static[W]=`SQLiteForeignKey`;reference;onUpdate;onDelete;constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[Kj],...r,n[0].table[Kj],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function $N(e){function t(){if(typeof e==`function`){let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignColumns:r}}return e}return new ZN(t)}var eP=class extends zN{static[W]=`SQLiteColumnBuilder`;foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:`always`,mode:t?.mode??`virtual`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>((n,r)=>{let i=new ZN(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)})(n,r))}},tP=class extends Wj{static[W]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},nP=class extends eP{static[W]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new rP(e,this.config)}},rP=class extends tP{static[W]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>JN(e.toString())},iP=class extends eP{static[W]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new aP(e,this.config)}},aP=class extends tP{static[W]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>JN(JSON.stringify(e))},oP=class extends eP{static[W]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new sP(e,this.config)}},sP=class extends tP{static[W]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function cP(e,t){let{name:n,config:r}=xN(e,t);return r?.mode===`bigint`?new nP(n):r?.mode===`buffer`?new oP(n):new iP(n)}var lP=class extends eP{static[W]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new uP(e,this.config)}},uP=class extends tP{static[W]=`SQLiteCustomColumn`;codec;sqlName;mapFromJsonValue;jsonSelectIdentifier;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapToDriverValue=t.customTypeParams.toDriver??this.mapToDriverValue,this.mapFromDriverValue=t.customTypeParams.fromDriver??this.mapFromDriverValue,this.mapFromJsonValue=t.customTypeParams.fromJson,this.jsonSelectIdentifier=t.customTypeParams.forJsonSelect;let n=typeof t.customTypeParams.codec==`string`||t.customTypeParams.codec===void 0?t.customTypeParams.codec:t.customTypeParams.codec(t.fieldConfig);this.codec=typeof n==`string`?KN(n):void 0}getSQLType(){return this.sqlName}};function dP(e){return(t,n)=>{let{name:r,config:i}=xN(t,n);return new lP(r,i,e)}}var fP=class extends eP{static[W]=`SQLiteBaseIntegerBuilder`;constructor(e,t,n){super(e,t,n),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},pP=class extends tP{static[W]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},mP=class extends fP{static[W]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new hP(e,this.config)}},hP=class extends pP{static[W]=`SQLiteInteger`;codec=`integer`},gP=class extends fP{static[W]=`SQLiteTimestampBuilder`;constructor(e,t){super(e,`object date`,`SQLiteTimestamp`),this.config.mode=t}defaultNow(){return this.default(J`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new _P(e,this.config)}},_P=class extends pP{static[W]=`SQLiteTimestamp`;codec=`integer:${this.config.mode}`;mode=this.config.mode;mapToDriverValue=e=>{if(typeof e==`number`)return e;let t=e.getTime();return this.config.mode===`timestamp`?Math.floor(t/1e3):t}},vP=class extends fP{static[W]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new yP(e,this.config)}},yP=class extends pP{static[W]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function bP(e,t){let{name:n,config:r}=xN(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new gP(n,r.mode):r?.mode===`boolean`?new vP(n,r.mode):new mP(n)}var xP=class extends eP{static[W]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new SP(e,this.config)}},SP=class extends tP{static[W]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},CP=class extends eP{static[W]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new wP(e,this.config)}},wP=class extends tP{static[W]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},TP=class extends eP{static[W]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new EP(e,this.config)}},EP=class extends tP{static[W]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function DP(e,t){let{name:n,config:r}=xN(e,t),i=r?.mode;return i===`number`?new CP(n):i===`bigint`?new TP(n):new xP(n)}var OP=class extends eP{static[W]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new kP(e,this.config)}},kP=class extends tP{static[W]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function AP(e){return new OP(e??``)}var jP=class extends eP{static[W]=`SQLiteTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`SQLiteText`),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new MP(e,this.config)}},MP=class extends tP{static[W]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},NP=class extends eP{static[W]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new PP(e,this.config)}},PP=class extends tP{static[W]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=xN(e,t);return r.mode===`json`?new NP(n):new jP(n,r)}function FP(){return{blob:cP,customType:dP,integer:bP,numeric:DP,real:AP,text:X}}function IP(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).map(e=>e.toLowerCase()).join(`_`)}function LP(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function RP(e){return e===`snake_case`?IP:e===`camelCase`?LP:e=>e}var zP=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),BP=class extends K{static[W]=`SQLiteTable`;static Symbol=Object.assign({},K.Symbol,{InlineForeignKeys:zP});[K.Symbol.Columns];[zP]=[];[K.Symbol.ExtraConfigBuilder]=void 0};function VP(e,t,n,r,i,a=e){let o=RP(i),s=new BP(e,r,a),c=typeof t==`function`?t(FP()):t,l=Object.fromEntries(Object.entries(c).map(([e,t])=>{let n=t;n.setName(e,o);let r=n.build(s).postBuild();return s[zP].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[K.Symbol.Columns]=l,u[K.Symbol.ExtraConfigColumns]=l,n&&(u[BP.Symbol.ExtraConfigBuilder]=n),u}function HP(e){return(t,n,r)=>VP(t,n,r,void 0,e)}var UP=class{static[W]=`SQLiteDialect`;codecs;mapperGenerators;constructor(e){this.codecs=new WN(KN,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:mN,relationalRows:ON}:{rows:hN,relationalRows:EN}}escapeName(e){return`"${e.replace(/"/g,`""`)}"`}escapeParam(e){return`?`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=e.length,n=Array(t+1),r=0;n[r++]=new sM(`with `);for(let i=0;i<t;++i){let a=e[i];n[r++]=i<t-1?J`${J.identifier(a._.alias)} as (${a._.sql}), `:J`${J.identifier(a._.alias)} as (${a._.sql}) `}return new q(n)}buildDeleteQuery({table:e,where:t,returning:n,withList:r,limit:i,orderBy:a,ignoreSelectionCastCodecs:o}){let s=this.buildWithCTE(r),c=n?J` returning ${this.buildSelection(n,{isSingleTable:!0,ignoreCastCodecs:o,table:e})}`:void 0,l=t?J` where ${t}`:void 0,u=this.buildOrderBy(a),d=this.buildLimit(i);return J`${s}delete from ${e}${l}${c}${u}${d}`}buildUpdateSet(e,t){let n=e[K.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length,a=Array(i);for(let e=0;e<r.length;++e){let o=r[e],s=n[o],c;if(t[o]!==void 0)c=t[o];else{let e=s.onUpdateFn?.();c=G(e,q)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new q(a)}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,joins:a,from:o,limit:s,orderBy:c,ignoreSelectionCastCodecs:l}){let u=this.buildWithCTE(i),d=this.buildUpdateSet(e,t),f=o&&new q([new sM(` from `),this.buildFromTable(o)]),p=this.buildJoins(a),m=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:l,table:e})}`:void 0,h=n?J` where ${n}`:void 0,g=this.buildOrderBy(c),_=this.buildLimit(s);return J`${u}update ${e} set ${d}${f}${p}${h}${m}${g}${_}`}buildSelection(e,{isSingleTable:t=!1,ignoreCastCodecs:n=!1,table:r}={}){let{length:i}=e,a=[],o=r?G(r,q)||G(r,iM)?void 0:r[K.Symbol.IsAlias]||r[K.Symbol.Schema]===void 0?r[K.Symbol.Name]:`${r[K.Symbol.Schema]}.${r[K.Symbol.Name]}`:void 0;for(let r=0;r<i;++r){let{field:s,codecOverride:c,column:l,fieldType:u}=e[r],d=c;switch(u){case`Column`:{let e;e=t?s.isAlias?J.identifier(CM(s).name):J.identifier(s.name):s.isAlias?CM(s):s;let r=n?e:this.codecs.apply(s,`cast`,e,d);a.push(s.isAlias?J`${r} as ${s}`:r);break}case`SQL.Aliased`:if(s.isSelectionField){let e=!t&&s.origin!==void 0?J`${J.identifier(s.origin)}.${J.identifier(s.fieldAlias)}`:J.identifier(s.fieldAlias);l&&!n?a.push(this.codecs.apply(l,`cast`,e,d)):a.push(e)}else{if(t&&o!==void 0){let{queryChunks:e}=s.sql,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(G(i,Wj)){let{table:e}=i;if((e[K.Symbol.IsAlias]||e[K.Symbol.Schema]===void 0?e[K.Symbol.Name]:`${e[K.Symbol.Schema]}.${e[K.Symbol.Name]}`)!==o){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,s.sql,d):s.sql);else{let e=new q(t);s.sql.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,s.sql,d):s.sql);a.push(J` as ${J.identifier(s.fieldAlias)}`)}break;case`SQL`:if(t&&o!==void 0){let{queryChunks:e}=s,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(G(i,Wj)){let{table:e}=i;if((e[K.Symbol.IsAlias]||e[K.Symbol.Schema]===void 0?e[K.Symbol.Name]:`${e[K.Symbol.Schema]}.${e[K.Symbol.Name]}`)!==o){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,s,d):s);else{let e=new q(t);s.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,s,d):s);break;case`Subquery`:if(s._.isWith)a.push(l&&!n?this.codecs.apply(l,`cast`,s,d):s);else{let e=J`(${s._.sql})`;a.push(J`${l&&!n?this.codecs.apply(l,`cast`,e,d):e} ${J.identifier(s._.alias)}`)}}r<i-1&&a.push(new sM(`, `))}return new q(a)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[n,r]of e.entries()){n===0&&t.push(new sM(` `));let i=r.table,a=r.on?J` on ${r.on}`:void 0;if(G(i,BP)){let e=i[BP.Symbol.Name],n=i[BP.Symbol.Schema],o=i[BP.Symbol.OriginalName],s=e===o?void 0:r.alias;t.push(J`${new sM(r.joinType)} join ${n?J`${J.identifier(n)}.`:void 0}${J.identifier(o)}${s&&J` ${J.identifier(s)}`}${a}`)}else t.push(J`${new sM(r.joinType)} join ${i}${a}`);n<e.length-1&&t.push(new sM(` `))}return new q(t)}buildLimit(e){return typeof e==`object`||typeof e==`number`?J` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e)for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new sM(`, `));return t.length>0?J` order by ${J.join(t)}`:void 0}buildFromTable(e){if(G(e,K)&&e[K.Symbol.IsAlias])return J`${J`${J.identifier(e[K.Symbol.Schema]??``)}.`.if(e[K.Symbol.Schema])}${J.identifier(e[K.Symbol.OriginalName])} ${J.identifier(e[K.Symbol.Name])}`;if(G(e,rM)&&e[Bj].isAlias){let t=J`${J.identifier(e[Bj].originalName)}`;return e[Bj].schema&&(t=J`${J.identifier(e[Bj].schema)}.${t}`),J`${t} ${J.identifier(e[Bj].name)}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,distinct:d,setOperators:f,ignoreSelectionCastCodecs:p}){let m=n??gN(t,void 0,this.codecs);for(let e of m)if(G(e.field,Wj)&&tM(e.field.table)!==(G(a,iM)?a._.alias:G(a,BN)?a[Bj].name:G(a,q)?void 0:tM(a))&&!(e=>o?.some(({alias:t})=>t===(e[K.Symbol.IsAlias]?tM(e):e[K.Symbol.BaseName])))(e.field.table)){let t=tM(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let h=!o||o.length===0,g=this.buildWithCTE(e),_=d?J` distinct`:void 0,v=this.buildSelection(m,{isSingleTable:h,table:a,ignoreCastCodecs:p||f.length>0}),y=this.buildFromTable(a),ee=this.buildJoins(o),b=r?J` where ${r}`:void 0,te=i?J` having ${i}`:void 0,ne=[];if(c)for(let[e,t]of c.entries())ne.push(t),e<c.length-1&&ne.push(new sM(`, `));let re=ne.length>0?J` group by ${J.join(ne)}`:void 0,ie=this.buildOrderBy(s),ae=this.buildLimit(l),oe=u?J` offset ${u}`:void 0,se=J`${g}select${_} ${v} from ${y}${ee}${b}${re}${te}${ie}${ae}${oe}`;return f.length>0?this.buildSetOperations(se,m,p,f):se}buildSetOperations(e,t,n,r){for(let n=0;n<r.length;++n){let i=r[n];e=this.buildSetOperationQuery({leftSelect:e,setOperator:i});let a=gN(i.rightSelect.getSelectedFields());for(let e=0;e<t.length;++e){let n=t[e],r=n.path.join(`.`),i=a.find(e=>e.path.join(`.`)===r),o=n.codecOverride??n.column?.codec,s=i.codecOverride??i.column?.codec;n.codecOverride=o&&s?XN(o,s):o}}for(let e=0;e<t.length;++e){let n=t[e];n.codec=n.codecOverride?this.codecs.get(n.column,`normalize`,n.codecOverride):n.codec}return n?e:J`select ${this.buildSelection(t.map(e=>{if(e.fieldType===`SQL.Aliased`){let t=e.field.clone();return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Column`&&e.field.isAlias){let t=new q.Aliased(J`${J.identifier(e.field.name)}`,e.field.name);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Subquery`){let t=new q.Aliased(J`${e.field.getSQL()}`,e.field._.alias);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}return e}),{isSingleTable:!0,ignoreCastCodecs:n})} from (${e}) ${J.identifier(`drizzle_union`)}`}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=J`${e.getSQL()} `,c=J`${r.withoutSelectionCastCodecs().getSQL()}`,l;if(a&&a.length>0){let e=[];for(let t of a)if(G(t,tP))e.push(J.identifier(t.name));else if(G(t,q)){for(let e=0;e<t.queryChunks.length;e++){let n=t.queryChunks[e];G(n,tP)&&(t.queryChunks[e]=J.identifier(n.name))}e.push(J`${t}`)}else e.push(J`${t}`);l=J` order by ${J.join(e,new sM(`, `))}`}let u=typeof i==`object`||typeof i==`number`&&i>=0?J` limit ${i}`:void 0,d=new sM(`${t} ${n?`all `:``}`),f=o?J` offset ${o}`:void 0;return J`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,columnList:o,ignoreSelectionCastCodecs:s}){let c=e[K.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!G(t,q)?Object.keys(t.getSelectedFields()).map(e=>[e,c[e]]):l.filter(([e,t])=>!t.shouldDisableInsert()),d=Array(u.length*2+1),f=0;d[f++]=new sM(`(`);for(let e=0;e<u.length;++e){let[,{name:t}]=u[e];d[f++]=J.identifier(t),e<u.length-1&&(d[f++]=new sM(`, `))}d[f++]=new sM(`)`);let p=new q(d),m=Array.from({length:a?1:(u.length*2+1)*t.length+t.length});if(a)m[0]=t.getSQL();else{let e=t,n=0;m[n++]=new sM(`values `);for(let t=0;t<e.length;++t){let r=e[t];m[n++]=new sM(`(`);for(let e=0;e<u.length;++e){let[t,i]=u[e],a=r[t];if(a===void 0){let e;if(i.defaultFn!==void 0){let t=i.defaultFn();e=G(t,q)?t:J.param(t,i)}else if(i.default!==null&&i.default!==void 0)e=G(i.default,q)?i.default:J.param(i.default,i);else if(i.onUpdateFn!==void 0){let t=i.onUpdateFn();e=G(t,q)?t:J.param(t,i)}else e=new sM(`null`);m[n++]=e}else m[n++]=G(a,q)?a:new fM(a,i);e<u.length-1&&(m[n++]=new sM(`, `))}m[n++]=new sM(`)`),t<e.length-1&&(m[n++]=new sM(`, `))}}let h=this.buildWithCTE(i),g=new q(m),_=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:s,table:e})}`:void 0,v=n?.length?J.join(n):void 0;return J`${h}insert into ${e} ${p} ${g}${v}${_}`}sqlToQuery(e,t){return e.toQuery({escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,codecs:this.codecs,invokeSource:t})}buildRqbColumn(e,t,n,r,i,a){let o,s,c,l;if(G(t,Wj)){o=t,c=`Column`;let i=J`${e}.${J.identifier(t.name)}`,a=r&&t.jsonSelectIdentifier?t.jsonSelectIdentifier(i,J):this.codecs.apply(t,r?`castInJson`:`cast`,i);l=J`${a} as ${J.identifier(n)}`}else if(G(t,q)){o=G(t.decoder,Wj)?t.decoder:void 0,c=`SQL`;let i=J`${e}.${J.identifier(n)}`;l=J`${o?this.codecs.apply(o,r?`castInJson`:`cast`,i):i} as ${J.identifier(n)}`}else if(G(t,q.Aliased)){o=G(t.sql.decoder,Wj)?t.sql.decoder:void 0,c=`SQL.Aliased`;let i=J`${e}.${J.identifier(t.fieldAlias)}`;l=J`${o?this.codecs.apply(o,r?`castInJson`:`cast`,i):i} as ${J.identifier(n)}`}else if(G(t,iM)){let i=Object.values(t._.selectedFields)[0];G(i,Wj)?(o=i,s=i):G(i,q.Aliased)?(o=_N(i),s=i.sql.decoder):G(i,q)&&(o=_N(i),s=i.decoder),c=`Subquery`;let a=J`${e}.${J.identifier(t._.alias)}`;l=J`${o?this.codecs.apply(o,r?`castInJson`:`cast`,a):a} as ${J.identifier(n)}`}else if(oM(t)){let i=t.getSQL();o=G(i.decoder,Wj)?i.decoder:void 0,c=`SQLWrapper`;let a=J`${e}.${J.identifier(n)}`;l=J`${o?this.codecs.apply(o,r?`castInJson`:`cast`,a):a} as ${J.identifier(n)}`}else throw new Gj({message:t===void 0?`Unknown column: "${a}"."${n}"`:`Views and subqueries with nested selections are not supported by the relational query builder`});return i.push(o?{key:n,field:t,fieldType:c,subqueryDecoder:s,codec:!r||!o.mapFromJsonValue?this.codecs.get(o,r?`normalizeInJson`:`normalize`):void 0}:{key:n,field:t,fieldType:c,subqueryDecoder:s}),l}getSelectedTableColumns=(e,t)=>{let n=[],r=e[Jj],i=Object.entries(t),a;for(let[e,t]of i)if(t!==void 0&&(a||=t,t)){let t=r[e];n.push({column:t,tsName:e})}if(a===!1)for(let[e,i]of Object.entries(r))t[e]!==!1&&n.push({column:i,tsName:e});return n};buildColumns=(e,t,n,r,i)=>{if(!i?.columns)return J.join(Object.entries(e[Jj]).map(([i,a])=>this.buildRqbColumn(e,a,i,n,t,r)),new sM(`, `));let a=[],o=this.getSelectedTableColumns(e,i?.columns);for(let{column:i,tsName:s}of o)a.push(this.buildRqbColumn(e,i,s,n,t,r));return a.length?J.join(a,new sM(`, `)):void 0};buildRelationalQuery({schema:e,table:t,tableConfig:n,queryConfig:r,relationWhere:i,mode:a,isNested:o,errorPath:s,depth:c,throughJoin:l,jsonb:u,withSubqueries:d}){let f=[],p=a===`first`,m=r===!0?void 0:r,h=s??``,g=c??0,_=d??new Map;g||(IN(_,t),t=xM(t,`d${g}`));let v=p?1:m?.limit,y=m?.offset,ee=this.buildColumns(t,f,!!o,n.name,m),b=m&&`where`in m&&i?FM(jN(t,m.where,n.relations,e,_),i):m&&`where`in m?jN(t,m.where,n.relations,e,_):i,te=m?.orderBy?MN(t,m.orderBy):void 0,ne=m?.extras?NN(t,m.extras,this.codecs,!!o):void 0;ne&&f.push(...ne.selection);let re;switch(m){case void 0:break;default:{let{with:r}=m;if(!r)break;let i=Object.entries(r).filter(([e,t])=>t);if(!i.length)break;let a=Array(i.length*2-1);for(let r=0,s=0;r<i.length;++r){let[c,l]=i[r],d=n.relations[c];if(!d)throw new Gj({message:`Unknown relation "${n.name}" -> "${c}"`});let p=d.relationType===`one`;IN(_,d.targetTable),IN(_,d.throughTable);let m=xM(d.targetTable,`d${g+1}`),v=d.throughTable?xM(d.throughTable,`tr${g}`):void 0,{filter:y,joinCondition:ee}=FN(d,t,m,v),b=v?J` inner join ${LN(v)} on ${ee}`:void 0,te=this.buildRelationalQuery({table:m,mode:p?`first`:`many`,schema:e,queryConfig:l,tableConfig:e[d.targetTableName],relationWhere:y,isNested:!0,errorPath:`${h.length?`${h}.`:``}${c}`,depth:g+1,withSubqueries:_,throughJoin:b,jsonb:u});f.push({field:m,fieldType:`Nested`,key:c,selection:te.selection,isArray:!p,isOptional:(d.optional??!1)||l!==!0&&!!l.where});let ne=J.join(te.selection.map(e=>J`${new sM(this.escapeString(e.key))}, ${e.selection?J`${u}(${J.identifier(e.key)})`:J.identifier(e.key)}`),new sM(`, `)),re=o?u:J`json`,ie=p?J`(select ${re}_object(${ne}) as ${J.identifier(`r`)} from (${te.sql}) as ${J.identifier(`t`)}) as ${J.identifier(c)}`:J`(select ${re}_group_array(json_object(${ne})) as ${J.identifier(`r`)} from (${te.sql}) as ${J.identifier(`t`)}) as ${J.identifier(c)}`;a[s++]=ie,r<i.length-1&&(a[s++]=new sM(`, `))}re=new q(a);break}}let ie=[ee,ne?.sql,re].filter(e=>e!==void 0);if(!ie.length)throw new Gj({message:`No fields selected for table "${n.name}"${h?` ("${h}")`:``}`});let ae=J.join(ie,new sM(`, `)),oe=g?void 0:this.buildWithCTE([..._.values()]);return{sql:J`${oe}select ${ae} from ${LN(t)}${l}${J` where ${b}`.if(b)}${J` order by ${te}`.if(te)}${J` limit ${v}`.if(v!==void 0)}${J` offset ${y}`.if(y!==void 0)}`,selection:f}}},WP=class{name;value;static[W]=`SQLiteCheckBuilder`;brand;constructor(e,t){this.name=e,this.value=t}build(e){return new GP(e,this)}},GP=class{table;static[W]=`SQLiteCheck`;name;value;constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}};function KP(e,t){return new WP(e,t)}var qP=class{name;unique;static[W]=`SQLiteIndexBuilderOn`;constructor(e,t){this.name=e,this.unique=t}on(...e){return new JP(this.name,e,this.unique)}},JP=class{static[W]=`SQLiteIndexBuilder`;config;constructor(e,t,n){this.config={name:e,columns:t,unique:n,where:void 0}}where(e){return this.config.where=e,this}build(e){return new YP(this.config,e)}},YP=class{static[W]=`SQLiteIndex`;config;isNameExplicit;constructor(e,t){this.config={...e,table:t},this.isNameExplicit=!!e.name}};function XP(e){return new qP(e,!1)}function ZP(e){return new qP(e,!0)}function QP(...e){return e[0].columns?new $P(e[0].columns,e[0].name):new $P(e)}var $P=class{static[W]=`SQLitePrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new eF(e,this.columns,this.name)}},eF=class{table;static[W]=`SQLitePrimaryKey`;columns;name;isNameExplicit;constructor(e,t,n){this.table=e,this.columns=t,this.name=n,this.isNameExplicit=!!n}getName(){return this.name??`${this.table[BP.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}};function tF(e){return G(e,BP)?[`${e[K.Symbol.BaseName]}`]:G(e,iM)?e._.usedTables??[]:G(e,q)?e.usedTables??[]:[]}function nF(e,t){return new Proxy(e,new _M(t,!1))}var rF=class e{static[W]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(t,n,r){if(n===`_`)return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===Bj)return{...t[Bj],selectedFields:new Proxy(t[Bj].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=(G(t,iM)?t._.selectedFields:G(t,rM)?t[Bj].selectedFields:t)[n];if(i===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}if(G(i,q.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!i.isSelectionField)return i.sql;let e=i.clone();return e.isSelectionField=!0,e.origin=this.config.alias,e}if(G(i,q)){if(this.config.sqlBehavior===`sql`)return i;throw Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return G(i,Wj)?this.config.alias?new Proxy(i,new hM(new Proxy(i.table,new _M(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):i:typeof i!=`object`||!i?i:new Proxy(i,new e(this.config))}},iF=class{static[W]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}withoutSelectionCastCodecs(){return this}},aF=class{builder;static[W]=`SQLiteSelectBuilder`;fields;session;dialect;withList;distinct;constructor(e,t=oF){this.builder=t,this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;return n=this.fields?this.fields:G(e,iM)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):G(e,BN)?e[Bj].selectedFields:G(e,q)?{}:yN(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},oF=class extends iF{static[W]=`SQLiteSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=bN(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of tF(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,n)=>{let r=this.tableName,i=bN(t);for(let e of tF(t))this.usedTables.add(e);if(typeof i==`string`&&this.config.joins?.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(this.config.fieldsFlat=void 0,this.config.mapper=void 0,!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==`string`&&(this.config.fields={[r]:this.config.fields}),typeof i==`string`&&!G(t,q))){let e=G(t,iM)?t._.selectedFields:G(t,rM)?t[Bj].selectedFields:t[K.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new rF({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);crossJoin=this.createJoin(`cross`);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(cF()):n;if(!vN(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);except=this.createSetOperator(`except`,!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new rF({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new rF({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new rF({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new rF({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enabled:!0,autoInvalidate:!0}:e===!1?{enabled:!1}:{enabled:!0,autoInvalidate:!0,...e},this}getSQL(){return this.config.fieldsFlat??=gN(this.config.fields,void 0,this.dialect.codecs),this.dialect.buildSelectQuery(this.config)}toSQL(){return this.dialect.sqlToQuery(this.getSQL())}as(e){let t=[];if(t.push(...tF(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...tF(e.table));return new Proxy(new iM(this.withoutSelectionCastCodecs().getSQL(),this.config.fields,e,!1,[...new Set(t)]),new rF({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new rF({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}withoutSelectionCastCodecs(){return this.config.ignoreSelectionCastCodecs=!0,this}$dynamic(){return this}};function sF(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!vN(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var cF=()=>({union:lF,unionAll:uF,intersect:dF,except:fF}),lF=sF(`union`,!1),uF=sF(`union`,!0),dF=sF(`intersect`,!1),fF=sF(`except`,!1),pF=class{static[W]=`SQLiteQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=G(e,UP)?e:void 0,this.dialectConfig=G(e,UP)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>{typeof r==`function`&&(r=r(n));let i=(`withoutSelectionCastCodecs`in r?r.withoutSelectionCastCodecs():r).getSQL();return new Proxy(new aM(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new rF({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new aF({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new aF({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new aF({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new aF({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new UP(this.dialectConfig),this.dialect}},mF=class{name;static[W]=`SQLiteViewBuilderCore`;constructor(e){this.name=e}config={}},hF=class extends mF{static[W]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new pF));let t=new rF({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new _F({config:{name:this.name,schema:void 0,selectedFields:n,query:e.withoutSelectionCastCodecs().getSQL().inlineParams()}}),t)}},gF=class extends mF{static[W]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=yN(VP(e,t,void 0,void 0,n))}existing(){return new Proxy(new _F({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new rF({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new _F({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new rF({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},_F=class extends BN{static[W]=`SQLiteView`;constructor({config:e}){super(e)}};function vF(e){return((t,n)=>n?new gF(t,n,e):new hF(t))}var yF={table:HP(`snake_case`),view:vF(`snake_case`)},bF=yF.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[KP(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=yF.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>bF.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:wD}).$type().notNull(),permissions:X({enum:ED}).$type().notNull().default(`write`),cycleLimit:bP().$type(),cycleGeneration:bP().notNull().default(0),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),reopensEventId:X().$type().references(()=>bF.eventId),reopening:bP().notNull().default(0)},e=>[KP(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),KP(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),KP(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),XP(`usine_trigger_events_item`).on(e.loopName,e.itemKey),XP(`usine_trigger_events_item_history`).on(e.itemKey),ZP(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),xF=yF.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>bF.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>bF.eventId)},e=>[QP({columns:[e.loopName,e.itemKey]})]),SF=yF.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:bP().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:bP({mode:`boolean`}).notNull().default(!1)},e=>[KP(`usine_item_cycle_generation`,J`${e.generation} >= 0`),KP(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),CF=yF.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>SF.itemKey),generation:bP().notNull(),loop:X().$type().notNull()},e=>[XP(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),KP(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),wF=yF.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>bF.eventId),itemKey:X().$type().notNull().references(()=>SF.itemKey)}),Q=yF.table(`usine_runs`,{runId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>Z.eventId),loopName:X().$type().notNull(),stateJson:X({mode:`json`}).$type().notNull(),resolvedFailureAttemptId:X().$type(),openedAt:X().notNull(),closedAt:X(),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),nextStartJson:X({mode:`json`}).$type()},e=>[KP(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),KP(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),TF=yF.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[QP({columns:[e.runId,e.stepName]}),KP(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=yF.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:bP({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:bP({mode:`boolean`}).notNull().default(!1),parentModel:X().$type(),startedAt:X().notNull(),outcomeJson:X({mode:`json`}).$type(),endedAt:X(),salvageJson:X({mode:`json`}).$type(),leftoversDiscardedAt:X(),startJson:X({mode:`json`}).$type(),reattachedAt:X(),commentsJson:X({mode:`json`}).$type()},e=>[KP(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),KP(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),KP(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),KP(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),ZP(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),ZP(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),$N({columns:[e.runId,e.stepName],foreignColumns:[TF.runId,TF.stepName]})]),EF=yF.table(`usine_attempt_transcripts`,{sequence:bP({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:hA}).notNull(),channelSequence:bP({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[KP(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),KP(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),KP(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),ZP(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),XP(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence)]),DF=yF.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>bF.eventId),channel:X({enum:WA}).$type(),approver:X().$type()},e=>[KP(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui' or (${e.channel} = 'github-ask' and ${e.approver} is not null)`)]),OF=yF.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),kF=yF.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:lj}).$type().notNull()},e=>[KP(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),AF=yF.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[KP(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),jF=yF.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:bP({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[KP(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),KP(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),ZP(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),MF=yF.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[KP(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),NF=yF.table(`usine_board_moves`,{moveId:bP({mode:`number`}).primaryKey({autoIncrement:!0}),repository:X().$type().notNull(),itemKey:X().$type().notNull(),movedAt:X().notNull(),fromLane:X().notNull(),toLane:X().notNull(),addedJson:X({mode:`json`}).$type().notNull(),removedJson:X({mode:`json`}).$type().notNull()},e=>[KP(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),KP(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),XP(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),PF=yF.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:bP({mode:`boolean`}).notNull()}),FF=yF.table(`usine_projection_revision`,{singleton:bP({mode:`number`}).primaryKey().default(1),revision:bP({mode:`number`}).notNull().default(0)},e=>[KP(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]),IF=F({eventId:bD,dedupKey:xD,payload:tE,receivedAt:jT,itemKey:aA,loop:CD,step:RO,approval:TD,permissions:DD,cycleLimit:R(sA),cycleGeneration:cA,repository:mD,revision:hD,task:Jk,agent:kO,parentModel:R(CO)}),LF=F({itemKey:aA,repository:mD,revision:hD,task:Jk,agent:kO,parentModel:R(CO),runId:oO,eventId:bD,loop:CD,state:BD,resolvedFailureAttemptId:R(Kk),openedAt:jT,closedAt:R(jT),stepName:RO,result:R(LO),approvedAt:R(jT),approvalChannel:R(GA),approver:R(Rk),againFrom:R(oO),againRequestedBy:R(Rk)}),RF=F({attemptId:Kk,runId:oO,stepName:RO,worker:BO,number:qk,brain:EO,task:Jk,agent:DO,operatorIntervened:_w,parentModel:R(CO),startedAt:jT,outcome:R(Nk),endedAt:R(jT),salvage:R(Lk),start:R(Gk),reattachedAt:R(jT),comments:R(I(FO))}),zF=F({sequence:_j,attemptId:Kk,direction:gA,envelope:Cj.fields.envelope,receivedAt:jT}),BF=F({runId:oO}),VF=F({reason:uj}),HF=F({revision:Fj}),UF=F({runId:oO,eventId:bD,dedupKey:xD,payload:tE,receivedAt:jT}),WF=F({...IF.fields,reopening:B}),GF=F({eventId:bD,dedupKey:xD}),KF=qC(I(IF)),qF=qC(I(WF)),JF=qC(I(GF)),YF=qC(I(LF)),XF=qC(I(UF)),ZF=qC(I(RF)),QF=qC(I(BF)),$F=qC(I(VF)),eI=qC(I(HF)),tI=qC(I(zF)),nI=iw(tE),rI=iw(jT),iI=iw(BD),aI=iw(Nk),oI=iw(Lk),sI=iw(I(FO)),cI=iw(Gk),lI=qC(I(F({nextStart:R(Wk)}))),uI=iw(LO),dI=iw(UA),fI=iw(kO),pI=iw(EO),mI=KC(ej),hI=e=>t=>Ag(t,t=>mI(t)?t:new QA({operation:e,cause:t})),gI=e=>new SD({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),_I=e=>new Aj({runId:e.runId,event:gI(e)}),vI=e=>new rj({event:gI(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:wi(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:wi(e.parentModel)}),yI=e=>new sO({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),bI=e=>Ai(wi(e.approvedAt),t=>new qA({approvedAt:t,source:Ai(wi(e.approvalChannel),t=>new KA({channel:t,approver:wi(e.approver)}))})),xI=e=>Ai(wi(e.againFrom),t=>new gj({from:t,requestedBy:wi(e.againRequestedBy)})),SI=e=>new zO({runId:e.runId,name:e.stepName,result:wi(e.result)}),CI=e=>new Xk({id:e.attemptId,runId:e.runId,stepName:e.stepName,worker:e.worker,number:e.number,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,parentModel:wi(e.parentModel),startedAt:e.startedAt,outcome:wi(e.outcome),endedAt:wi(e.endedAt),salvage:wi(e.salvage),start:wi(e.start),reattachedAt:wi(e.reattachedAt),comments:e.comments??[]}),wI=(e,t)=>new Mj({itemKey:e.itemKey,run:yI(e),step:SI(e),attempts:t.map(CI),resolvedFailureAttemptId:wi(e.resolvedFailureAttemptId),closedAt:wi(e.closedAt),approval:bI(e),runAgain:xI(e),repository:e.repository,task:e.task,agent:e.agent}),TI=e=>new Cj({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),EI=class extends H(`CycleBudgetReset`)({itemKey:aA,repository:mD,generation:cA}){},DI=class extends BT(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:fA}){},OI=F({...EI.fields,ask:rT(pA),resetPending:_w}),kI={itemKey:SF.itemKey,repository:SF.repository,generation:SF.generation,ask:SF.askJson,resetPending:SF.resetPending},AI=qC(I(OI),{onExcessProperty:`error`}),jI=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
27
+ select ${SF.generation} from ${SF}
28
+ where ${SF.itemKey} = ${Z.itemKey}
29
+ ), 0)`),n=j(`CycleBudget.get`)(function*(t){return yield*A({itemKey:t}),wi((yield*e.select(kI).from(SF).where(Y(SF.itemKey,t)).execute().pipe(k(AI)))[0])}),r=j(`CycleBudget.counts`)(function*(t){yield*A({itemKey:t.itemKey,generation:t.generation});let n=QM(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:CF.loop,admitted:J`count(*)`,completed:J`sum(case when ${YM(r,[...JD])} and ${n} then 1 else 0 end)`}).from(CF).innerJoin(Q,Y(Q.runId,CF.runId)).where(FM(Y(CF.itemKey,t.itemKey),Y(CF.generation,t.generation),IM(kM(r,`Canceled`),n))).groupBy(CF.loop).orderBy(lN(CF.loop)).execute();return yield*qC(I(dA))(i,{onExcessProperty:`error`})});return{admit:j(`CycleBudget.admit`)(function*(t){yield*A({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(T(i)&&T(i.value.ask))return yield*M(`Item cycle budget remains exhausted`,{itemKey:t.itemKey,askId:i.value.ask.value.id,loop:t.loop}),i.value.ask;if(w(t.cycleLimit))return S();yield*e.insert(SF).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(w(a))return yield*pg(Error(`Cycle budget missing after insertion`));let o=yield*r(a.value),s=o.find(({loop:e})=>e===t.loop);if(s===void 0||s.admitted<t.cycleLimit.value)return S();let c=new pA({id:fA.make(bD.make(JSON.stringify([t.event.id,a.value.generation]))),itemKey:t.itemKey,repository:t.repository,loop:t.loop,limit:t.cycleLimit.value,counts:[s,...o.filter(({loop:e})=>e!==t.loop)]});return yield*e.update(SF).set({askJson:iw(pA)(c)}).where(Y(SF.itemKey,t.itemKey)).execute(),yield*h_(`Item cycle budget exhausted; operator reset required`,{itemKey:t.itemKey,repository:t.repository,askId:c.id,loop:c.loop,limit:c.limit,completedCycles:c.completedCycles,counts:c.counts}),C(c)}),reserve:j(`CycleBudget.reserve`)(function*(t,i){if(w(t.cycleLimit))return;yield*A({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(w(a))return yield*pg(Error(`Run admitted without its cycle budget`));yield*e.insert(CF).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*M(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:j(`CycleBudget.asks`)(function*(){return(yield*e.select(kI).from(SF).where(ZM(SF.askJson)).execute().pipe(k(AI))).flatMap(({ask:e})=>Pi(e))}),pendingResets:j(`CycleBudget.pendingResets`)(function*(){return yield*e.select(kI).from(SF).where(Y(SF.resetPending,!0)).execute().pipe(k(AI))}),isCurrentEvent:j(`CycleBudget.isCurrentEvent`)(function*(e){yield*A({eventId:e.event.id,itemKey:e.itemKey});let t=E(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*M(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},MI=qC(I(F({observedEventId:R(bD),suppressedByRunId:R(oO),suppressedEventId:R(bD)}))),NI=qC(I(F({loop:CD,itemKey:aA,observedEventId:R(bD),suppressedByRunId:R(oO)}))),PI=qC(I(F({eventId:bD,reopensEventId:bD}))),FI=qC(I(F({eventId:bD,runId:oO}))),II=e=>{let t=(e,t)=>FM(Y(xF.loopName,e),Y(xF.itemKey,t)),n=j(`LoopItems.row`)(function*(n,r){return wi((yield*MI(yield*e.select({observedEventId:xF.observedEventId,suppressedByRunId:xF.suppressedByRunId,suppressedEventId:xF.suppressedEventId}).from(xF).where(t(n,r)).execute()))[0])});return{sighted:j(`LoopItems.sighted`)(function*(t,r,i){let a=Ai(yield*n(t,r),({observedEventId:e})=>wi(e));return yield*e.insert(xF).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[xF.loopName,xF.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:j(`LoopItems.unmatched`)(function*(n,r){yield*e.update(xF).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:j(`LoopItems.suppression`)(function*(e,t){return ji(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?S():C({runId:e,suppressedEventId:wi(t)}))}),startSuppression:j(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(Ri(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=Di(o);return yield*e.insert(xF).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[xF.loopName,xF.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:j(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(xF).set({suppressedEventId:i}).where(FM(t(n,r),ZM(xF.suppressedByRunId))).execute()}),lift:j(`LoopItems.lift`)(function*(n,r){yield*e.update(xF).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:j(`LoopItems.liftRun`)(function*(t){return(yield*e.update(xF).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(xF.suppressedByRunId,t)).returning({loopName:xF.loopName}).execute()).length>0}),sightings:j(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*ng(Da(n,100),t=>e.select({loop:xF.loopName,itemKey:xF.itemKey,observedEventId:xF.observedEventId,suppressedByRunId:xF.suppressedByRunId}).from(xF).where(qM(xF.itemKey,t)).execute().pipe(k(NI)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*ng(Da(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(qM(Z.reopensEventId,t)).orderBy(uN(Z.reopening)).execute().pipe(k(PI)))).flat(),o=new Map;for(let{eventId:e,reopensEventId:t}of a)o.has(t)||o.set(t,e);let s=e=>o.get(e)??e,c=new Map((yield*ng(Da(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(qM(Q.eventId,t)).execute().pipe(k(FI)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Ai(wi(n),s);return new Pj({loop:e,itemKey:t,event:i,run:ji(i,e=>wi(c.get(e))),suppressedBy:wi(r)})})})}},LI=e=>({appendTranscript:j(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(EF).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:dI(n),receivedAt:rI(r)}).onConflictDoNothing().returning({sequence:EF.sequence}).execute()).length>0}),transcript:j(`RunStoreQueries.transcript`)(function*(t){yield*A({attemptId:t.attemptId,query:t._tag});let n=$E(t,{TranscriptSessionsQuery:({attemptId:t})=>qM(EF.sequence,e.select({sequence:J`max(${EF.sequence})`}).from(EF).where(FM(Y(EF.attemptId,t),J`(
30
+ json_extract(${EF.envelope}, '$.payload._tag') = 'InterventionApplied'
31
+ OR (json_extract(${EF.envelope}, '$.payload._tag') = 'SessionEvent'
32
+ AND json_extract(${EF.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
33
+ )`)).groupBy(J`coalesce(json_extract(${EF.envelope}, '$.payload.event.session.id'), json_extract(${EF.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${EF.envelope}, '$.payload._tag')`,J`json_extract(${EF.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:EF.sequence,tokens:J`max(json_extract(${EF.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(EF).where(FM(Y(EF.attemptId,t),J`json_extract(${EF.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${EF.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${EF.envelope}, '$.payload.event.session.id')`).as(`highest`);return qM(EF.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(EF.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>FM(Y(EF.attemptId,e),zM(EF.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>E(t,{onNone:()=>Y(EF.attemptId,e),onSome:t=>FM(Y(EF.attemptId,e),UM(EF.sequence,t))})}),r=e.select({sequence:EF.sequence,attemptId:EF.attemptId,direction:EF.direction,envelope:EF.envelope,receivedAt:EF.receivedAt}).from(EF).where(n);return(yield*tI(yield*$E(t,{TranscriptSessionsQuery:()=>r.orderBy(lN(EF.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(lN(EF.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(lN(EF.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(lN(EF.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(uN(EF.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(TI).sort((e,t)=>e.sequence-t.sequence)})}),RI=(e,t)=>Dv(t.openedAt)-Dv(e.openedAt)||t.runId.localeCompare(e.runId),zI={eventId:bF.eventId,dedupKey:bF.dedupKey,payload:bF.payloadJson,receivedAt:bF.receivedAt,itemKey:Z.itemKey,loop:Z.loopName,step:Z.stepName,approval:Z.approval,permissions:Z.permissions,cycleLimit:Z.cycleLimit,cycleGeneration:Z.cycleGeneration,repository:Z.repository,revision:Z.revision,task:Z.task,agent:Z.agentJson,parentModel:Z.parentModel},BI=nF(bF,`approval_event`),VI={itemKey:Z.itemKey,runId:Q.runId,eventId:Q.eventId,loop:Q.loopName,state:Q.stateJson,resolvedFailureAttemptId:Q.resolvedFailureAttemptId,openedAt:Q.openedAt,closedAt:Q.closedAt,repository:Q.repository,revision:Q.revision,task:Q.task,agent:Q.agentJson,parentModel:Q.parentModel,stepName:TF.stepName,result:TF.result,approvedAt:BI.receivedAt,approvalChannel:DF.channel,approver:DF.approver,againFrom:OF.fromRunId,againRequestedBy:OF.requestedBy},HI={attemptId:$.attemptId,runId:$.runId,stepName:$.stepName,worker:$.workerName,number:$.attemptNumber,brain:$.brainJson,task:$.task,agent:$.agent,operatorIntervened:$.operatorIntervened,parentModel:$.parentModel,startedAt:$.startedAt,outcome:$.outcomeJson,endedAt:$.endedAt,salvage:$.salvageJson,start:$.startJson,reattachedAt:$.reattachedAt,comments:$.commentsJson},UI=J`json_extract(${Q.stateJson}, '$._tag')`,WI=qM(UI,[...JD]),GI=qM(UI,[...XD]),KI=e=>ew(tE)(fI(e)),qI=e=>{let t=j(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*KF(yield*e.select(zI).from(bF).innerJoin(Z,Y(Z.eventId,bF.eventId)).where(Y(bF.dedupKey,t)).execute())}),n=j(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*KF(yield*e.select(zI).from(Q).innerJoin(bF,Y(bF.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,bF.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(VI).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(TF,Y(TF.runId,Q.runId)).leftJoin(DF,Y(DF.runId,Q.runId)).leftJoin(BI,Y(BI.eventId,DF.eventId)).leftJoin(OF,Y(OF.eventId,Q.eventId)),i=j(`RunStoreQueries.runRows`)(function*(e){return yield*YF(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>O(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(FM(XM($.leftoversDiscardedAt),...t)).execute();return(yield*qC(I(F({attemptId:Kk,worker:BO,repository:mD,runId:oO,number:qk,permissions:DD,outcome:P})))(n)).map(({runId:e,number:t,outcome:n,...r})=>({...r,ref:Fk(e,t),succeeded:n===`Succeeded`,open:n===``}))}),o=j(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=j(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*A({attemptId:e}),_a(yield*a(Y($.attemptId,e)))}),c=j(`RunStoreQueries.attemptRows`)(function*(t){return yield*ZF(yield*e.select(HI).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=j(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*tg([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new YA({runId:e}):new kj({event:gI(s),itemKey:s.itemKey,run:yI(o),step:SI(o),attempts:r.map(CI),resolvedFailureAttemptId:wi(o.resolvedFailureAttemptId),closedAt:wi(o.closedAt),approval:bI(o),runAgain:xI(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:wi(o.parentModel),permissions:s.permissions})}),u=j(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=Oa((yield*ng(Da(t.map(({runId:e})=>e),100),t=>e.select(HI).from($).where(qM($.runId,t)).orderBy(lN($.runId),lN($.attemptNumber)).execute().pipe(k(ZF)))).flat(),({runId:e})=>e);return t.map(e=>wI(e,n[e.runId]??[]))}),d=j(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*ng(Da([...new Set(e)],100),e=>r().where(qM(Z.itemKey,e)).execute().pipe(k(YF)))).flat().sort(RI);return yield*u(t)}),f=j(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*tg([r().where(WI).orderBy(uN(Q.openedAt),uN(Q.runId)).execute().pipe(k(YF)),r().where(YM(UI,[...JD])).orderBy(uN(Q.openedAt),uN(Q.runId)).limit(e).execute().pipe(k(YF))]),i=[...t,...n].sort(RI);return yield*u(i)}),p=j(`RunStoreQueries.runEvents`)(function*(t){return(yield*ng(Da([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:bF.eventId,dedupKey:bF.dedupKey,payload:bF.payloadJson,receivedAt:bF.receivedAt}).from(Q).innerJoin(bF,Y(bF.eventId,Q.eventId)).where(qM(Q.runId,t)).execute().pipe(k(XF)))).flat().map(_I)}),m=j(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(YM(UI,[...JD])).orderBy(uN(Q.closedAt),uN(Q.runId)).limit(e).execute().pipe(k(YF));return yield*u(t)}),h=j(`RunStoreQueries.projectionRevision`)(function*(){return wi((yield*eI(yield*e.select({revision:FF.revision}).from(FF).where(Y(FF.singleton,1)).limit(1).execute()))[0]?.revision)}),g=j(`RunStoreQueries.updateState`)(function*(t,n,r){let i=UD(n)?null:rI(r??(yield*xv));if((yield*e.update(Q).set({stateJson:iI(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new YA({runId:t})}),_=j(`RunStoreQueries.resolveFailure`)(function*(t,n){yield*A({runId:t,attemptId:n}),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),v=j(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:pI(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:Di(t.parentModel),startedAt:rI(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:E(t.start,{onNone:()=>null,onSome:cI})}).execute()}),y=j(`RunStoreQueries.recordReattach`)(function*(t,n){yield*A({attemptId:t}),yield*e.update($).set({reattachedAt:rI(n)}).where(Y($.attemptId,t)).execute()}),ee=j(`RunStoreQueries.nextStart`)(function*(t){return wi((yield*lI(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),b=j(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:E(n,{onNone:()=>null,onSome:cI})}).where(Y(Q.runId,t)).execute()}),te=j(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*A({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:oI(n)}).where(Y($.attemptId,t)).execute()}),ne=j(`RunStoreQueries.recordComments`)(function*(t,n){yield*A({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:sI(n)}).where(Y($.attemptId,t)).execute()}),re=j(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:aI(n),endedAt:rI(r)}).where(FM(Y($.attemptId,t),XM($.outcomeJson))).execute()}),ie=j(`RunStoreQueries.amend`)(function*(t,n){yield*A({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:KI(n.agent),parentModel:Di(n.parentModel)}).where(Y(Q.runId,t)).execute()}),ae=j(`RunStoreQueries.markIntervened`)(function*(t){yield*A({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),oe=j(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),se=j(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(TF).set({result:uI(r)}).where(FM(Y(TF.runId,t),Y(TF.stepName,n))).execute()}),ce=j(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(DF,Y(DF.runId,t)).execute())>0}),le=j(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(bF).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:nI(n.payload),receivedAt:rI(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(DF).values({runId:t,eventId:n.id,channel:r.channel,approver:Di(r.approver)}).execute()}),ue=j(`RunStoreQueries.createRun`)(function*(t,n,r){let i=nF(Z,`candidate`),a=nF(Q,`candidate_run`),o=nF(kF,`ignored`);yield*e.insert(kF).select(e.select({eventId:i.eventId,reason:J`'superseded'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).leftJoin(o,Y(o.eventId,i.eventId)).where(FM(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),kM(i.eventId,n),XM(a.runId),XM(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:iI(new MD),openedAt:rI(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:KI(t.agent),parentModel:Di(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(TF).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),de=j(`RunStoreQueries.runForEvent`)(function*(t){return yield*QF(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),fe=j(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*$F(yield*e.select({reason:kF.reason}).from(kF).where(Y(kF.eventId,t)).execute())}),pe=j(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*QF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(FM(Y(Z.loopName,t),Y(Z.itemKey,n),WI)).orderBy(uN(Q.openedAt)).limit(1).execute())}),me=j(`RunStoreQueries.newestReopening`)(function*(t){return Ai(wi((yield*qF(yield*e.select({...zI,reopening:Z.reopening}).from(bF).innerJoin(Z,Y(Z.eventId,bF.eventId)).where(Y(Z.reopensEventId,t)).orderBy(uN(Z.reopening)).limit(1).execute()))[0]),e=>({submission:vI(e),reopening:e.reopening}))}),he=j(`RunStoreQueries.reopenedEvent`)(function*(t){let n=nF(bF,`reopened_event`);return wi((yield*JF(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),ge=j(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(OF).values({eventId:t,fromRunId:n.from,requestedBy:Di(n.requestedBy)}).execute()}),_e=j(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=S()){yield*e.insert(bF).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:nI(n.event.payload),receivedAt:rI(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:Di(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:KI(n.agent),parentModel:Di(n.parentModel),reopensEventId:Di(Ai(r,({eventId:e})=>e)),reopening:E(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):vI(i)}),ve=j(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return S();let i=yield*II(e).suppression(r.loop,r.itemKey);if(T(i))return yield*M(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),S();let a=yield*KF(yield*e.select(zI).from(bF).innerJoin(Z,Y(Z.eventId,bF.eventId)).leftJoin(Q,Y(Q.eventId,bF.eventId)).leftJoin(kF,Y(kF.eventId,bF.eventId)).where(FM(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),jI(e).currentEvent,XM(Q.runId),XM(kF.eventId))).orderBy(uN(bF.receivedAt)).execute());return wi(a[0]).pipe(Ai(e=>({submission:vI(e),eventIds:a.map(e=>e.eventId)})))}),ye=j(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*QF(yield*e.select({runId:Q.runId}).from(Q).where(FM(WI,kM(UI,`Waiting`))).execute())).map(({runId:e})=>e)}),be=j(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(kF,Y(kF.eventId,Z.eventId)).leftJoin(SF,Y(SF.itemKey,Z.itemKey)).leftJoin(xF,FM(Y(xF.loopName,Z.loopName),Y(xF.itemKey,Z.itemKey))).where(FM(XM(Q.runId),XM(kF.eventId),XM(SF.askJson),XM(xF.suppressedByRunId),jI(e).currentEvent)).execute();return(yield*ng(yield*qC(I(F({loop:CD,itemKey:aA})))(t),({loop:t,itemKey:n})=>O(function*(){return(yield*pe(t,n)).length>0?[]:yield*QF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(FM(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(uN(Q.openedAt),uN(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),xe=j(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=nF(Z,`candidate`),a=nF(Q,`candidate_run`);return(yield*e.insert(kF).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(FM(Y(i.loopName,t),Y(i.itemKey,n),qM(i.eventId,r),XM(a.runId)))).onConflictDoNothing().returning({eventId:kF.eventId}).execute()).length}),Se=j(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*QF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(FM(Y(Z.loopName,t),Y(Z.itemKey,n),GI)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(FM(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*xe(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:jI(e),loopItems:II(e),...LI(e),addAttempt:v,recordReattach:y,nextStart:ee,setNextStart:b,recordSalvage:te,recordComments:ne,amend:ie,markIntervened:ae,approvalExists:ce,blockingRun:pe,closeAttempt:re,createRun:ue,eventRouteByRun:n,ignoredEvent:fe,newestReopening:me,nextQueued:ve,reopenedEvent:he,recordRunAgain:ge,pendingContinuations:be,recordTriggerEvent:_e,runIdsToDrive:ye,recordApproval:le,revision:h,revokeQueued:xe,revokeUnstarted:Se,runSummaries:f,closedRunSummaries:m,itemRunSummaries:d,runEvents:p,runForEvent:de,snapshot:l,updateStepResult:se,updateAttemptParentModel:oe,updateState:g,resolveFailure:_}},JI=e=>({attemptWindows:j(`RunStoreQueries.attemptWindows`)(function*(t){yield*A({attemptId:t});let[n]=yield*e.select(HI).from($).where(Y($.attemptId,t)).execute().pipe(k(ZF));if(n===void 0)return yield*pg(Error(`No attempt ${t} recorded`));let r=Qk(CI(n));if(w(r))return yield*N(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new rA({own:r,overlapping:[]});let i=e.select({itemKey:Z.itemKey}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Y(Q.runId,n.runId));return new rA({own:r,overlapping:(yield*e.select(HI).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(FM(qM(Z.itemKey,i),Y($.agent,n.agent),kM($.attemptId,t))).orderBy($.startedAt).execute().pipe(k(ZF))).flatMap(e=>Pi(Qk(CI(e)))).filter(e=>nA(r.value,e))})})}),YI=XM($.leftoversDiscardedAt),XI=XM($.outcomeJson),ZI=e=>{let t=j(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${XI} then 1 else 0 end)`}).from($).where(YI).groupBy($.workerName).orderBy(lN($.workerName)).execute();return yield*qC(I(Nj))(t)});return{attemptCountsByWorker:t,openAttempts:j(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:j(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:rI(n)}).where(FM(Y($.workerName,t),YI)).returning({attemptId:$.attemptId}).execute()).length})}},QI=qk.make(3),$I=e=>wi(e.attempts.at(-1)).pipe(Fi(e=>w(e.outcome))),eL=(e,t,n)=>{let r=new jk({failure:n});return iA({failure:n,number:t.number,maxAutoAttempts:QI})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:tO(e)}},tL=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=$I(e);return w(r)?{_tag:`Unchanged`,reason:`NoOpenAttempt`}:r.value.id===t?Wi(n)?eL(e.run.state,r.value,n.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new Ak,state:eO(e.run.state),result:n.success}:{_tag:`Unchanged`,reason:`AttemptReplaced`}},nL=e=>ba(e,e=>Fi(e.salvage,e=>e._tag===`Pushed`)),rL=(e,t,n,r)=>{let i=e.run.state;if(!GD(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=S(),o=$I(e);if(i._tag===`Running`&&T(o)){if(Li(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:nL(e.attempts)};let r=eL(i,o.value,t);if(r._tag===`RunFailed`)return r;a=C(r)}let s=T(a)?new Uk:xi(r,()=>e.attempts.length===0?new zk:new Hk);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:$D(i),number:qk.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:nL(e.attempts)}},iL=e=>UD(e.run.state)?{_tag:`Canceled`,state:rO(e.run.state),attempt:e.run.state._tag===`Running`?Ai($I(e),e=>({id:e.id,outcome:new Mk})):S()}:{_tag:`AlreadyClosed`},aL=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:nO(t)}:t._tag===`Running`&&w($I(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},oL=(e,t)=>E(e,{onNone:()=>!1,onSome:e=>!Li(e,t)}),sL=(e,t)=>e._tag===`Owned`?e.run.state._tag===`Canceled`&&t?{_tag:`ReopenEvent`}:{_tag:`JoinRun`,run:e.run}:e.reason===`revoked`&&t?{_tag:`ReopenEvent`}:{_tag:`StayIgnored`,reason:e.reason},cL=e=>{if(e._tag!==`RunFailed`)return S();switch(e.outcome.failure._tag){case`QuestionFailure`:return C(`question`);case`BlockedFailure`:return C(`blocker`);default:return S()}},lL=(e,t)=>E(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),uL=(e,t)=>{if(w(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:WD(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:iO(n.state,t)}:{_tag:`OpenRun`}},dL=nT(oO).pipe(Mw(D(S()))),fL=class extends H(`@usine/engine/internal/Claim`)({result:mj,openedRun:dL,supersededRun:dL}){},pL=class extends U(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:Rj}){},mL=class extends U(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},hL=class extends U(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},gL=O(function*(){let e=yield*JA,t=yield*DE,n=qI(e),r=j(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return T(r)?new pj({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new sj({eventId:t.event.id,runId:n}))}),i=j(`RunStore.openRun`)(function*(e,t,n,i=S()){let a=yield*r(e,t,n);return new fL({result:a,openedRun:a._tag===`Claimed`?C(n):S(),supersededRun:i})}),a=e=>aj(e).pipe(qg(DE,t)),o=j(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return C({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?S():C({_tag:`Ignored`,reason:r.reason})}),s=j(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new fL({result:new dj({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(T(r)){let n=lL(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*M(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new fL({result:new fj({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*M(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new fL({result:new fj({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*M(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=uL(a===void 0?S():C((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*M(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new fL({result:new cj({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,C(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=j(`RunStore.recordAndClaim`)(function*(t,n){return yield*A({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>O(function*(){let r=qI(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=xi(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(w(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=sL(d.value,oL(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*M(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new fL({result:new sj({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*M(`Event remains ignored`,{eventId:u,reason:f.reason}),new fL({result:new dj({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(oj(t,i.event.dedupKey,e),C({eventId:i.event.id,reopening:e}));return yield*M(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},hI(`submit event`)),l=j(`RunStore.parkForApproval`)(function*(t){return yield*A({runId:t}),yield*e.transaction(e=>O(function*(){let n=qI(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=ZD(r.run.state);return yield*n.updateState(t,i),i}))},hI(`park run for approval`)),u=j(`RunStore.applyFinish`)(function*(e,t,n){if(yield*A({runId:t}),n._tag===`Unchanged`){yield*M(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*A({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*M(`Attempt completion decided`,$E(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*xv;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=j(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Ai(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*M(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:xi(i,()=>`none yet`)}):yield*M(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new Rj({attempt:t,event:e.event,run:new sO({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=j(`RunStore.beginAttempt`)(function*(t,n,r){return yield*A({runId:t,worker:n}),yield*e.transaction(e=>O(function*(){let i=qI(e),a=yield*i.snapshot(t),o=new Sk({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=rL(a,o,r,s);if(c._tag===`RunClosed`)return yield*M(`Attempt start skipped`,{runId:t,state:c.state._tag}),new hL;if(c._tag===`RunFailed`)return yield*u(i,t,c),new mL;if(c._tag===`ReattachAttempt`){let e=yield*xv,r=new Xk({...c.attempt,reattachedAt:C(e)});return yield*i.recordReattach(r.id,e),yield*A({attemptId:r.id}),yield*M(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*g_(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new pL({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}T(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=Kk.make(`${t}/${a.step.name}/${c.number}`),d=yield*xv,p=new Xk({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:S(),endedAt:S(),salvage:S(),start:C(c.start),reattachedAt:S()});return yield*i.addAttempt(p),T(s)&&(yield*i.setNextStart(t,S())),yield*M(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Ai(c.resume,({ref:e})=>e)}),new pL({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},hI(`begin attempt`)),m=j(`RunStore.recordSalvage`)(function*(t,n){yield*A({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>qI(e).recordSalvage(t,n)),yield*M(`Attempt salvage recorded`,$E(n,{Pushed:({ref:e,commit:n})=>({attemptId:t,ref:e,commit:n}),Retained:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},hI(`record attempt salvage`)),h=j(`RunStore.recordComments`)(function*(t,n){yield*A({attemptId:t,comments:n.length}),yield*e.transaction(e=>qI(e).recordComments(t,n)),yield*M(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},hI(`record attempt comments`)),g=j(`RunStore.attemptWindows`)(function*(t){yield*A({attemptId:t});let n=yield*JI(e).attemptWindows(t);return yield*N(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:T(n.own),ended:Ri(n.own,({endedAt:e})=>T(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},hI(`read attempt windows`)),_=j(`RunStore.discardLeftovers`)(function*(t){yield*A({worker:t});let n=yield*xv;return yield*e.transaction(e=>ZI(e).discardLeftovers(t,n))},hI(`discard attempt leftovers`)),v=j(`RunStore.openAttempts`)(function*(t){return yield*A({worker:t}),yield*ZI(e).openAttempts(t)},hI(`count open attempts`)),y=j(`RunStore.finishAttempt`)(function*(t,n){return yield*A({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>O(function*(){let r=qI(e),i=yield*r.snapshot(t.runId),a=tL(i,t.id,n);yield*u(r,t.runId,a);let o=cL(a);return T(o)&&(yield*d(r,i,o.value)),a}))},hI(`finish attempt`)),ee=j(`RunStore.resolveFailure`)(function*(t,n){return yield*A({runId:t,attemptId:n}),yield*e.transaction(e=>O(function*(){let r=qI(e),i=yield*r.snapshot(t),a=i.attempts.at(-1);if(!KD(i.run.state).canResolveFailure||a?.id!==n)return yield*M(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:i.run.state._tag,latestAttemptId:a?.id}),yield*new XA({runId:t,operation:`resolveFailure`,state:i.run.state._tag});if(Li(i.resolvedFailureAttemptId,n))return yield*M(`Run failure already resolved`,{runId:t,attemptId:n}),!1;yield*r.resolveFailure(t,n);let o=yield*r.loopItems.liftRun(t);return yield*M(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:o}),o}))},hI(`resolve run failure`)),b=j(`RunStore.approve`)(function*(t,n,r){return yield*A({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>O(function*(){let i=qI(e);if(yield*i.approvalExists(t))return!1;let a=yield*i.snapshot(t);return a.run.state._tag===`Waiting`?(yield*i.recordApproval(t,n,r),yield*i.updateState(t,QD(a.run.state)),!0):yield*new XA({runId:t,operation:`approve`,state:a.run.state._tag})}))},hI(`approve run`)),te=j(`RunStore.retry`)(function*(t,n=hj){let{amendment:r,requestedBy:i}=n;return yield*A({runId:t}),yield*e.transaction(e=>O(function*(){let n=qI(e),a=yield*n.snapshot(t),o=aL(a);if(yield*M(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(T(r)&&(yield*n.amend(t,r.value),yield*M(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*M(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,C(T(r)?new Vk({operator:i}):new Bk({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*M(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new ZA({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&w(r)?!1:yield*new XA({runId:t,operation:`retry`,state:a.run.state._tag})}))},hI(`retry run`)),ne=j(`RunStore.runAgain`)(function*(t,n){yield*A({runId:t,agent:n.context.agent.name});let i=yield*xv;return yield*e.transaction(e=>O(function*(){let o=qI(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!KD(s.run.state).canRunAgain)return yield*M(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new XA({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*M(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new ZA({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=xi(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=E(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=E(yield*o.cycles.get(l),{onNone:()=>cA.make(0),onSome:e=>e.generation}),m=Lj(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,C({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new gj({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*M(`Run again decided`,$E(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:xi(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:xi(n.requestedBy,()=>`none`)})})),g}))},hI(`run again`)),re=j(`RunStore.cancel`)(function*(t){return yield*A({runId:t}),yield*e.transaction(e=>O(function*(){let n=qI(e),r=yield*n.snapshot(t),i=iL(r);if(yield*M(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;let a=yield*xv;if(T(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Ai(i.attempt,({id:e})=>e)}}))},hI(`cancel run`)),ie=j(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>O(function*(){let r=qI(e);yield*r.loopItems.unmatched(t,n);let i=yield*r.revokeUnstarted(t,n);for(let e of i){let t=yield*r.snapshot(e.runId);WD(t.run.state)&&(yield*r.updateState(e.runId,aO(t.run.state)))}return i.map(e=>e.runId)}))},hI(`revoke run`)),ae=j(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*A({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},hI(`revoke queued events`)),oe=j(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>O(function*(){let r=qI(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||T(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?S():(yield*i(r,t,n)).openedRun:(yield*M(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),S())}))},hI(`claim queued event`)),se=j(`RunStore.appendTranscript`)(function*(t,n){let r=yield*xv;yield*e.transaction(e=>O(function*(){let i=qI(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*N(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},hI(`append attempt transcript`)),ce=j(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},hI(`read attempt transcript`));return{approve:b,appendTranscript:se,beginAttempt:p,cancel:re,claimQueued:oe,finishAttempt:y,nextQueued:e=>n.nextQueued(e).pipe(hI(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(hI(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(hI(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(hI(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(hI(`read a salvage candidate`)),recordSalvage:m,recordComments:h,attemptWindows:g,discardLeftovers:_,openAttempts:v,submission:e=>n.eventRouteByRun(e).pipe(k(t=>t[0]===void 0?ug(new YA({runId:e})):D(vI(t[0]))),hI(`read run submission`)),resolveFailure:ee,retry:te,revoke:ie,revokeQueued:ae,runAgain:ne,snapshot:e=>n.snapshot(e).pipe(hI(`read run`)),transcript:ce}}),_L=class e extends ro()(`@usine/engine/internal/RunStore`){static layer=Op(e,gL)},vL=O(function*(){let e=yield*JA,t=qI(e),n=j(`RunReader.inspect`)(e=>t.snapshot(e).pipe(hI(`read run`))),r=j(`RunReader.evidence`)(function*(t){yield*A({runId:t});let n=yield*e.transaction(e=>O(function*(){let n=qI(e),r=yield*n.snapshot(t);return new jj({snapshot:r,transcript:(yield*ng(r.attempts,({id:e})=>n.transcript(new wj({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(hI(`read run evidence`));return yield*N(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=j(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(hI(`list runs`))),a=j(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(hI(`list closed runs`))),o=j(`RunReader.revision`)(()=>t.revision().pipe(hI(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,forItems:j(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(hI(`read item run histories`))),events:j(`RunReader.events`)(e=>t.runEvents(e).pipe(hI(`read the events of runs`))),revision:o,transcript:j(`RunReader.transcript`)(e=>t.transcript(e).pipe(hI(`read attempt transcript`))),attemptsByWorker:j(`RunReader.attemptsByWorker`)(()=>ZI(e).attemptCountsByWorker().pipe(hI(`count attempts by worker`))),sightings:j(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(hI(`read loop sightings`)))}}),yL=class e extends ro()(`@usine/engine/RunReader`){static layer=Op(e,vL)},bL=V.pipe(z(`ItemProjectionSource`)),xL=V.pipe(z(`ItemContentHash`)),SL=class extends H(`@usine/engine/ItemProjection`)({itemKey:aA,repository:mD,source:bL,number:oA,contentHash:xL,payload:nE,goneAt:rT(jT).pipe(Pw(D(null)),Mw(D(S())))}){},CL=F({itemKey:SL.fields.itemKey,repository:mD,source:bL,number:oA,contentHash:xL,payload:nE,goneAt:SL.fields.goneAt}),wL=qC(I(CL)),TL=qC(I(oA)),EL=iw(nE),DL=iw(CL.fields.goneAt),OL=e=>t=>Ag(t,t=>new QA({operation:e,cause:t})),kL=O(function*(){let e=yield*JA;return{list:j(`ItemProjectionReader.list`)(function*(t,n){return yield*A({repository:t,limit:n.limit}),(yield*wL(yield*e.select({itemKey:jF.itemKey,repository:jF.repository,source:jF.source,number:jF.itemNumber,contentHash:jF.contentHash,payload:jF.payloadJson,goneAt:jF.goneAt}).from(jF).where(Y(jF.repository,t)).orderBy(uN(jF.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new SL(e))},OL(`list item projections`)),openIssues:j(`ItemProjectionReader.openIssues`)(function*(t){return yield*A({repository:t}),yield*TL((yield*e.select({number:jF.itemNumber}).from(jF).where(FM(Y(jF.repository,t),Y(jF.source,`issue`),XM(jF.goneAt),J`json_extract(${jF.payloadJson}, '$.state') = 'OPEN'`)).orderBy(lN(jF.itemNumber)).execute()).map(({number:e})=>e))},OL(`list open issue projections`))}}),AL=O(function*(){let e=yield*JA;return{upsert:j(`ItemProjectionWriter.upsert`)(function*(t){yield*A({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=DL(t.goneAt);return(yield*e.insert(jF).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:EL(t.payload),goneAt:n}).onConflictDoUpdate({target:jF.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:EL(t.payload),goneAt:n},setWhere:J`${jF.contentHash} != ${t.contentHash} OR ${jF.goneAt} IS NOT ${n}`}).returning({itemKey:jF.itemKey}).execute()).length===0?(yield*N(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*N(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},OL(`write item projection`)),markGone:j(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*A({itemKey:t}),(yield*e.update(jF).set({goneAt:DL(C(n))}).where(FM(Y(jF.itemKey,t),XM(jF.goneAt))).returning({itemKey:jF.itemKey}).execute()).length===0?(yield*N(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*M(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:kv(n)}),!0)},OL(`mark item projection gone`))}}),jL=class e extends ro()(`@usine/engine/ItemProjectionReader`){static layer=Op(e,kL)},ML=class e extends ro()(`@usine/engine/ItemProjectionWriter`){static layer=Op(e,AL)},NL=P.check(Vw(/\S/u,{message:`Expected a non-blank repository label`})),PL=P.check(Vw(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),FL=class extends H(`@usine/engine/RepositoryLabel`)({name:NL,color:rT(PL),description:rT(P)}){},IL=Bw(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),LL=I(FL).check(IL),RL=class extends H(`@usine/engine/RepositoryLabelProjection`)({repository:mD,labels:LL}){},zL=I(P),BL=KC(zL),VL=F({repository:mD,labels:L([RL.fields.labels,zL])}),HL=e=>BL(e)?e.map(e=>new FL({name:e,color:S(),description:S()})):e,UL=qC(I(VL)),WL=iw(RL.fields.labels),GL=e=>t=>Ag(t,t=>new QA({operation:e,cause:t})),KL=O(function*(){let e=yield*JA;return{get:j(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*UL(yield*e.select({repository:MF.repository,labels:MF.labelsJson}).from(MF).where(Y(MF.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?S():C(new RL({repository:n.repository,labels:HL(n.labels)}))},GL(`read repository label projection`))}}),qL=O(function*(){let e=yield*JA;return{replace:j(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*A({repository:t.repository});let n=WL(t.labels);return(yield*e.insert(MF).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:MF.repository,set:{labelsJson:n},setWhere:kM(MF.labelsJson,n)}).returning({repository:MF.repository}).execute()).length===0?(yield*N(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*N(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},GL(`write repository label projection`))}}),JL=class e extends ro()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Op(e,KL)},YL=class e extends ro()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Op(e,qL)},XL=class extends ro()(`@usine/engine/TriggerCondition`){},ZL=V.pipe(z(`CursorKey`)),QL=qC(I(F({value:tE}))),$L=e=>t=>Ag(t,t=>new QA({operation:e,cause:t})),eR=class e extends ro()(`@usine/engine/CursorStore`){static layer=Op(e,O(function*(){let e=yield*JA;return{read:j(`CursorStore.read`)(function*(t,n){let r=wi((yield*O(function*(){return yield*QL(yield*e.select({value:AF.valueJson}).from(AF).where(Y(AF.cursorKey,t)).limit(1).execute())}).pipe($L(`read runtime cursor`)))[0]);return w(r)?S():yield*qC(n)(r.value.value,{onExcessProperty:`error`}).pipe(xg(C),Tg(e=>h_(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(Sg(S()))))}),write:j(`CursorStore.write`)(function*(t,n,r){let i=yield*nw(n)(r).pipe($L(`encode runtime cursor`));yield*e.insert(AF).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:AF.cursorKey,set:{valueJson:i}}).execute().pipe(wg,$L(`write runtime cursor`))})}}))},tR=class extends H(`@usine/engine/LoopRuntimeState`)({loop:CD,paused:_w}){},nR=e=>t=>t.pipe(Ag(t=>new QA({operation:e,cause:t}))),rR=O(function*(){let e=yield*JA,t=j(`LoopControl.stateFor`)(function*(t){yield*A({loop:t});let n=(yield*e.select({loop:PF.loopName,paused:PF.paused}).from(PF).where(Y(PF.loopName,t)).limit(1).execute())[0];return n===void 0?new tR({loop:t,paused:!1}):new tR(n)},nR(`read loop runtime state`)),n=j(`LoopControl.states`)(function*(){return(yield*e.select({loop:PF.loopName,paused:PF.paused}).from(PF).orderBy(lN(PF.loopName)).execute()).map(e=>new tR(e))},nR(`list loop runtime states`)),r=j(`LoopControl.write`)(function*(n){yield*A({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*N(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(PF).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:PF.loopName,set:{paused:n.paused}}).execute().pipe(nR(`write loop runtime state`)),yield*M(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:j(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:j(`LoopControl.pause`)(e=>r(new tR({loop:e,paused:!0}))),states:n(),unpause:j(`LoopControl.unpause`)(e=>r(new tR({loop:e,paused:!1})))}}),iR=class e extends ro()(`@usine/engine/LoopControl`){static layer=Op(e,rR)},aR=e=>e.pipe(Ag(e=>e instanceof DI?e:new QA({operation:`update cycle budget`,cause:e}))),oR=class e extends ro()(`@usine/engine/CycleBudgets`){static layer=Op(e,O(function*(){let e=yield*JA,t=jI(e);return{generation:j(`CycleBudgets.generation`)(function*(e){return yield*A({itemKey:e}),E(yield*t.get(e).pipe(Ag(e=>new QA({operation:`read cycle generation`,cause:e}))),{onNone:()=>cA.make(0),onSome:e=>e.generation})}),asks:j(`CycleBudgets.asks`)(()=>t.asks().pipe(Ag(e=>new QA({operation:`read cycle asks`,cause:e})))),reset:j(`CycleBudgets.reset`)(function*(t,n){yield*A({askId:t,eventId:n.id}),yield*e.transaction(e=>O(function*(){if((yield*e.select().from(wF).where(Y(wF.askId,t)).execute())[0]?.eventId===n.id){yield*M(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*jI(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new DI({askId:t});let i=yield*jI(e).get(r.itemKey);if(w(i))return yield*pg(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(bF).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:nI(n.payload),receivedAt:rI(n.receivedAt)}).execute(),yield*e.insert(wF).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(SF).set({generation:a,askJson:null,resetPending:!0}).where(Y(SF.itemKey,r.itemKey)).execute(),yield*e.update(CF).set({generation:a}).where(FM(Y(CF.itemKey,r.itemKey),qM(CF.runId,e.select({runId:Q.runId}).from(Q).where(qM(J`json_extract(${Q.stateJson}, '$._tag')`,[...XD]))))).execute(),yield*M(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(aR)}),pendingResets:j(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(xg(e=>e.map(e=>new EI(e))),Ag(e=>new QA({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:j(`CycleBudgets.acknowledgeReset`)(function*(t){yield*A({itemKey:t.itemKey,generation:t.generation}),yield*e.update(SF).set({resetPending:!1}).where(FM(Y(SF.itemKey,t.itemKey),Y(SF.generation,t.generation))).execute().pipe(Ag(e=>new QA({operation:`acknowledge cycle reset`,cause:e}))),yield*M(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},sR=I(V),cR=class extends H(`@usine/engine/BoardMoveRecord`)({repository:mD,itemKey:aA,at:AT,fromLane:V,toLane:V,added:sR.check($w()),removed:sR}){},lR=qC(I(F({repository:cR.fields.repository,itemKey:cR.fields.itemKey,at:jT,fromLane:cR.fields.fromLane,toLane:cR.fields.toLane,added:cR.fields.added,removed:cR.fields.removed}))),uR=iw(cR.fields.added),dR=iw(cR.fields.removed),fR=e=>t=>Ag(t,t=>new QA({operation:e,cause:t})),pR=O(function*(){let e=yield*JA;return{record:j(`BoardMoves.record`)(function*(t){yield*A({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(NF).values({repository:t.repository,itemKey:t.itemKey,movedAt:rI(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:uR(t.added),removedJson:dR(t.removed)}).execute(),yield*N(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:rI(t.at),fromLane:t.fromLane,toLane:t.toLane})},fR(`record board move`)),onItem:j(`BoardMoves.onItem`)(function*(t,n){return yield*A({itemKey:t}),(yield*lR(yield*e.select({repository:NF.repository,itemKey:NF.itemKey,at:NF.movedAt,fromLane:NF.fromLane,toLane:NF.toLane,added:NF.addedJson,removed:NF.removedJson}).from(NF).where(FM(Y(NF.itemKey,t),VM(NF.movedAt,rI(n)))).orderBy(lN(NF.movedAt),lN(NF.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new cR(e))},fR(`read board moves`))}}),mR=class e extends ro()(`@usine/engine/BoardMoves`){static layer=Op(e,pR)},hR=class extends ro()(`@usine/engine/RunEngineShutdown`){},gR=class e extends ro()(`@usine/engine/AttemptAdmission`){static layer=Op(e,O(function*(){let e=yield*Gg(hR),t=T(e)?e.value:yield*Zf(),n=yield*nD(new Set),r=yield*Zf(),i=j(`AttemptAdmission.enter`)(function*(e){yield*A({runId:e});let r=yield*aD(n,n=>tp(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*M(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=j(`AttemptAdmission.leave`)(function*(e){yield*A({runId:e});let i=yield*sD(n,t=>new Set([...t].filter(t=>t!==e)));(yield*ep(t))&&(yield*M(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*np(r,void 0)))});return{withAttempt:j(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*A({runId:e}),yield*Yg(i(e),e=>e?t:lg,t=>t?a(e):cg)}),drain:j(`AttemptAdmission.drain`)(function*(){yield*np(t,void 0);let e=yield*rD(n);yield*M(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*np(r,void 0)),yield*Qf(r),yield*M(`Engine drain completed; all admitted Attempts settled`)})}}))},_R=class extends BT(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:Kk,cause:vT()}){},vR=(e,t)=>{let n=new Map(e);return n.delete(t),n},yR=j(`CheckoutRecovery.for`)(function*(e,t){let n=yield*nD(new Map),r=n=>t.recover(n,{salvage:t=>e.recordSalvage(n.attemptId,t),comments:t=>e.recordComments(n.attemptId,t),windows:e.attemptWindows(n.attemptId)}).pipe(Mg(e=>g_(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),Pg),i=j(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker).pipe(k(e=>$g(e.release).pipe(xg(t=>({worker:e.worker,release:t})))),k(t=>oD(n,n=>new Map(n).set(e.attemptId,t))),n_)}),a=j(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*A(n);let a=yield*t.isLive(e.attemptId).pipe(yg);if(Gi(a)&&!a.success)return yield*r(e);Wi(a)?yield*h_(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*M(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*M(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=j(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*A(n);let a=yield*t.interrupt(e.attemptId).pipe(yg);return Gi(a)?(yield*r(e),S()):(yield*h_(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),C(e.attemptId))}),s=j(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*h_(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),Pa(yield*ng(i,e=>e.open?a(e).pipe(Sg(S())):o(e)))}),c=j(`CheckoutRecovery.reattachSlot`)(function*(e){return Ai(Ti((yield*rD(n)).get(e)),t=>({worker:t.worker,release:rD(n).pipe(k(n=>n.has(e)?M(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=j(`CheckoutRecovery.acquired`)(function*(e){(yield*aD(n,t=>[t.has(e),vR(t,e)]))&&(yield*M(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=j(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*t.interrupt(n).pipe(yg);if(Wi(i))return yield*h_(`Could not confirm that the parent task of an Attempt its Run does not reattach stopped; its checkout and its Worker's slot stay, and the Run starts no next Attempt until the stop is confirmed`,{attemptId:n,errorTag:i.failure._tag,message:i.failure.message}),yield*new _R({attemptId:n,cause:i.failure});let a=yield*e.salvageCandidate(n).pipe(yg);if(Wi(a)){yield*g_(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:a.failure._tag});return}if(w(a.success)){yield*h_(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let o=a.success.value,s={attemptId:n,worker:o.worker,open:o.open};yield*A(s),(yield*t.workers).includes(o.worker)?(yield*M(`Reconciling the checkout startup kept for an Attempt that was not reattached`,s),yield*r(o)):yield*h_(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,s)});return{atStartup:s,reattachSlot:c,acquired:l,reconcile:j(`CheckoutRecovery.reconcile`)(function*(e){yield*A({attemptId:e});let t=(yield*rD(n)).get(e);t===void 0?yield*N(`No checkout startup kept for the Attempt awaits reconciliation`,{attemptId:e}):(yield*u(e),yield*oD(n,t=>vR(t,e)).pipe(_g(t.release),n_),yield*M(`Released the slot startup occupied for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:t.worker}))})}}),bR=e=>Dg(e,{EnginePersistenceError:e=>new Sk({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>pg(e),RunOperationRejectedError:e=>pg(e),RunRetryBlockedError:e=>pg(e)}),xR=4,SR=`100 millis`,CR=(e,t)=>n=>n.pipe(Mg(n=>n._tag===`EnginePersistenceError`?h_(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):cg),Ng({schedule:Uh(SR),times:xR,while:e=>e._tag===`EnginePersistenceError`})),wR=e=>ji(e,e=>e._tag===`Live`?C(e.attempt):S()),TR=class e extends ro()(`@usine/engine/internal/RunDriver`){static layer=Op(e,O(function*(){let e=yield*_L,t=yield*zj,n=yield*gR,r=yield*XL,i=yield*ML,a=yield*DE,o=yield*ME(),s=yield*yR(e,t),c=yield*nD(new Set),l=j(`RunDriver.launch`)(function*(e){yield*A({runId:e}),(yield*zE(o,e))?yield*N(`The Run's fiber already runs in this process`,{runId:e}):(yield*N(`Starting the Run's fiber`,{runId:e}),yield*HE(o,e,_(e).pipe(Og(t=>Nf(t)?dg(t):g_(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t}))),{onlyIfMissing:!0}))}),u=j(`RunDriver.resume`)(function*(e){yield*A({runId:e});let t=yield*LE(o,e);T(t)&&(yield*N(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*Zx(t.value)),yield*l(e)}),d=j(`RunDriver.stop`)(function*(e){yield*A({runId:e}),(yield*zE(o,e))?(yield*BE(o,e),yield*M(`The closed Run's fiber stopped`,{runId:e})):yield*N(`The closed Run has no fiber in this process`,{runId:e})}),f=j(`RunDriver.markItemGone`)(function*(e,t){return yield*A({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*xv).pipe(CR(e,`mark the item's projection gone`),Tg(n=>h_(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(Sg(!1))))}),p=j(`RunDriver.continueWithNewest`)(function*(t){yield*A({runId:t});let n=yield*e.nextQueued(t).pipe(CR(t,`read the queued events`));if(w(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(CR(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*M(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*f(t,i);yield*M(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*aj(i).pipe(qg(DE,a)),u=yield*e.claimQueued(i,c).pipe(CR(t,`claim the queued event`));w(u)?yield*M(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*M(`Queued Event still matches its trigger; opening its Run`,{...o,runId:u.value}),yield*l(u.value))}),m=j(`RunDriver.openAttempt`)(function*(n){yield*A({runId:n});let r=yield*e.snapshot(n).pipe(CR(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||T(i.outcome))return S();let a={runId:n,attemptId:i.id,worker:i.worker};yield*A({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe(yg);if(Wi(o))return yield*h_(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),C({_tag:`Interrupted`,attempt:i});if(o.success)return yield*M(`The open Attempt's parent task is live; reattaching it`,a),C({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe(yg);if(Wi(s))return yield*h_(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),C({_tag:`Interrupted`,attempt:i});if(w(s.success))return yield*M(`The open Attempt's parent task is gone; the Run does not reattach it`,a),C({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*M(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:qi(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),C({_tag:`Finished`,attempt:i,result:c})}),h=j(`RunDriver.slot`)(function*(e,n,r,i){yield*A({runId:e});let a=D(r),o=wR(r);if(T(o)){let t=yield*s.reattachSlot(o.value.id);if(T(t))return yield*M(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(n,Ai(o,({worker:e})=>e))),open:T(o)?m(e):a}}),g=j(`RunDriver.attempt`)(function*(n,r,i){yield*A({runId:n,worker:r});let a=yield*i;if(T(a)&&a.value._tag===`Finished`){let t=yield*e.finishAttempt(a.value.attempt,a.value.result).pipe(CR(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let o=yield*e.beginAttempt(n,r,Ai(wR(a),({id:e})=>e)).pipe(CR(n,`begin the attempt`));if(o._tag===`AttemptRecoveryFailed`)return`RunFailed`;if(o._tag===`RunClosed`)return`Unchanged`;let c=yield*t.execute(o.execution,{append:(t,n)=>e.appendTranscript(t,n).pipe(bR),salvage:t=>e.recordSalvage(o.execution.attempt.id,t).pipe(bR),comments:t=>e.recordComments(o.execution.attempt.id,t).pipe(bR),windows:e.attemptWindows(o.execution.attempt.id).pipe(CR(n,`read the attempt windows`),bR),transcript:e.transcript(new wj({attemptId:o.execution.attempt.id})).pipe(CR(n,`read the attempt transcript`),bR,xg(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(o.execution.attempt.id)}).pipe(kg(e=>g_(`Step executor defect; operator intervention required`,{runId:n,attemptId:o.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(_g(new Ck({message:`The step executor crashed with an unexpected error`,cause:e})))),yg);return o.execution.reattach&&Wi(c)&&(yield*s.reconcile(o.execution.attempt.id)),(yield*e.finishAttempt(o.execution.attempt,c).pipe(CR(n,`finish the attempt`)))._tag}),_=j(`RunDriver.drive`)(function*(t){let r=yield*e.submission(t).pipe(CR(t,`read the run's submission`));if(yield*A({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(CR(t,`park the run for approval`)))._tag===`Waiting`){yield*M(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*m(t);T(e)&&e.value._tag!==`Live`&&(yield*s.reconcile(e.value.attempt.id)),i=yield*r_(i=>h(t,r,e,i).pipe(k(({lease:e,open:r})=>i(n.withAttempt(t,g(t,e.worker,r))).pipe(Xg(e.release)))))}while(i===`RetryAttempt`);i===`Unchanged`?yield*M(`Run closed by another operation; its fiber ends`,{runId:t}):yield*p(t)}),v=j(`RunDriver.releaseKept`)(function*(e){yield*A({attemptId:e});let t=yield*s.reconcile(e).pipe(yg);yield*oD(c,n=>{let r=new Set(n);return Gi(t)?r.delete(e):r.add(e),r}),Wi(t)&&(yield*h_(`The parent task of an Attempt whose Run closed is not confirmed stopped; its checkout and its Worker's slot stay kept, and the next reconcile tries the stop again`,{attemptId:e}))}),y=j(`RunDriver.recoverWorkspaces`)(function*(){let e=yield*s.atStartup();yield*oD(c,t=>new Set([...t,...e]))});return{launch:l,resume:u,stop:d,continueWithNewest:p,reconcile:j(`RunDriver.reconcile`)(function*(){let t=[...yield*rD(c)];yield*ng(t,v,{discard:!0});let n=yield*e.pendingContinuations;yield*ng(n,e=>p(e).pipe(Mg(t=>g_(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),Pg),{discard:!0});let r=yield*e.runIdsToDrive,i=yield*Rg(r,e=>xg(zE(o,e),e=>!e));yield*ng(i,l,{discard:!0});let a={continuedAfterRunIds:n,startedRunIds:i,drivenRunIds:r.length,retriedStopAttemptIds:t};n.length===0&&i.length===0&&t.length===0?yield*N(`Every Run to drive already has its fiber`,a):yield*M(`Runs recovered from the run tables`,a)}),recoverWorkspaces:y,releaseKept:v}}))},ER=Ro(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});O(function*(){let e=yield*_L,t=yield*TR,n=yield*gR,r=yield*zj,i=yield*DE,a=j(`RunEngine.submit`)(function*(n){let r=yield*aj(n).pipe(qg(DE,i)),a=yield*e.recordAndClaim(n,r);return T(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),T(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},n_),o=j(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*M(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:xi(i.approver,()=>`none`)}),yield*t.resume(n)):yield*N(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},n_),s=j(`RunEngine.retry`)(function*(n,r=hj){(yield*e.retry(n,r))?yield*t.resume(n):yield*N(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},n_),c=j(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},n_),l=j(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*N(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*M(`Run canceled`,{runId:n,openAttempt:xi(i.openAttempt,()=>`none`)});let a=T(i.openAttempt)?yield*r.interrupt(i.openAttempt.value).pipe(yg):zi(void 0);if(yield*t.stop(n),T(i.openAttempt)&&(yield*t.releaseKept(i.openAttempt.value)),yield*t.continueWithNewest(n),T(i.openAttempt)&&Wi(a))return yield*new $A({attemptId:i.openAttempt.value,cause:a.failure})},n_),u=j(`RunEngine.intervene`)(function*(t,n,i){yield*A({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||T(o.outcome))return yield*M(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new tj({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(Ag(e=>new tj({runId:t,attemptId:n,message:$E(e,{RunawayFailure:()=>`The attempt reached its runaway limit`,ChildSessionBudgetFailure:()=>`The attempt reached its child-session budget`,QuestionFailure:()=>`The attempt ended with a question for the operator`,BlockedFailure:({message:e})=>e,InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),Mg(e=>h_(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=j(`RunEngine.resolveFailure`)(function*(n,r){(yield*e.resolveFailure(n,r))&&(yield*M(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},n_),f=j(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*ng(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},n_),p=j(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=j(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=j(`RunEngine.discardLeftovers`)(function*(t){if(yield*A({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*M(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new nj({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*M(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n}),n});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*Fg(yield*ER).pipe(_g(t.reconcile()),Mg(e=>g_(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),Pg,i_,c_),{approve:o,cancel:l,discardLeftovers:h,drain:n.drain,inspect:p,intervene:u,reconcile:t.reconcile,retry:s,resolveFailure:d,revoke:f,runAgain:c,submit:a,transcript:m}});var DR=class extends ro()(`@usine/engine/RunEngine`){},OR=Ow([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),kR=Ow([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`]),AR=class extends BT(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:OR,message:V,cause:vT()}){},jR=Ow([`refused`,`unreachable`]);L([AR,class extends BT(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:mD,reason:jR,message:V,cause:vT()}){},class extends BT(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:BO,capability:kR,message:V,cause:vT()}){}]),H(`@usine/executor/CheckoutRequest`)({attemptId:Kk,worker:BO,repository:mD,loop:CD,permissions:DD,revision:hD,payload:tE,task:Jk,agent:kO,parentModel:nT(CO),maxChildren:ek,maxAttemptMinutes:nT(B.check(Jw(0))),maxAttemptTokens:nT(B.check(Jw(0))),parentEffort:TO,salvageRef:Pk,resume:nT(Ik),reattach:_w.pipe(Mw(D(!1))),botLogin:nT(HO).pipe(Mw(D(S())))});var MR=V.pipe(z(`WorktreePath`));H(`@usine/executor/AttemptWorkspace`)({worker:BO,spec:_A,worktree:MR}),H(`@usine/executor/WorkerCredential`)({value:aT(P),expiresAt:AT}),ro()(`@usine/executor/CredentialProvider`),ro()(`@usine/executor/Executor`);var NR=`~effect/http/UrlParams`,PR=e=>At(e,NR),FR={...nr,[NR]:NR,[Symbol.iterator](){return this.params[Symbol.iterator]()},toJSON(){return{_id:`UrlParams`,params:Object.fromEntries(this.params)}},[Qt](e){return zR(this,e)},[Pt](){return Gt(this.params.flat())}},IR=e=>{let t=Object.create(FR);return t.params=e,t},LR=e=>{if(PR(e))return e;let t=RR(e),n=[];for(let e=0;e<t.length;e++)if(Array.isArray(t[e][0])){let[r,i]=t[e];n.push([`${r[0]}[${r.slice(1).join(`][`)}]`,i])}else n.push(t[e]);return IR(n)},RR=e=>{let t=typeof e[Symbol.iterator]==`function`?sa(e):Object.entries(e),n=[];for(let[e,r]of t)if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]!==void 0&&n.push([e,String(r[t])]);else if(typeof r==`object`){let t=RR(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,String(r)]);return n},zR=_n((e,t)=>BR(e.params,t.params)),BR=Fa(Zi([yn(),yn()])),VR=BC(PR,{representation:{id:`effect/http/UrlParams`,payload:null},toCode:()=>({runtime:`UrlParams.UrlParamsSchema`,Type:`UrlParams.UrlParams`,importDeclarations:[`import * as UrlParams from "effect/unstable/http/UrlParams"`]}),expected:`UrlParams`,toEquivalence:()=>zR,toCodec:()=>zw()(I(Tw([P,P])),ty({decode:IR,encode:e=>e.params}))}),HR=IR([]),UR=x(2,(e,t)=>IR(t(e.params))),WR=x(2,(e,t)=>{let n=LR(t),r=n.params,i=new Set;for(let e=0;e<r.length;e++)i.add(r[e][0]);for(let t=0;t<e.params.length;t++)i.has(e.params[t][0])||r.push(e.params[t]);return n}),GR=x(2,(e,t)=>UR(e,da(LR(t).params))),KR=e=>new URLSearchParams(LR(e).params).toString(),qR=VR.pipe(Aw(Cw(P,L([P,Ew(P)])),ty({decode:e=>{let t={};for(let[n,r]of e.params)if(!Object.hasOwn(t,n))Cn(t,n,r);else{let e=t[n];typeof e==`string`?Cn(t,n,[e,r]):e.push(r)}return t},encode:LR}))),JR=`~effect/http/HttpBody`,YR=e=>At(e,JR),XR=class{[JR];constructor(){this[JR]=JR}[zn](){return this.toJSON()}toString(){return Mn(this,{ignoreToString:!0})}},ZR=new class extends XR{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},QR=class extends XR{_tag=`Uint8Array`;body;contentType;contentLength;constructor(e,t,n){super(),this.body=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}},$R=(e,t)=>new QR(e,t??`application/octet-stream`,e.length),ez=new TextEncoder,tz=(e,t)=>$R(ez.encode(e),t??`text/plain`),nz=(e,t)=>tz(JSON.stringify(e),t??`application/json`),rz=(e,t)=>tz(KR(LR(e)),t??`application/x-www-form-urlencoded`),iz=class extends XR{_tag=`FormData`;contentType=void 0;contentLength=void 0;formData;constructor(e){super(),this.formData=e}toJSON(){return{_id:`effect/HttpBody`,_tag:`FormData`,formData:this.formData}}},az=e=>new iz(e),oz=Symbol.for(`~effect/http/Headers`),sz=Object.defineProperties(Object.create(null),{[oz]:{value:oz},[Tn]:{value(e){return _z(this,Ao(e,yz))}},toJSON:{value(){return Dn(this)}},[Qt]:{value(e){return lz(this,e)}},[Pt]:{value(){return Ut(this)}},toString:{value:Hn.toString},[zn]:{value:Hn[zn]}}),cz=e=>Object.assign(Object.create(sz),e),lz=aa(yn()),uz=Object.create(sz),dz=e=>{if(e===void 0)return uz;if(Symbol.iterator in e){let t=Object.create(sz);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(sz);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},fz=e=>Object.setPrototypeOf(e,sz),pz=x(3,(e,t,n)=>{let r=cz(e);return r[t.toLowerCase()]=n,r}),mz=x(2,(e,t)=>cz({...e,...dz(t)})),hz=x(2,(e,t)=>{let n=cz(e);return Object.assign(n,t),n}),gz=x(2,(e,t)=>{let n=cz(e);return delete n[t.toLowerCase()],n}),_z=x(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=PC(e[r]))}else for(let r in e)t.test(r)&&(n[r]=PC(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),vz=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(typeof r==`string`){if(r.toLowerCase()===e)return!0}else if(r.test(e))return!0}return!1},yz=Ro(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),bz=`~effect/http/Cookies`,xz=`~effect/http/Cookies/Cookie`,Sz={[bz]:bz,...Hn,toJSON(){return{_id:`effect/Cookies`,cookies:na(this.cookies,e=>e.toJSON())}},pipe(){return nt(this,arguments)}},Cz=e=>{let t=Object.create(Sz);return t.cookies=e,t},wz=e=>{let t={};for(let n of e)Cn(t,n.name,n);return Cz(t)},Tz=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=Ez(e.trim());t&&n.push(t)}return wz(n)};function Ez(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!Dz.test(r))return;let i=t[0].slice(n+1),a=kz(i);if(t.length===1)return Object.assign(Object.create(Oz),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=cs(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(Oz),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var Dz=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Oz={[xz]:xz,...Hn,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},kz=e=>{try{return decodeURIComponent(e)}catch{return e}},Az=`~effect/http/HttpClientError`,jz=class extends Ms(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[Az]=Az;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},Mz=e=>e.endsWith(`Error`)?e.slice(0,-5):e,Nz=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,Pz=class extends Ms(`TransportError`){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return Nz(Mz(this._tag),this.description,this.methodAndUrl)}},Fz=class extends Ms(`InvalidUrlError`){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return Nz(Mz(this._tag),this.description,this.methodAndUrl)}},Iz=class extends Ms(`StatusCodeError`){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Nz(Mz(this._tag),this.description,e)}},Lz=class extends Ms(`DecodeError`){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Nz(Mz(this._tag),this.description,e)}},Rz=class extends Ms(`EmptyBodyError`){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Nz(Mz(this._tag),this.description,e)}},zz=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,Bz=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Vz=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?gz(gz(e,`content-type`),`content-length`):(e=t.contentType===void 0?gz(e,`content-type`):pz(e,`content-type`,t.contentType),t.contentLength===void 0?gz(e,`content-length`):pz(e,`content-length`,t.contentLength.toString())),Hz=class extends Ms(`UrlError`){},Uz=(e,t,n)=>Hi({try:()=>{let r=new URL(e,Wz());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,i)}return n!==void 0&&(r.hash=n),r},catch:e=>new Hz({cause:e})}),Wz=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},Gz=`~effect/http/HttpClientRequest`,Kz={[Gz]:Gz,...Hn,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Dn(this.headers),body:this.body.toJSON()}},pipe(){return nt(this,arguments)}};function qz(e,t,n,r,i,a){let o=Object.create(Kz);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Jz=qz(`GET`,``,HR,S(),uz,ZR),Yz=e=>(t,n)=>Qz(Jz,{method:e,url:t,...n??void 0}),Xz=Yz(`GET`),Zz=Yz(`POST`),Qz=x(2,(e,t)=>{let n=e;return t.method&&(n=$z(n,t.method)),t.url&&(n=iB(n,t.url)),t.headers&&(n=tB(n,t.headers)),t.urlParams&&(n=sB(n,t.urlParams)),t.hash&&(n=lB(n,t.hash)),t.body&&(n=uB(n,t.body)),t.accept&&(n=nB(n,t.accept)),t.acceptJson&&(n=rB(n)),n}),$z=x(2,(e,t)=>qz(t,e.url,e.urlParams,e.hash,e.headers,e.body)),eB=x(3,(e,t,n)=>qz(e.method,e.url,e.urlParams,e.hash,pz(e.headers,t,n),e.body)),tB=x(2,(e,t)=>qz(e.method,e.url,e.urlParams,e.hash,mz(e.headers,t),e.body)),nB=x(2,(e,t)=>eB(e,`Accept`,t)),rB=nB(`application/json`),iB=x(2,(e,t)=>{if(typeof t==`string`)return qz(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=LR(n.searchParams),i=wi(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,qz(e.method,n.toString(),r,i,e.headers,e.body)}),aB=x(2,(e,t)=>t===``?e:qz(e.method,oB(t,e.url),e.urlParams,e.hash,e.headers,e.body)),oB=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},sB=x(2,(e,t)=>qz(e.method,e.url,WR(e.urlParams,t),e.hash,e.headers,e.body)),cB=x(2,(e,t)=>qz(e.method,e.url,GR(e.urlParams,t),e.hash,e.headers,e.body)),lB=x(2,(e,t)=>qz(e.method,e.url,e.urlParams,C(t),e.headers,e.body)),uB=x(2,(e,t)=>qz(e.method,e.url,e.urlParams,e.hash,Vz(e.headers,t),t)),dB=x(2,(e,t)=>uB(e,nz(t))),fB=x(2,(e,t)=>uB(e,az(t))),pB=`~effect/http/HttpIncomingMessage`,mB=(e,t)=>{let n=YC(VT(e)),r=t?.reviver===void 0?void 0:YC(TT(VT(e),t));return e=>r===void 0?k(e.json,e=>n(e,t)):k(e.text,i=>i===``?k(e.json,e=>n(e,t)):r(i,t))},hB=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=f_(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=f_(e.text)}catch{}let i={...t,headers:Dn(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},gB=`~effect/http/HttpClientResponse`,_B=(e,t)=>new yB(e,t),vB=x(2,(e,t)=>{let n=e.status;return t[n]?t[n](e):n>=200&&n<300&&t[`2xx`]?t[`2xx`](e):n>=300&&n<400&&t[`3xx`]?t[`3xx`](e):n>=400&&n<500&&t[`4xx`]?t[`4xx`](e):n>=500&&n<600&&t[`5xx`]?t[`5xx`](e):t.orElse(e)}),yB=class extends Un{[pB];[gB];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[pB]=pB,this[gB]=gB}toJSON(){return hB(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get headers(){return dz(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Tz(this.source.headers.getSetCookie())}get remoteAddress(){return S()}get stream(){return this.source.body?hE({evaluate:()=>this.source.body,onError:e=>new jz({reason:new Lz({request:this.request,response:this,cause:e})})}):mE(new jz({reason:new Rz({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return k(this.text,e=>mg({try:()=>e===``?null:JSON.parse(e),catch:e=>new jz({reason:new Lz({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=xg(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return k(this.text,e=>mg({try:()=>LR(new URLSearchParams(e)),catch:e=>new jz({reason:new Lz({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=ig({try:()=>this.source.formData(),catch:e=>new jz({reason:new Lz({request:this.request,response:this,cause:e})})}).pipe($g,f_)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=ig({try:()=>this.source.arrayBuffer(),catch:e=>new jz({reason:new Lz({request:this.request,response:this,cause:e})})}).pipe($g,f_),this.arrayBufferBody}pipe(){return nt(this,arguments)}};({...nr});var bB=new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")bB[e.charCodeAt(0)]=1;var xB=new Uint8Array(256);xB[9]=1;for(let e=32;e<=126;e++)xB[e]=1;for(let e=128;e<=255;e++)xB[e]=1;var SB=ro(`effect/http/HttpServerRequest`),CB=e=>fz({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${E(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),wB=new WeakSet,TB=e=>hg(t=>{let n=ko(t.context,SB);return wB.add(n.source),e}),EB=`~effect/http/HttpClient`,DB=ro(`effect/HttpClient`),OB=x(2,(e,t)=>kB(n=>t(e.postprocess(n)),e.preprocess)),kB=(e,t)=>{let n=Object.create(AB);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},AB={[EB]:EB,pipe(){return nt(this,arguments)},...Hn,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Bz.map(([e,t])=>[t,function(t,n){return this.execute(Yz(e)(t,n))}]))},jB=e=>kB(t=>k(t,t=>hg(n=>{let r=zB.get(t),i=r??new AbortController,a=Uz(t.url,t.urlParams,Oi(t.hash));if(Wi(a))return ug(new jz({reason:new Fz({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Xs)||n.getRef(NB)(t)){let a=e(t,o,i.signal,n);return r?a:r_(e=>Bg(e(a),{onSuccess(e){return RB.register(e,i),D(new BB(e,i))},onFailure(e){return Lf(e)&&i.abort(),dg(e)}}))}return a_(n.getRef(IB)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method),a.attribute(`server.address`,o.origin),o.port!==``&&a.attribute(`server.port`,+o.port),a.attribute(`url.full`,o.toString()),a.attribute(`url.path`,o.pathname),a.attribute(`url.scheme`,o.protocol.slice(0,-1));let s=o.search.slice(1);s!==``&&a.attribute(`url.query`,s);let c=n.getRef(yz),l=n.getRef(PB);for(let e in t.headers)l(e,`request`)&&a.attribute(`http.request.header.${e}`,vz(e,c)?`<redacted>`:t.headers[e]);return t=n.getRef(FB)?tB(t,CB(a)):t,r_(s=>s(e(t,o,i.signal,n)).pipe(s_(a,{captureStackTrace:!1}),Bg({onSuccess:e=>{a.attribute(`http.response.status_code`,e.status);for(let t in e.headers)l(t,`response`)&&a.attribute(`http.response.header.${t}`,vz(t,c)?`<redacted>`:e.headers[t]);return r?D(e):(RB.register(e,i),D(new BB(e,i)))},onFailure(e){return!r&&Lf(e)&&i.abort(),dg(e)}})))})})),D),MB=x(2,(e,t)=>kB(e.postprocess,n=>xg(e.preprocess(n),t))),NB=Ro(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>ct}),PB=Ro(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>st}),FB=Ro(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:st}),IB=Ro(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),LB=e=>Op(DB)(Hg(t=>xg(e,e=>OB(e,Kg(e=>Fo(t,e)))))),RB=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new Map;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),zB=new WeakMap,BB=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[gB]=gB;[pB]=pB;applyInterrupt(e){return og(()=>(RB.unregister(this.original),t_(e,()=>sg(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return pE(()=>(RB.unregister(this.original),bE(this.original.stream,sg(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[zn](){return this.original[zn]()}pipe(){return nt(this,arguments)}},VB=ro(`effect/http/HttpRouter`),HB=e=>e.endsWith(`/`)?e.slice(0,-1):e,UB=x(2,(e,t)=>(t=HB(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),WB=`~effect/http/HttpRouter/Middleware`,GB=function(){return arguments.length===0?KB:KB(arguments[0],arguments[1])},KB=(e,t)=>t?.global?jp(O(function*(){let t=yield*VB,n=eg(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new YB(eg(e)?Ap(xg(e,e=>_o(new Map([[JB,e]])))):Dp(_o(new Map([[JB,e]])))),qB=0,JB=`effect/http/HttpRouter/MiddlewareFn`,YB=class e{[WB]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++qB}`;this.layer=Ap(O({self:this},function*(){let e=yield*Vg(),t=[Oo(e,JB)];if(this.dependencies){let n=yield*Cp,r=Ao(e,ap),i=yield*wp(this.dependencies,n,r);t.push(...ZB(i))}return _o(new Map([[n,t]]))})).pipe(Fp(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?Ip(this.dependencies,t.layer):t.layer)}},XB=new WeakMap,ZB=e=>{let t=XB.get(e);if(t)return t;let n=ja(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=sa(e).reverse()}return XB.set(e,t),t};GB(TB).layer;var QB={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},$B=e=>QB[e],eV=`~effect/httpapi/HttpApiSchema/Stream`;function tV(e){let t=typeof e==`string`?$B(e):e;return e=>e.annotate({httpApiStatus:t})}var nV=(e=>yw.pipe(tV(e)))(204),rV=e=>ow(e)&&At(e,eV),iV=e=>rV(e)&&e._tag===`StreamSse`,aV=e=>rV(e)&&e._tag===`StreamUint8Array`,oV=`~effect/httpapi/HttpApiSchema/WithHeaders`,sV=`~effect/httpapi/HttpApiSchema/WithHeadersValue`,cV=e=>({[sV]:sV,body:e.body,headers:e.headers}),lV=e=>ow(e)&&At(e,`~effect/httpapi/HttpApiSchema/WithHeaders`);function uV(e,t,n){return aw(e.ast,{[oV]:oV,schema:t,headers:n})}function dV(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??fV(t._tag)}})}function fV(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function pV(e){return t=>dV(t,{_tag:`FormUrlEncoded`,...e})}var mV=e=>{if(Cy(e)||Cy(ux(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&Cy(t)},hV=kx(`~httpApiEncoding`),gV=kx(`~httpApiWithHeaders`),_V=kx(`httpApiStatus`),vV={_tag:`Json`,contentType:`application/json`},yV={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function bV(e){return hV(e)??vV}function xV(e,t){return hV(e)||(zz(t)?vV:yV)}function SV(e){let t=bV(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function CV(e){return _V(e)??200}function wV(e){return lV(e)?_V(e.ast)??CV(e.schema.ast):CV(e.ast)}function TV(e){return lV(e)&&hV(e.ast)===void 0?SV(e.schema.ast):SV(e.ast)}function EV(e){return _V(e)??500}function DV(e){return lV(e)?_V(e.ast)??EV(e.schema.ast):EV(e.ast)}function OV(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var kV=`~effect/httpapi/HttpApiEndpoint`;function AV(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function jV(e){let t=Array.from(e.success);return fa(t)?t:[nV]}function MV(e){let t=new Set(e.error);for(let n of e.middlewares){let e=n;for(let n of e.error)t.add(n)}return Array.from(t)}var NV={[kV]:kV,pipe(){return nt(this,arguments)},prefix(e){return FV({...PV(this),path:UB(this.path,e)})},middleware(e){return FV({...PV(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return FV({...PV(this),annotations:To(this.annotations,e,t)})},annotateMerge(e){return FV({...PV(this),annotations:Fo(this.annotations,e)})}},PV=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares});function FV(e){function t(){}return Object.setPrototypeOf(t,NV),Object.assign(t,e)}var IV=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?at:JT;return FV({identifier:t,path:n,method:e,params:LV(r?.params,a),query:LV(r?.query,a),headers:LV(r?.headers,a),payload:RV(r?.payload,e,i),success:BV(r?.success,e,i),error:HV(r?.error,i),annotations:So(),middlewares:new Set})};function LV(e,t){if(e!==void 0)return ow(e)?t(e):t(F(e))}function RV(e,t,n){let r=new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:ow(e)?[e]:[F(e).pipe(pV())],a=n?at:QV;for(let e of i){let n=xV(e.ast,t),i=OV(n.contentType),o=r.get(i);if(o){if(o.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(o.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);o.schemas.push(a(e,t))}else r.set(i,{encoding:n,schemas:[a(e,t)]})}return r}var zV=`effect/httpapi/stream/failure`;function BV(e,t,n){if(e===void 0)return new Set;let r=ca(e);return UV(r,t),new Set(n?r:r.map(VV))}function VV(e){return rV(e)?e:lV(e)?uV(e,rV(e.schema)?e.schema:ZV(e.schema,TV(e)),JT(e.headers)):XV(e)}function HV(e,t){if(e===void 0)return new Set;let n=ca(e);for(let e of n)if(rV(lV(e)?e.schema:e))throw Error(`Streaming schemas are not supported in error responses`);return GV(n,DV),new Set(t?n:n.map(VV))}function UV(e,t){let n=!1,r=new Map;for(let i of e){let e=lV(i)?i.schema:i,a=wV(i);if(rV(e)){if(KV(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=WV(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(OV(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);r.set(a,{...i,stream:e})}else{let t=WV(r,a),n=mV(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=TV(i);if(OV(e.contentType)===OV(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(OV(TV(i).contentType)),t.noContent=t.noContent||n}}GV(e,wV)}function WV(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function GV(e,t){let n=new Map;for(let r of e){let e=t(r),i=gV(r.ast),a=lV(r)?r.schema:i?.body??r,o=mV(a.ast)?``:OV(rV(a)?a.contentType:TV(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:new Set},n.set(e,s));let c=()=>Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(lV(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function KV(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(iV(e)&&qV(e.events.ast))throw Error(`SSE event name is reserved: ${zV}`)}function qV(e){return JV(ux(e),new Set)}function JV(e,t){if(t.has(e))return!1;if(t.add(e),ky(e))return e.types.some(e=>JV(e,t));if(Ay(e))return JV(e.thunk(),t);if(!Oy(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&YV(n.type,t)}function YV(e,t){if(t.has(e))return!1;t.add(e);let n=ux(e);return n===e?Ty(e)?e.literal===zV:ky(e)?e.types.some(e=>YV(e,t)):Ay(e)?YV(e.thunk(),t):!1:YV(n,t)}function XV(e){let t=SV(e.ast),n=gV(e.ast);if(n===void 0)return ZV(e,t);let r=uw(n.headers);return F({body:ZV(uw(n.body),t),headers:r}).pipe(Aw(e)).annotate({"~httpApiWithHeaders":{...n,headersCodec:JT(r)}})}function ZV(e,t){switch(t._tag){case`Json`:return VT(e);case`FormUrlEncoded`:return JT(e);case`Text`:case`Uint8Array`:return e}}function QV(e,t){switch(xV(e.ast,t)._tag){case`Json`:return VT(e);case`FormUrlEncoded`:return JT(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var $V=IV(`GET`),eH=IV(`POST`),tH=`~effect/httpapi/HttpApi`,nH={[tH]:tH,pipe(){return nt(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Cn(t,n.identifier,n);return iH({...rH(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Cn(t,n,r.annotateMerge(Fo(e.annotations,r.annotations)))}return iH({...rH(this),groups:t})},prefix(e){return iH({...rH(this),groups:na(this.groups,t=>t.prefix(e))})},middleware(e){return iH({...rH(this),groups:na(this.groups,t=>t.middleware(e))})},annotate(e,t){return iH({...rH(this),annotations:To(this.annotations,e,t)})},annotateMerge(e){return iH({...rH(this),annotations:Fo(this.annotations,e)})}},rH=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),iH=e=>{function t(){}return Object.setPrototypeOf(t,nH),Object.assign(t,e)},aH=e=>iH({identifier:e,groups:{},annotations:So()}),oH=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=Fo(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:Fo(n,e.annotations),successes:sH(jV(e),wV),errors:sH(MV(e),DV)})}},sH=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){if(rV(lV(e)?e.schema:e))return;let r=t(e),i=n.get(r);i===void 0?n.set(r,[e]):i.push(e)}},cH=`~effect/encoding/Sse/SseError`,lH=class extends Ms(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},uH=class extends Ms(`SseError`){[cH]=cH;get message(){return this.reason.message}},dH=10485760,fH=e=>FS((t,n)=>sg(()=>{let n=[],r,i=mH(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=k(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return ug(n)}return cg});return og(function e(){if(fa(n)){let e=n;return n=[],D(e)}return r?ug(r):k(a,e)})})),pH=(e,t)=>KS(fH(t),rE(gH.pipe(Aw(e)))());function mH(e,t){let n=t?.maxEventSize??dH,r,i,a,o,s,c,l,u;return d(),{feed:f,reset:d};function d(){r=!0,i=``,a=0,o=-1,s=!1,c=void 0,l=void 0,u=``}function f(e){i=i?i+e:e,r&&i.startsWith(hH)&&(i=i.slice(hH.length)),r=!1;let t=i.length,c=0;for(;c<t;){s&&=(i[c]===`
34
+ `&&++c,!1);let e=-1,n=o,r;for(let o=a;e<0&&o<t;++o)r=i[o],r===`:`&&n<0?n=o-c:r===`\r`?(s=!0,e=o-c):r===`
35
+ `&&(e=o-c);if(e<0){a=t-c,o=n;break}a=0,o=-1,p(i,c,n,e),c+=e+1}if(c===t?i=``:c>0&&(i=i.slice(c)),i.length+u.length>n){let e=new uH({reason:new lH({maxEventSize:n})});return d(),e}}function p(t,n,r,i){if(i===0){u.length>0&&(e({_tag:`Event`,id:c,event:l||`message`,data:u.slice(0,-1)}),u=``),l=void 0;return}let a=r<0,o=t.slice(n,n+(a?i:r)),s=0;s=a?i:t[n+r+1]===` `?r+2:r+1;let d=n+s,f=i-s,p=t.slice(d,d+f).toString();o===`data`?u+=p?`${p}\n`:`
36
+ `:o===`event`?l=p:o===`id`&&!p.includes(`\0`)?c=p:o===`retry`&&/^\d+$/.test(p)&&e(new vH({duration:ss(parseInt(p,10)),lastEventId:c}))}}var hH=``,gH=F({id:cw(P),event:P,data:P}),_H=`~effect/encoding/Sse/Retry`,vH=class e extends js(`Retry`){[_H]=_H;static is(e){return At(e,_H)}static filter(t){return e.is(t)?zi(t):Bi(t)}},yH=`~effect/httpapi/HttpApiMiddleware`,bH=`~effect/httpapi/HttpApiMiddleware/Security`,xH=()=>(e,t)=>{let n=globalThis.Error,r=pc();mc(2);let i=new n;mc(r);class a extends ro()(e){}let o=a;if(Object.defineProperty(a,"stack",{get(){return i.stack}}),o[yH]=yH,o.error=SH(t?.error),o.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);o[bH]=bH,o.security=t.security}return o};function SH(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var CH=(e,t)=>O(function*(){let n=yield*Vg(),r=t.httpClient.pipe(t?.baseUrl===void 0?at:MB(aB(t.baseUrl.toString())));function i(e,t,a,o,s){if(s===-1)return r.execute(a);let c=n.mapUnsafe.get(o[s]);return c===void 0?i(e,t,a,o,s-1):c({endpoint:t,group:e,request:a,next(n){return i(e,t,n,o,s-1)}})}oH(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:a,successes:o}=e,s=DH(r.path),c={orElse:KH},l=vB(c),u=new Map;for(let[e,t]of a.entries()){let n=MH(t);for(let[t,r]of n.entries())AH(u,e,t,OH(r))}for(let[e,t]of u.entries()){let n=jH(t);c[e]=e=>k(Og(n(e),t=>dg(Ff(kf(new jz({reason:new Iz({request:e.request,response:e})})),t))),ug)}let d=new Map;for(let[e,t]of o.entries()){let n=MH(t);for(let[t,r]of n.entries())AH(d,e,t,OH(r))}for(let e of IH(r)){let t=FH(e)?e.schema:e;AH(d,wV(e),t.contentType,LH(e))}for(let[e,t]of d.entries())c[e]=jH(t);let f=kC(r.params,tw),p=AV(r),m=fa(p)?zz(r.method)?tw(JH(p,r.method)):tw(L(p)):void 0,h=kC(r.headers,tw),g=kC(r.query,tw),_=Array.from(e.middleware,e=>`${e.key}/Client`),v=m_(function*(e){let a=Yz(r.method)(r.path);if(e!==void 0){if(f!==void 0){let t=yield*f(e.params);a=iB(a,s(t))}if(m!==void 0){if(zz(r.method)){if(e.payload instanceof FormData)a=fB(a,e.payload);else{let t=yield*m(e.payload);a=uB(a,t)}}else{let t=yield*m(e.payload);a=cB(a,t)}}if(h!==void 0){let t=yield*h(e.headers);a=tB(a,t)}if(g!==void 0){let t=yield*g(e.query);a=cB(a,t)}}let o=yield*i(n,r,a,_,_.length-1);if(e?.responseMode===`response-only`)return o;let c=yield*t.transformResponse===void 0?l(o):t.transformResponse(l(o));return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:v})}})}),wH=(e,t)=>k(DB,n=>TH(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),TH=(e,t)=>{let n={};return CH(e,{...t,onGroup({group:e}){e.topLevel||Cn(n,e.identifier,{})},onEndpoint({endpoint:e,endpointFn:t,group:r}){Cn(r.topLevel?n:n[r.identifier],e.identifier,t)}}).pipe(Sg(n))},EH=/(\/?):(\w+)(\?)?/g,DH=e=>EH.test(e)?(EH.lastIndex=0,t=>(EH.lastIndex=0,e.replace(EH,(e,n,r,i)=>{let a=t[r];if(a===void 0){if(i!==void 0)return``;throw Error(`Missing path parameter: ${r}`)}return`${n}${encodeURIComponent(a)}`}))):t=>e;function OH(e){let t=e.some(e=>lV(e)||gV(e.ast)!==void 0),n=YC(t?L(e.map(kH)):WH(e));return e=>k(e.arrayBuffer,t?t=>n({body:t,headers:e.headers}):n)}function kH(e){let t=lV(e),n=gV(e.ast);if(n!==void 0)return F({body:GH(n.body),headers:n.headersCodec}).pipe(Aw(e));let r=t?e.schema:e;return F({body:GH(r).pipe(Aw(r)),headers:t?e.headers:pw}).pipe(Aw(t?e:lw(e),ty({decode:e=>t?cV(e):e.body,encode:e=>t?e:{body:e,headers:void 0}})))}function AH(e,t,n,r){let i=OV(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function jH(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:t=>{let n=OV(t.headers[`content-type`]??``),r=e.find(e=>e.contentType===n);return r===void 0?NH(t,n,e):r.decode(t)}}function MH(e){let t=new Map;for(let n of e){let e=mV((lV(n)?n.schema:n).ast)?``:OV(TV(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function NH(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return ug(new jz({reason:new Lz({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var PH=`effect/httpapi/stream/failure`,FH=e=>lV(e);function IH(e){let t=[];for(let n of e.success)rV(lV(n)?n.schema:n)&&t.push(n);return t}function LH(e){let t=FH(e),n=t?e.schema:e,r=aV(n)?void 0:{declaration:n,decoder:RH(n)},i=e=>xg(Vg(),t=>xE(r===void 0?e.stream:zH(e.stream,r.declaration,r.decoder),t));if(!t)return i;let a=qC(e.headers);return e=>k(a(e.headers),t=>xg(i(e),e=>cV({body:e,headers:t})))}function RH(e){return pH(L([F({event:dw(PH),data:TT(VT(dT(e.error,vT())))}),e.events]))}function zH(e,t,n){let r=dE(e.pipe(yE,vE(n)),e=>sg(()=>{let t;return og(()=>t===void 0?k(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===PH&&wf(r.data)){if(n===0)return dg(r.data);t=r.data,e=e.slice(0,n);break}}return D(e)}):dg(t))}));return t.sseMode===`data`?gE(r,e=>e.data):r}var BH=Rw(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),VH=BH.pipe(Aw(kT,ty({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),HH=BH.pipe(Aw(P,ty({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),UH=HH.pipe(Aw(L([dw(``).pipe(Aw(hw,ty({decode:()=>void 0,encode:()=>``}))),ET])));function WH(e){return L(e.map(t));function t(e){return GH(e).pipe(Aw(e))}}function GH(e){switch(SV(e.ast)._tag){case`Json`:return Sy(ux(e.ast))?UH.pipe(Aw(pw,ty({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):UH;case`FormUrlEncoded`:return HH.pipe(Aw(qR));case`Uint8Array`:return VH;case`Text`:return HH}}var KH=e=>ug(new jz({reason:new Lz({request:e.request,response:e})})),qH=BC(YR);function JH(e,t){return L(e.map(e=>XH(e,t)))}var YH=new WeakMap;function XH(e,t){let n=e.ast,r=YH.get(n);if(r!==void 0)return r;let i=xV(n,t),a=qH.pipe(Aw(e,ey({decode(e,t){return ug(new J_({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return ug(new J_({message:`Payload must be a FormData`},e,t));case`Json`:try{return D(tz(JSON.stringify(e),i.contentType))}catch{return ug(new K_({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?D(tz(e,i.contentType)):ug(new K_({message:`Expected a string`},e,t));case`FormUrlEncoded`:return Ot(e)?D(rz(LR(e),i.contentType)):ug(new K_({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?D($R(e,i.contentType)):ug(new K_({message:`Expected a Uint8Array`},e,t))}}})));return YH.set(n,a),a}var ZH=`~effect/httpapi/HttpApiGroup`,QH={[ZH]:ZH,add(...e){let t={...this.endpoints};for(let n of e)Cn(t,n.identifier,n);return eU({...$H(this),endpoints:t})},prefix(e){return eU({...$H(this),endpoints:na(this.endpoints,t=>t.prefix(e))})},middleware(e){return eU({...$H(this),endpoints:na(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return eU({...$H(this),annotations:Fo(this.annotations,e)})},annotate(e,t){return eU({...$H(this),annotations:To(this.annotations,e,t)})},annotateEndpointsMerge(e){return eU({...$H(this),endpoints:na(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return eU({...$H(this),endpoints:na(this.endpoints,n=>n.annotate(e,t))})},pipe(){return nt(this,arguments)}},$H=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),eU=e=>{function t(){}return Object.setPrototypeOf(t,QH),t.key=`effect/httpapi/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},tU=(e,t)=>eU({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:So()}),nU=class extends H(`@usine/config/AgentFile`)({name:DO,harness:wO,model:CO,effort:TO,parentModel:nT(CO),parentEffort:nT(TO),persona:OO}){get agent(){return new kO({name:this.name,persona:this.persona,brain:new EO({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},rU=class extends H(`@usine/config/InvalidAgent`)({file:bO,error:SO}){},iU=P.check(Vw(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),eT(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(z(`GitHubLabelName`)),aU=e=>e.toLowerCase(),oU=P.check(Vw(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(z(`GitHubLabelColor`)),sU=P.check(eT(100,{message:`Expected a GitHub label description of at most 100 characters`})),cU=class extends H(`@usine/config/DeclaredLabel`)({name:iU,color:iT(oU),description:iT(sU)}){},lU=e=>P.check(Vw(/\S/u,{message:e})),uU=e=>Bw(t=>new Set(t.map(t=>yD(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),dU=lU(`Expected a non-blank lane name`).pipe(z(`LaneName`)),fU=Ow([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),pU=new Set([`issue-closed`,`pr-closed`,`pr-merged`]),mU=e=>pU.has(e),hU=class extends H(`@usine/config/LabelLaneSource`)({label:iU}){},gU=L([hU,class extends H(`@usine/config/StateLaneSource`)({state:fU}){}]),_U=class extends H(`@usine/config/Lane`)({name:dU,sources:I(gU).check($w())}){},vU=lU(`Expected a non-blank registry tag`).pipe(z(`RegistryTag`)),yU=B.check(Yw(1)),bU=Bw(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),xU=e=>`label`in e?`label:${aU(e.label)}`:`state:${e.state}`,SU=Bw(e=>{let t=e.flatMap(({sources:e})=>e.map(xU));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),CU=I(_U).check(bU,SU),wU=Bw(e=>new Set(e.map(({name:e})=>aU(e))).size===e.length,{message:`Expected unique GitHub label names`}),TU=I(cU).check(wU),EU=class extends H(`@usine/config/ManagedRepo`)({name:mD,tags:I(vU).check(tT()).pipe(Pw(D([]))),lanes:CU.pipe(Pw(D([])))}){},DU=yU.pipe(Pw(D(1))),OU=class extends H(`@usine/config/LocalWorker`)({name:BO,kind:dw(`local`),maxConcurrentAttempts:DU}){},kU=class extends H(`@usine/config/ExeDevWorker`)({name:BO,kind:dw(`exe.dev`),maxConcurrentAttempts:DU}){},AU=P.check(Vw(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(z(`EnvironmentVariableName`)),jU=class extends H(`@usine/config/WorkerGateway`)({domain:qO,destination:UO,adminPort:JO.pipe(Pw(D(7070))),adminTokenEnv:AU,llmProviders:I(YO).check(tT()).pipe(Pw(D([])))}){},MU=class extends H(`@usine/config/SshWorker`)({name:BO,kind:dw(`ssh`),maxConcurrentAttempts:DU,destination:UO,identityFile:iT(GO),port:iT(WO),root:KO,gateway:iT(jU.pipe(Sw({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`})))}){};L([OU,kU,MU]);var NU=class extends H(`@usine/config/Settings`)({pollInterval:yU.pipe(Pw(D(60))),maxChildren:ek.pipe(Pw(D(4))),maxAttemptMinutes:iT(yU),maxAttemptTokens:iT(yU),parentModel:iT(CO),parentEffort:iT(TO)}){},PU=L([F({mode:dw(`off`)}),F({mode:dw(`deliveries`)}),F({mode:dw(`endpoint`),publicUrl:ST}).pipe(Sw({publicUrl:`public_url`}))]),FU=NU.pipe(Sw({pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),IU=L([OU.pipe(Sw({maxConcurrentAttempts:`max_concurrent_attempts`})),kU.pipe(Sw({maxConcurrentAttempts:`max_concurrent_attempts`})),MU.pipe(Sw({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`}))]),LU=I(EU).check(uU(e=>e.name)),RU=I(IU).check($w(),bU),zU=class extends H(`@usine/config/UsineConfig`)({version:dw(1),labels:TU.pipe(Pw(D([]))),repos:LU,settings:FU.pipe(Pw(D({}))),workers:RU.pipe(Pw(D([{name:`local`,kind:`local`}]))),webhooks:PU.pipe(Pw(D({mode:`off`}))),operator:iT(Rk)}){},BU=class extends H(`@usine/config/Selector`)({repos:iT(I(mD).check($w(),uU(e=>e))),tags:iT(I(vU).check($w(),tT()))}){}.check(Bw(e=>T(e.repos)||T(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),VU=(e,t)=>E(e,{onNone:()=>!0,onSome:e=>{let n=E(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>yD(e)===yD(t.name))}),r=E(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),HU=P.check(Bw(e=>e.trim().split(/\s+/u).length===5&&Gi(ah(e)),{message:`Expected a valid five-field cron expression`})).pipe(z(`Cron`)),UU=P.check(Bw(e=>T(Cv(e)),{message:`Expected an IANA time-zone name`})).pipe(z(`TimeZone`)),WU=class extends H(`@usine/config/IssueTrigger`)({on:dw(`issue`),if:gO}){},GU=class extends H(`@usine/config/PullRequestTrigger`)({on:dw(`pr`),if:gO}){},KU=class extends H(`@usine/config/ScheduleTrigger`)({on:dw(`schedule`),if:gO,cron:HU,tz:UU.pipe(Pw(D(`UTC`)))}){},qU=L([WU,GU,KU]),JU=Vw(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),YU=CD.check(JU),XU=lU(`Expected a non-blank Markdown prompt`).pipe(z(`PromptTemplate`)),ZU=class extends H(`@usine/config/LoopFile`)({name:YU,trigger:qU,selector:nT(BU),approval:TD,maxCycles:sA.pipe(Pw(D(lA)),Mw(D(lA))),permissions:DD.pipe(Pw(D(`write`)),Mw(D(`write`))),step:RO,agent:DO,body:XU}){},QU=class extends H(`@usine/config/QuarantinedLoop`)({file:bO,error:SO}){},$U=e=>bO.make(`loops/${e}.md`),eW=Ow([`workers`,`webhooks`]),tW=e=>F({added:I(e),removed:I(e),changed:I(e)}),nW=class extends H(`@usine/orchestrator/InstanceReload`)({loops:tW(CD),agents:tW(DO),labels:tW(iU),repos:tW(mD),workers:tW(BO),settingsChanged:_w,operatorChanged:_w,quarantinedLoops:I(QU),invalidAgents:I(rU)}){},rW=class extends U(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:P}){},iW=class extends U(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:P}){},aW=class extends U(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:P}){},oW=class extends U(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:P}){},sW=class extends U(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:P}){},cW=class extends U(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:Dk}){},lW=class extends U(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:ek,attemptedChildren:tk}){},uW=L([rW,iW,aW,oW,sW,cW,lW]),dW=class extends U(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},fW=class extends U(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:uW}){},pW=class extends U(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},mW=L([dW,fW,pW]),hW=class extends U(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},gW=class extends U(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:UO,port:R(WO)}){},_W=L([hW,gW]),vW=class extends H(`@usine/orchestrator/AttemptView`)({id:Kk,number:qk,worker:BO,workerAccess:R(_W),brain:EO,task:Jk,agent:DO,operatorIntervened:_w,startedAt:P,outcome:R(mW),endedAt:R(P),salvage:R(Lk),start:R(Gk).pipe(Mw(D(null))),reattachedAt:R(P).pipe(Mw(D(null)))}){},yW=class extends U(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:uW}){},bW=L([vA,yA,bA,yW,SA,CA,wA,EA,DA,TA,FA,IA,LA,RA]),xW=class extends H(`@usine/orchestrator/TranscriptEventView`)({sequence:_j,attemptId:Kk,receivedAt:P,direction:gA,target:sw(MA),operator:sw(V),payload:bW}){},SW=class extends H(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:Kk,before:_j}){},CW=class extends U(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},wW=class extends U(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:_j}){},TW=class extends U(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:Kk,before:_j}){};L([CW,wW,TW]);var EW=class extends BT(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:oO,attemptId:Kk}){},DW=class extends H(`@usine/orchestrator/UsageCostView`)({usd:fk,estimate:_w}){},OW=class extends H(`@usine/orchestrator/SessionUsageView`)({attemptId:Kk,session:nk,pool:mk,tokens:QO,cost:R(DW)}){},kW=class extends H(`@usine/orchestrator/PoolUsageView`)({pool:mk,tokens:QO,cost:R(DW)}){},AW=class extends H(`@usine/orchestrator/RunUsageView`)({tokens:QO,pools:I(kW),sessions:I(OW)}){},jW=class extends H(`@usine/orchestrator/TaskPoolUsageView`)({pool:mk,tokens:QO,cost:R(DW),unpriced:_w}){},MW=class extends H(`@usine/orchestrator/TaskUsageView`)({durationMillis:B.check(Yw(0)),runningSince:I(P),unmeasured:B.check(Yw(0)),tokens:QO,pools:I(jW),cost:R(DW)}){},NW=[`apiKeys`,`claudePlan`,`chatgptPlan`],PW=(e,t)=>e===`chatgptPlan`?null:E(t,{onNone:()=>null,onSome:t=>new DW({usd:t,estimate:e===`claudePlan`})}),FW=e=>{let t=new Map;for(let{attemptId:n,envelope:r}of e){let e=r.payload;if(e._tag!==`SessionEvent`||e.event._tag!==`SessionTokensUpdated`)continue;let{session:i,totalTokens:a,costUsd:o}=e.event,s=`${n} ${i.id}`,c=t.get(s);if(c!==void 0&&c.tokens>=a)continue;let l=gk(i);t.set(s,new OW({attemptId:n,session:i,pool:l,tokens:a,cost:PW(l,o)}))}let n=[...t.values()],r=NW.flatMap(e=>{let t=n.filter(t=>t.pool===e);if(t.length===0)return[];let r=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new kW({pool:e,tokens:QO.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:PW(e,r.length===t.length?C(fk.make(r.reduce((e,t)=>e+t,0))):S())})]});return new AW({tokens:QO.make(n.reduce((e,{tokens:t})=>e+t,0)),pools:r,sessions:n})},IW=(e,t)=>{let n=0,r=0,i=[];for(let{attempts:t}of e)for(let{startedAt:e,endedAt:a,outcome:o}of t)o===null?i.push(e):a===null?r+=1:n+=Math.max(0,Date.parse(a)-Date.parse(e));let a=e.flatMap(({id:e})=>t.get(e)?.sessions??[]),o=NW.flatMap(e=>{let t=a.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new jW({pool:e,tokens:QO.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:PW(e,n.length===0?S():C(fk.make(n.reduce((e,t)=>e+t,0)))),unpriced:e!==`chatgptPlan`&&n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new MW({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:QO.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new DW({usd:fk.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},LW=O(function*(){let e=yield*yL,t=yield*sg(()=>new Map),n=j(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new Ej({attemptId:n.id}));return T(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:j(`RunUsageReader.read`)(function*(e){yield*A({runId:e.run.id});let t=yield*ng(e.attempts,n,{concurrency:4}),r=FW(t.flatMap(({reports:e})=>e));return yield*N(`Read Run usage`,{runId:e.run.id,sessions:r.sessions.length,tokens:r.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),r})}});(class e extends ro()(`@usine/orchestrator/RunUsageReader`){static layer=Op(e,LW)});var RW=Ow(YD),zW=R(P),BW=class extends H(`@usine/orchestrator/EditAndRetry`)({task:Jk,agent:DO}){},VW=class extends H(`@usine/orchestrator/SessionIntervention`)({attemptId:Kk,target:MA.pipe(Pw(D({_tag:`Parent`}))),action:OA}){};BT(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:DO,message:P}),BT(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:CD,message:P});var HW=class extends H(`@usine/orchestrator/ApprovalView`)({approvedAt:P,source:R(KA)}){},UW=class extends H(`@usine/orchestrator/RunView`)({id:oO,itemKey:aA,loop:CD,repository:mD,agent:DO,state:RW,loopPaused:_w,openedAt:P,closedAt:R(P),task:P,attempts:I(vW),approval:R(HW),runAgain:R(gj),resultMessage:zW,pullRequestUrl:zW,canApprove:_w,canRetry:_w,canResolveFailure:_w,canCancel:_w,canRunAgain:_w}){},WW=B.check(Yw(0)),GW=B.check(Yw(0)),KW=class extends H(`@usine/orchestrator/RunDurationView`)({endedMillis:WW,runningSince:R(P),unmeasured:GW}){},qW=class extends H(`@usine/orchestrator/RunDetailView`)({run:UW,eventDedupKey:P,eventPayload:tE,transcript:I(xW),sessionState:I(xW),earlierTranscript:I(SW),worker:R(BO).pipe(Mw(D(null))),duration:KW.pipe(Mw(D(new KW({endedMillis:0,runningSince:null,unmeasured:0})))),usage:AW.pipe(Mw(D(new AW({tokens:QO.make(0),pools:[],sessions:[]}))))}){},JW=V.pipe(z(`BoardLaneId`)),YW=Ow([`authored`,`proposed`,`fallback`]),XW=class extends H(`@usine/orchestrator/BoardItemLink`)({itemKey:aA,kind:Ow([`issue`,`pr`]),number:oA,title:P,url:V}){},ZW=class extends H(`@usine/orchestrator/BoardPullRequestView`)({number:oA,url:V,state:Ow([`pr-open`,`pr-merged`])}){},QW=class extends H(`@usine/orchestrator/BoardTaskView`)({...XW.fields,state:fU,labels:I(iU),items:I(XW).check($w()),pullRequest:R(ZW),runs:I(UW),run:R(UW),needsYou:_w,conflicting:_w,loops:I(CD),usage:MW}){},$W={id:JW,name:dU,sources:I(gU),origin:YW,items:I(QW)},eG=class extends U(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...$W,origin:dw(`authored`),labels:I(iU).check($w())}){},tG=class extends U(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,$W){},nG=L([eG,tG]),rG=class extends BT(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:mD,itemKey:aA,message:V}){},iG=class extends H(`@usine/orchestrator/BoardView`)({lanes:I(nG),failures:I(rG)}){},aG=class extends H(`@usine/orchestrator/LabelView`)({name:iU,color:R(P),description:R(P)}){};H(`@usine/orchestrator/BoardMove`)({repository:mD,item:oA,toLane:JW});var oG=class extends BT(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:mD}){},sG=class extends BT(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:mD,item:oA}){};BT(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:mD,lane:JW}),BT(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:mD,lane:JW});var cG=Ro(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),lG=class extends ro()(`effect/http/FetchHttpClient/RequestInit`){},uG=LB(D(jB((e,t,n,r)=>{let i=r.getRef(cG),a=Do(r.context,lG)??{},o=a.headers?hz(dz(a.headers),e.headers):e.headers;o[`content-length`]&&(o=gz(o,`content-length`));let s=r=>xg(ig({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new jz({reason:new Pz({request:e,cause:t})})}),t=>_B(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return k(TE(e.body.stream),s)}return s(void 0)}))),dG=B.check(Yw(1)).pipe(z(`GitHubAppId`)),fG=oT(V.check(Vw(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(z(`GitHubAppPrivateKey`)),{disallowEncode:!0});H(`@usine/github/AppCredentials`)({appId:dG,privateKey:fG});var pG=class extends ro()(`@usine/github/GitHubCredentials`){},mG=class extends BT(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:V}){},hG=new TextEncoder,gG=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),_G=(...e)=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},vG=e=>{if(e<128)return new Uint8Array([e]);let t=[];for(let n=e;n>0;n>>>=8)t.unshift(n&255);return new Uint8Array([128|t.length,...t])},yG=(e,t)=>_G(new Uint8Array([e]),vG(t.length),t),bG=e=>yG(48,_G(new Uint8Array([2,1,0]),gG,yG(4,e))),xG=e=>{let t=e.includes(`-----BEGIN RSA PRIVATE KEY-----`),n=e.replace(/-----BEGIN (?:RSA )?PRIVATE KEY-----/gu,``).replace(/-----END (?:RSA )?PRIVATE KEY-----/gu,``).replace(/\s/gu,``),r=atob(n),i=Uint8Array.from(r,e=>e.charCodeAt(0));return t?bG(i):i},SG=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},CG=e=>SG(hG.encode(JSON.stringify(e))),wG=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},TG=j(`AppJwt.import`)(function*(e){let t=yield*ig({try:async()=>crypto.subtle.importKey(`pkcs8`,wG(xG(IC(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new mG({message:`Could not import the GitHub App private key as an RSA private key`})});return j(`AppJwt.sign`)(function*(){let n=Math.floor((yield*Lp)/1e3),r=`${CG({alg:`RS256`,typ:`JWT`})}.${CG({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*rg(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,wG(hG.encode(r))));return PC(`${r}.${SG(new Uint8Array(i))}`)})}),EG=B.check(Yw(1)),DG=EG.pipe(z(`GitHubInstallationId`)),OG=EG.pipe(z(`GitHubRepositoryId`)),kG=V.pipe(z(`GitHubAppSlug`)),AG=class extends H(`@usine/github/Installation`)({id:DG,accountLogin:V,appSlug:kG}){},jG=class extends U(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},MG=class extends U(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:mD,repositoryId:OG,permissions:DD}){},NG=L([jG,MG]),PG=class extends H(`@usine/github/InstallationToken`)({value:aT(V,{disallowJsonEncode:!0}),expiresAt:AT,scope:NG}){},FG=Ow([`missing`,`multiple`,`suspended`]),IG=class extends BT(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:FG,message:V}){},LG={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},RG={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},zG=(e,t)=>e===t||t===`read`&&e===`write`,BG=e=>Object.entries(LG).flatMap(([t,n])=>zG(e[t],n)?[]:[`${t}:${n}`]),VG=class extends U(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:DG,repository:mD,repositoryId:OG}){},HG=class extends BT(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:mD,message:V}){};L([VG,HG]);var UG=(e,t,n)=>{let r=new Map(n.map(e=>[e.name.toLowerCase(),e]));return t.map(t=>{let n=r.get(t.toLowerCase());return n===void 0?new HG({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new VG({installationId:e.id,repository:t,repositoryId:n.id})})},WG=class extends BT(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:I(V).check($w()),message:V}){},GG=Ow([`create-repository-label`,`discover-installation`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`update-item-labels`]),KG=class extends BT(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:GG,status:nT(B),message:V}){},qG=class extends BT(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:GG,retryAt:AT,message:V}){},JG=class extends BT(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:GG,message:V,detail:V}){},YG=class extends BT(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:GG,item:B.check(Yw(1)),message:V}){};L([IG,WG,KG,qG,JG]);var XG=`https://api.github.com`,ZG=`2026-03-10`,QG=e=>tB({accept:`application/vnd.github+json`,authorization:`Bearer ${IC(e)}`,"user-agent":`usine`,"x-github-api-version":ZG}),$G=(e,t)=>new KG({operation:e,status:t.response===void 0?S():C(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),eK=QC(F({message:V})),tK=(e,t)=>t.json.pipe(xg(t=>E(eK(t),{onNone:()=>e,onSome:({message:t})=>new KG({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),Tg(t=>N(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(Sg(e)))),nK=(e,t)=>new JG({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),rK=e=>{if(e===void 0||!/^\d+$/u.test(e))return S();let t=Number(e);return Number.isSafeInteger(t)?C(t):S()},iK=(e,t)=>{let n=rK(e);if(T(n))return C(t+n.value*1e3);if(e===void 0)return S();let r=Date.parse(e);return Number.isFinite(r)?C(r):S()},aK=(e,t)=>{let n=rK(e[`x-ratelimit-remaining`]),r=rK(e[`x-ratelimit-reset`]);return T(n)&&n.value<=t&&T(r)?C(r.value*1e3):S()},oK=(e,t)=>Ai(rK(e[`x-poll-interval`]),e=>t+e*1e3),sK=e=>{let t=e.flatMap(e=>E(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?S():C(Math.max(...t))},cK=(e,t)=>sK([iK(e[`retry-after`],t),aK(e,0)]),lK=(e,t,n)=>{let r=ji(cK(t.headers,n),bv);return(t.status===403||t.status===429)&&T(r)?new qG({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new KG({operation:e,status:C(t.status),message:`GitHub returned HTTP status ${t.status}`})},uK=36e5,dK=3e5,fK=I(F({id:DG,appSlug:kG,account:F({login:V}),permissions:Cw(P,P),suspendedAt:R(P)}).pipe(Sw({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),pK=F({id:OG,name:mD}).pipe(Sw({name:`full_name`})),mK=F({totalCount:B.check(Yw(0)),repositories:I(pK)}).pipe(Sw({totalCount:`total_count`})),hK=F({token:V,expiresAt:jT,repositories:iT(I(pK))}).pipe(Sw({expiresAt:`expires_at`})),gK=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:LG}}:{operation:`mint-worker-token`,body:{permissions:RG[e.permissions],repository_ids:[e.repositoryId]}},_K=class e extends ro()(`@usine/github/GitHubApp`){static layer=Op(e,O(function*(){let e=yield*TG(yield*pG),t=yield*DB,n=(e,n,r)=>O(function*(){let i=yield*t.execute(n).pipe(Ag(t=>$G(e,t)));if(i.status<200||i.status>=300){let t=lK(e,i,yield*Lp);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*tK(t,i)}return yield*mB(r)(i).pipe(Ag(t=>nK(e,t.message)))}),r=j(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,Xz(`${XG}/app/installations?per_page=2`).pipe(QG(t)),fK);if(r===void 0)return yield*new IG({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new IG({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new IG({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=BG(r.permissions);return a.length>0?yield*new WG({missing:a,message:`The GitHub App installation is missing permissions: ${a.join(`, `)}. Grant them in the GitHub App settings, then approve the change on the installation.`}):new AG({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=j(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=gK(r);yield*A({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,Zz(`${XG}/app/installations/${t}/access_tokens`).pipe(dB(a),QG(o)),hK),c=yield*Lp,l=Dv(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new JG({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${kv(s.expiresAt)} is ${l}ms from now`});l>uK&&(yield*M(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-uK}));let u=xi(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new JG({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new PG({value:PC(s.token),expiresAt:yv(c+Math.min(l,uK)),scope:r})}),a=j(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,Xz(`${XG}/installation/repositories?per_page=100&page=${r}`).pipe(QG(e.value)),mK);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new JG({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*dD(S()),s=j(`GitHubApp.lease`)(()=>pD(o,e=>O(function*(){let t=yield*Lp;if(T(e)&&Dv(e.value.token.expiresAt)-t>dK)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new jG)};return[a,C(a)]})));return{installation:j(`GitHubApp.installation`)(()=>xg(s(),e=>e.installation)),installationToken:j(`GitHubApp.installationToken`)(()=>xg(s(),e=>e.token)),projectAccess:j(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return UG(t,e,yield*a(n))}),workerToken:j(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new MG({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},vK=V.pipe(z(`GitHubEntityTag`)),yK=class e extends H(`@usine/github/PollCursor`)({entityTag:rT(vK),watermark:rT(jT)}){static empty=new e({entityTag:S(),watermark:S()})},bK=class extends U(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:B.check(Yw(1)),updatedAt:AT}){},xK=class extends U(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:B.check(Yw(1)),updatedAt:AT}){},SK=L([bK,xK]),CK=class extends U(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:yK,nextPollAt:nT(AT),backoffUntil:nT(AT).pipe(Mw(D(S())))}){},wK=class extends U(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:yK,items:I(SK),backlog:_w,nextPollAt:nT(AT),backoffUntil:nT(AT).pipe(Mw(D(S())))}){};L([CK,wK]);var TK=V.pipe(z(`GitHubRepositoryLabelName`)),EK=P.check(Vw(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(z(`GitHubRepositoryLabelColor`)),DK=class extends H(`@usine/github/RepositoryLabel`)({name:TK,color:EK,description:rT(P)}){},OK=Bw(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),kK=class extends H(`@usine/github/RepositoryLabelCatalog`)({entityTag:rT(vK),labels:I(DK).check(OK)}){},AK=class extends U(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};L([kK,AK]);var jK=class extends H(`@usine/github/NewRepositoryLabel`)({name:TK,color:nT(EK),description:nT(P)}){},MK=F({name:TK,color:EK,description:R(P)}),NK=e=>{let{name:t,owner:n}=vD(e);return`${XG}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},PK=class e extends ro()(`@usine/github/GitHubLabelWriter`){static layer=Op(e,O(function*(){let e=yield*_K,t=yield*DB;return{create:j(`GitHubLabelWriter.create`)(function*(n,r){yield*A({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};T(r.color)&&(a.color=r.color.value),T(r.description)&&(a.description=r.description.value);let o=Zz(NK(n)).pipe(dB(a),QG(i.value)),s=yield*t.execute(o).pipe(Ag(e=>$G(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*lK(`create-repository-label`,s,yield*Lp);let c=yield*mB(MK)(s).pipe(Ag(e=>nK(`create-repository-label`,e.message)));return new DK({name:c.name,color:c.color,description:wi(c.description)})})}}))},FK=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),IK=e=>Array.isArray(e)?e.map(IK):KC(nE)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!FK.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,IK(t)])):e,LK=6e4,RK=F({data:sw(pw),errors:sw(I(F({message:P,type:sw(P)})))}),zK=j(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=Zz(`${XG}/graphql`).pipe(dB({query:r,variables:i}),QG(t.value)),s=yield*e.execute(o).pipe(Ag(e=>$G(n,e))),c=yield*Lp;if(s.status!==200)return yield*lK(n,s,c);let l=yield*mB(RK)(s).pipe(Ag(e=>nK(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new qG({operation:n,retryAt:yv(xi(cK(s.headers,c),()=>c+LK)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*nK(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*qC(a)(l.data).pipe(Ag(e=>nK(n,e.message)))}),BK=B.check(Yw(1)),VK=B.check(Yw(0)),HK=P.check(Vw(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),UK=(e,t)=>R(e).pipe(Aw(e,{decode:Rv(e=>e??t),encode:Rv(e=>e)})),WK={totalCount:0,nodes:[]},GK=F({login:V}),KK=R(GK),qK=F({totalCount:VK,nodes:I(F({name:V}))}),JK=F({totalCount:VK,nodes:I(F({author:KK,body:P,createdAt:HK}))}),YK=F({number:BK,title:P,body:P,url:V,state:P,stateReason:R(P),createdAt:HK,updatedAt:HK,closedAt:R(HK),author:KK,issueType:R(F({name:P})),milestone:R(F({title:P})),labels:UK(qK,WK),assignees:F({totalCount:VK,nodes:I(GK)}),comments:JK,closedByPullRequestsReferences:UK(F({totalCount:VK,nodes:I(F({number:BK,state:P,isDraft:_w,url:V}))}),WK)}),XK=R(F({login:sw(V)})),ZK=F({author:KK,state:P,body:P,submittedAt:R(HK),commit:R(F({oid:V}))}),QK=F({author:KK,body:P}),$K=F({number:BK,title:P,body:P,url:V,state:P,isDraft:_w,merged:_w,createdAt:HK,updatedAt:HK,mergedAt:R(HK),author:KK,baseRefName:P,headRefName:P,headRefOid:V,additions:VK,deletions:VK,changedFiles:VK,reviewDecision:R(P),mergeable:P.pipe(Pw(D(`UNKNOWN`))),mergeStateStatus:P.pipe(Pw(D(`UNKNOWN`))),statusCheckRollup:R(F({state:P})),labels:UK(qK,WK),reviewRequests:UK(F({totalCount:VK,nodes:I(F({requestedReviewer:XK}))}),WK),reviews:UK(F({totalCount:VK,nodes:I(ZK)}),WK),reviewThreads:F({totalCount:VK,nodes:I(F({isResolved:_w,isOutdated:_w,path:P,comments:F({totalCount:VK,nodes:I(QK)})}))}),comments:JK,closingIssuesReferences:UK(F({totalCount:VK,nodes:I(F({number:BK,state:P}))}),WK)}),eq=P.check(Vw(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(z(`GitHubContentHash`)),tq=class extends U(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:YK,contentHash:eq}){},nq=class extends U(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:$K,contentHash:eq}){};L([tq,nq]);var rq=`
37
+ query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
38
+ repository(owner: $owner, name: $name) {
39
+ issue(number: $number) {
40
+ number
41
+ title
42
+ body
43
+ url
44
+ state
45
+ stateReason
46
+ createdAt
47
+ updatedAt
48
+ closedAt
49
+ author { login }
50
+ issueType { name }
51
+ milestone { title }
52
+ labels(first: 50) {
53
+ totalCount
54
+ nodes { name }
55
+ }
56
+ assignees(first: 10) {
57
+ totalCount
58
+ nodes { login }
59
+ }
60
+ comments(last: 20) {
61
+ totalCount
62
+ nodes {
63
+ author { login }
64
+ body
65
+ createdAt
66
+ }
67
+ }
68
+ closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
69
+ totalCount
70
+ nodes {
71
+ number
72
+ state
73
+ isDraft
74
+ url
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+ `,iq=`
81
+ query UsinePullRequestPayload($owner: String!, $name: String!, $number: Int!) {
82
+ repository(owner: $owner, name: $name) {
83
+ pullRequest(number: $number) {
84
+ number
85
+ title
86
+ body
87
+ url
88
+ state
89
+ isDraft
90
+ merged
91
+ createdAt
92
+ updatedAt
93
+ mergedAt
94
+ author { login }
95
+ baseRefName
96
+ headRefName
97
+ headRefOid
98
+ additions
99
+ deletions
100
+ changedFiles
101
+ reviewDecision
102
+ mergeable
103
+ mergeStateStatus
104
+ statusCheckRollup { state }
105
+ labels(first: 50) {
106
+ totalCount
107
+ nodes { name }
108
+ }
109
+ reviewRequests(first: 10) {
110
+ totalCount
111
+ nodes {
112
+ requestedReviewer {
113
+ ... on User { login }
114
+ }
115
+ }
116
+ }
117
+ reviews(last: 20) {
118
+ totalCount
119
+ nodes {
120
+ author { login }
121
+ state
122
+ body
123
+ submittedAt
124
+ commit { oid }
125
+ }
126
+ }
127
+ reviewThreads(first: 50) {
128
+ totalCount
129
+ nodes {
130
+ isResolved
131
+ isOutdated
132
+ path
133
+ comments(first: 10) {
134
+ totalCount
135
+ nodes {
136
+ author { login }
137
+ body
138
+ }
139
+ }
140
+ }
141
+ }
142
+ comments(last: 20) {
143
+ totalCount
144
+ nodes {
145
+ author { login }
146
+ body
147
+ createdAt
148
+ }
149
+ }
150
+ closingIssuesReferences(first: 10) {
151
+ totalCount
152
+ nodes {
153
+ number
154
+ state
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ `,aq=e=>{let t=Array.from({length:e},(e,t)=>t);return`
161
+ query UsineIssuesPresent($owner: String!, $name: String!, ${t.map(e=>`$n${e}: Int!`).join(`, `)}) {
162
+ repository(owner: $owner, name: $name) {
163
+ ${t.map(e=>`i${e}: issue(number: $n${e}) { number }`).join(`
164
+ `)}
165
+ }
166
+ }
167
+ `},oq=5e3,sq=100,cq=10,lq=100,uq=50,dq=I(F({number:B.check(Yw(1)),updatedAt:jT,pullRequest:sw(pw)}).pipe(Sw({updatedAt:`updated_at`,pullRequest:`pull_request`}))),fq=I(F({name:TK,color:EK,description:R(P)})),pq=({name:e,color:t,description:n})=>new DK({name:e,color:t,description:wi(n)}),mq=F({repository:rT(F({issue:rT(YK)}))}),hq=F({repository:rT(F({pullRequest:rT($K)}))}),gq=R(F({number:B})),_q=e=>F({repository:rT(F(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,gq]))))}),vq=e=>bv(e),yq=e=>e.map(e=>e.pullRequest===void 0?new bK({number:e.number,updatedAt:e.updatedAt}):new xK({number:e.number,updatedAt:e.updatedAt})),bq=e=>{let t=e.flatMap(e=>E(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?S():vq(Math.max(...t))},xq=(e,t)=>bq([iK(e[`retry-after`],t),aK(e,sq)]),Sq=(e,t)=>bq([oK(e,t),iK(e[`retry-after`],t),aK(e,sq)]),Cq=e=>e===void 0?S():wi(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),wq=e=>{let t=Dv(e)-oq;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},Tq=(e,t)=>{let{name:n,owner:r}=vD(e),i=new URL(`${XG}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues`);return i.searchParams.set(`state`,`all`),i.searchParams.set(`sort`,`updated`),i.searchParams.set(`direction`,`asc`),i.searchParams.set(`per_page`,`100`),T(t.watermark)&&i.searchParams.set(`since`,wq(t.watermark.value)),i.toString()},Eq=e=>{let{name:t,owner:n}=vD(e),r=new URL(`${XG}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},Dq=(e,t)=>{let{name:n,owner:r}=vD(e),i=new URL(`${XG}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},Oq=(e,t)=>{let n=t.map(({updatedAt:e})=>Dv(e));return T(e.watermark)&&n.push(Dv(e.watermark.value)),n.length===0?S():vq(Math.max(...n))},kq=class e extends ro()(`@usine/github/GitHubPolling`){static layer=Op(e,O(function*(){let e=yield*_K,t=yield*DE,n=yield*DB,r=Aq(t),i=j(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(Ag(t=>$G(e,t)))}),a=j(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=Xz(t).pipe(QG(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*Lp;return a.status===200?{items:yq(yield*mB(dq)(a).pipe(Ag(e=>nK(`poll-repository-changes`,e.message)))),next:Cq(a.headers.link)}:yield*lK(`poll-repository-changes`,a,o)}),o=j(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=Xz(n).pipe(QG(r.value)),o=yield*i(t,a),s=yield*Lp;return o.status===200?{labels:(yield*mB(fq)(o).pipe(Ag(e=>nK(t,e.message)))).map(pq),next:Cq(o.headers.link)}:yield*lK(t,o,s)}),s=j(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;T(r)&&i<lq;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return T(r)?yield*nK(e,`the GitHub label list has more than ${lq} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=j(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=j(`GitHubPolling.labels`)(function*(t,n){yield*A({repository:t});let r=yield*e.installationToken(),a=Xz(Eq(t)).pipe(QG(r.value));T(n)&&(a=eB(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*Lp;if(o.status===304)return new AK;if(o.status!==200)return yield*lK(`list-repository-labels`,o,c);let l=yield*mB(fq)(o).pipe(Ag(e=>nK(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(pq),next:Cq(o.headers.link)}),d=QC(vK)(o.headers.etag);return w(d)&&(yield*h_(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new kK({entityTag:d,labels:u})}),u=j(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=Xz(Tq(t,n)).pipe(QG(r.value));T(n.entityTag)&&(o=eB(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*Lp,l=Sq(s.headers,c);if(s.status===304)return new CK({cursor:n,nextPollAt:l,backoffUntil:xq(s.headers,c)});if(s.status!==200)return yield*lK(`poll-repository-changes`,s,c);let u=yq(yield*mB(dq)(s).pipe(Ag(e=>nK(`poll-repository-changes`,e.message)))),d=QC(vK)(s.headers.etag);w(d)&&(yield*h_(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=Cq(s.headers.link),m=1;for(;T(p)&&m<cq;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=T(p);return h&&(yield*M(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new wK({cursor:new yK({entityTag:d,watermark:Oq(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:xq(s.headers,c)})}),d=j(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=vD(r);return yield*zK(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,snapshot:j(`GitHubPolling.snapshot`)((e,t)=>O(function*(){let n=t=>nK(t,`repository "${e}" is null: deleted, renamed, or no longer accessible`),i=(n,r)=>new YG({operation:n,item:t.number,message:`GitHub ${r} ${e}#${t.number} was not found. It was deleted or transferred, or the GitHub App can no longer read it.`}),a=j(`GitHubPolling.completeItemLabels`)(function*(n){if(n.labels.nodes.length>=n.labels.totalCount)return n.labels;yield*N(`Completing truncated Item label connection for Board matching`,{repository:e,item:t.number,listedLabels:n.labels.nodes.length,totalLabels:n.labels.totalCount});let r=yield*c(`fetch-item-labels`,Dq(e,t.number));return{totalCount:r.length,nodes:r.map(({name:e})=>({name:e}))}});if(t._tag===`ChangedIssue`){let o=yield*d(`fetch-issue-snapshot`,e,t.number,rq,mq);if(w(o.repository))return yield*n(`fetch-issue-snapshot`);let s=o.repository.value.issue;if(w(s))return yield*i(`fetch-issue-snapshot`,`issue`);let c={...s.value,labels:yield*a(s.value)};return new tq({payload:c,contentHash:yield*r(c)})}let o=yield*d(`fetch-pull-request-snapshot`,e,t.number,iq,hq);if(w(o.repository))return yield*n(`fetch-pull-request-snapshot`);let s=o.repository.value.pullRequest;if(w(s))return yield*i(`fetch-pull-request-snapshot`,`pull request`);let l={...s.value,labels:yield*a(s.value)};return new nq({payload:l,contentHash:yield*r(l)})})),missingIssues:j(`GitHubPolling.missingIssues`)(function*(t,r){yield*A({repository:t,issues:r.length});let{name:i,owner:a}=vD(t);return(yield*ng(Da(r,uq),r=>O(function*(){let o=yield*e.installationToken(),s=yield*zK(n,o,`find-missing-issues`,aq(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},_q(r.length));if(w(s.repository))return yield*nK(`find-missing-issues`,`repository "${t}" is null: deleted, renamed, or no longer accessible`);let c=s.repository.value;return r.filter((e,t)=>c[`i${t}`]===null)}))).flat()})}}))},Aq=e=>j(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(IK(t))),r=yield*e.digest(`SHA-256`,n).pipe(jg);return eq.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),jq=class extends H(`@usine/orchestrator/LabelPreflightFinding`)({repository:mD,label:iU,errorTag:V,message:V}){},Mq=(e,t)=>{let n=[];if(T(e.color)){let r=e.color.value.toLowerCase();E(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(T(e.description)){let r=e.description.value;E(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},Nq=e=>new jK({name:TK.make(e.name),color:Ai(e.color,EK.make),description:e.description}),Pq=class e extends ro()(`@usine/orchestrator/LabelReconciler`){static layer=Op(e,O(function*(){let e=yield*PK;return{reconcile:j(`LabelReconciler.reconcile`)(function*(t,n,r){yield*A({repository:t});let i=[...r],a=new Map(r.map(e=>[aU(e.name),e])),o=[],s=!1,c=S();for(let r of n){let n=a.get(aU(r.name));if(n!==void 0){let e=Mq(r,n);e.length>0?yield*h_(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*N(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*yg(e.create(t,Nq(r)));if(Wi(l)){let e=l.failure;if(o.push(new jq({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=C(e.retryAt),yield*h_(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:kv(e.retryAt)});break}yield*g_(`Declared GitHub label could not be created; trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message});continue}let u=new FL({name:l.success.name,color:C(l.success.color),description:l.success.description});i.push(u),a.set(aU(u.name),u),s=!0,yield*M(`Created declared GitHub label`,{repository:t,label:u.name})}return i.sort((e,t)=>e.name.localeCompare(t.name)),{labels:i,findings:o,catalogChanged:s,nextPollAt:c}})}}))},Fq=(e,t,n)=>{let r=`${t}---`,i=e.indexOf(r,n);for(;i>=0;){let n=i+r.length;if(n===e.length||e.startsWith(t,n))return i;i=e.indexOf(r,n)}return-1},Iq=(e,t)=>{let n=t.startsWith(`---\r
168
+ `)?`\r
169
+ `:t.startsWith(`---
170
+ `)?`
171
+ `:void 0;if(n===void 0)return new SO({file:e,stage:`frontmatter`,expression:S(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=Fq(t,n,r);if(a<0)return new SO({file:e,stage:`frontmatter`,expression:S(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return D({yaml:t.slice(r,a),body:t.slice(s),newline:n})},Lq=class extends U(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:mD,lane:dU,label:iU}){},Rq=class extends U(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:ZU.fields.name,label:iU}){};L([Lq,Rq]);var zq=ew(cO),Bq=(e,t)=>new pO({name:e,fields:t.map(([e,t,n])=>new fO({name:e,type:zq(t),nullable:n===`nullable`}))}),Vq=Bq(`Actor`,[[`login`,`string`]]),Hq=Bq(`Label`,[[`name`,`string`]]),Uq=Bq(`Milestone`,[[`title`,`string`]]),Wq=Bq(`IssueType`,[[`name`,`string`]]),Gq=Bq(`Commit`,[[`oid`,`string`]]),Kq=Bq(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),qq=Bq(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),Jq=Bq(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),Yq=Bq(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),Xq=Bq(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),Zq=Bq(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),Qq=Bq(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),$q=Bq(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),eJ=Bq(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),tJ=Bq(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),nJ=Bq(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),rJ=Bq(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),iJ=Bq(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),aJ=Bq(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),oJ=Bq(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),sJ=Bq(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),cJ=Bq(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),lJ=Bq(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),uJ=Bq(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),dJ=Bq(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),fJ=Bq(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),pJ=Bq(`StatusCheckRollup`,[[`state`,`string`]]),mJ=Bq(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),hJ=Bq(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),gJ=Bq(`SchedulePayload`,[[`tick`,`Tick`]]),_J=(e,t)=>new hO({types:[Kq,...e],variables:[new mO({name:`repo`,type:zq(`RepoContext`)}),new mO({name:`item`,type:zq(t)})]}),vJ=_J([Vq,Hq,Uq,Wq,qq,Jq,Yq,Xq,Zq,Qq,$q],`IssuePayload`),yJ=_J([Vq,Hq,Gq,qq,eJ,tJ,nJ,rJ,iJ,aJ,oJ,sJ,cJ,lJ,uJ,dJ,fJ,pJ,mJ],`PullRequestPayload`),bJ=_J([hJ,gJ],`SchedulePayload`),xJ=e=>{switch(e){case`issue`:return vJ;case`pr`:return yJ;case`schedule`:return bJ}},SJ=e=>{let{owner:t}=vD(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},CJ=Symbol.for(`yaml.alias`),wJ=Symbol.for(`yaml.document`),TJ=Symbol.for(`yaml.map`),EJ=Symbol.for(`yaml.pair`),DJ=Symbol.for(`yaml.scalar`),OJ=Symbol.for(`yaml.seq`),kJ=Symbol.for(`yaml.node.type`),AJ=e=>!!e&&typeof e==`object`&&e[kJ]===CJ,jJ=e=>!!e&&typeof e==`object`&&e[kJ]===wJ,MJ=e=>!!e&&typeof e==`object`&&e[kJ]===TJ,NJ=e=>!!e&&typeof e==`object`&&e[kJ]===EJ,PJ=e=>!!e&&typeof e==`object`&&e[kJ]===DJ,FJ=e=>!!e&&typeof e==`object`&&e[kJ]===OJ;function IJ(e){if(e&&typeof e==`object`)switch(e[kJ]){case TJ:case OJ:return!0}return!1}function LJ(e){if(e&&typeof e==`object`)switch(e[kJ]){case CJ:case TJ:case DJ:case OJ:return!0}return!1}var RJ=e=>(PJ(e)||IJ(e))&&!!e.anchor,zJ=Symbol(`break visit`),BJ=Symbol(`skip children`),VJ=Symbol(`remove node`);function HJ(e,t){let n=WJ(t);jJ(e)?UJ(null,e.contents,n,Object.freeze([e]))===VJ&&(e.contents=null):UJ(null,e,n,Object.freeze([]))}HJ.BREAK=zJ,HJ.SKIP=BJ,HJ.REMOVE=VJ;function UJ(e,t,n,r){let i=GJ(e,t,n,r);if(LJ(i)||NJ(i))return KJ(e,r,i),UJ(e,i,n,r);if(typeof i!=`symbol`){if(IJ(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=UJ(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===zJ)return zJ;else i===VJ&&(t.items.splice(e,1),--e)}}else if(NJ(t)){r=Object.freeze(r.concat(t));let e=UJ(`key`,t.key,n,r);if(e===zJ)return zJ;e===VJ&&(t.key=null);let i=UJ(`value`,t.value,n,r);if(i===zJ)return zJ;i===VJ&&(t.value=null)}}return i}function WJ(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function GJ(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(MJ(t))return n.Map?.(e,t,r);if(FJ(t))return n.Seq?.(e,t,r);if(NJ(t))return n.Pair?.(e,t,r);if(PJ(t))return n.Scalar?.(e,t,r);if(AJ(t))return n.Alias?.(e,t,r)}function KJ(e,t,n){let r=t[t.length-1];if(IJ(r))r.items[e]=n;else if(NJ(r))e===`key`?r.key=n:r.value=n;else if(jJ(r))r.contents=n;else{let e=AJ(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var qJ={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},JJ=e=>e.replace(/[!,[\]{}]/g,e=>qJ[e]),YJ=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+JJ(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&LJ(e.contents)){let t={};HJ(e.contents,(e,n)=>{LJ(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
172
+ `)}};YJ.defaultYaml={explicit:!1,version:`1.2`},YJ.defaultTags={"!!":`tag:yaml.org,2002:`};function XJ(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function ZJ(e){let t=new Set;return HJ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function QJ(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function $J(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=ZJ(e);let a=QJ(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(PJ(t.node)||IJ(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function eY(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=eY(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=eY(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=eY(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=eY(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function tY(e,t,n){if(Array.isArray(e))return e.map((e,t)=>tY(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!RJ(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var nY=class{constructor(e){Object.defineProperty(this,kJ,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!jJ(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=tY(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?eY(i,{"":o},``,o):o}},rY=class extends nY{constructor(e){super(CJ),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],HJ(e,{Node:(e,t)=>{(AJ(t)||RJ(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(tY(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=iY(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(XJ(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function iY(e,t,n){if(AJ(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(IJ(t)){let r=0;for(let i of t.items){let t=iY(e,i,n);t>r&&(r=t)}return r}if(NJ(t)){let r=iY(e,t.key,n),i=iY(e,t.value,n);return Math.max(r,i)}return 1}var aY=e=>!e||typeof e!=`function`&&typeof e!=`object`,oY=class extends nY{constructor(e){super(DJ),this.value=e}toJSON(e,t){return t?.keep?this.value:tY(this.value,e,t)}toString(){return String(this.value)}};oY.BLOCK_FOLDED=`BLOCK_FOLDED`,oY.BLOCK_LITERAL=`BLOCK_LITERAL`,oY.PLAIN=`PLAIN`,oY.QUOTE_DOUBLE=`QUOTE_DOUBLE`,oY.QUOTE_SINGLE=`QUOTE_SINGLE`;var sY=`tag:yaml.org,2002:`;function cY(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function lY(e,t,n){if(jJ(e)&&(e=e.contents),LJ(e))return e;if(NJ(e)){let t=n.schema[TJ].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new rY(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=sY+t.slice(2));let l=cY(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new oY(e);return c&&(c.node=t),t}l=e instanceof Map?o[TJ]:Symbol.iterator in Object(e)?o[OJ]:o[TJ]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new oY(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function uY(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return lY(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var dY=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,fY=class extends nY{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>LJ(t)||NJ(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(dY(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(IJ(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,uY(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(IJ(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&PJ(i)?i.value:i:IJ(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!NJ(t))return!1;let n=t.value;return n==null||e&&PJ(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return IJ(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(IJ(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,uY(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},pY=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function mY(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var hY=(e,t,n)=>e.endsWith(`
173
+ `)?mY(n,t):n.includes(`
174
+ `)?`
175
+ `+mY(n,t):(e.endsWith(` `)?``:` `)+n,gY=`flow`,_Y=`block`,vY=`quoted`;function yY(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=bY(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
176
+ `)n===`block`&&(h=bY(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
177
+ `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
178
+ `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function bY(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
179
+ `);r=t,i=t+1,a=e[i]}return r}var xY=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),SY=e=>/^(%|---|\.\.\.)/m.test(e);function CY(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
180
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function wY(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(SY(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
181
+
182
+ `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
183
+ `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:yY(o,a,vY,xY(t,!1))}function TY(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
184
+ `)||/[ \t]\n|\n[ \t]/.test(e))return wY(e,t);let n=t.indent||(SY(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:yY(r,n,gY,xY(t,!1))}function EY(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=wY;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?TY:i&&!t?wY:n?TY:wY}return r(e,t)}var DY;try{DY=RegExp(`(^|(?<!
185
+ ))
186
+ +(?!
187
+ |$)`,`g`)}catch{DY=/\n+(?!\n|$)/g}function OY({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return EY(n,r);let l=r.indent||(r.forceBlockIndent||SY(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===oY.BLOCK_FOLDED?!1:t===oY.BLOCK_LITERAL||!CY(n,c,l.length);if(!n)return u?`|
188
+ `:`>
189
+ `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
190
+ `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
191
+ `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
192
+ `&&(p=p.slice(0,-1)),p.replace(DY,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
193
+ `)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let y=(h?l?`2`:`1`:``)+d;if(e&&(y+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
194
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=xY(r,!0);o!==`folded`&&t!==oY.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=yY(`${v}${e}${p}`,l,_Y,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function kY(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
195
+ `)||u&&/[[\]{},]/.test(a))return EY(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
196
+ `)?EY(a,t):OY(e,t,n,r);if(!s&&!u&&i!==oY.PLAIN&&a.includes(`
197
+ `))return OY(e,t,n,r);if(SY(a)){if(c===``)return t.forceBlockIndent=!0,OY(e,t,n,r);if(s&&c===l)return EY(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return EY(a,t)}return s?d:yY(d,c,gY,xY(t,!1))}function AY(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==oY.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=oY.QUOTE_DOUBLE);let c=e=>{switch(e){case oY.BLOCK_FOLDED:case oY.BLOCK_LITERAL:return i||a?EY(o.value,t):OY(o,t,n,r);case oY.QUOTE_DOUBLE:return wY(o.value,t);case oY.QUOTE_SINGLE:return TY(o.value,t);case oY.PLAIN:return kY(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function jY(e,t){let n=Object.assign({blockQuote:!0,commentString:pY,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function MY(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(PJ(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function NY(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(PJ(e)||IJ(e))&&e.anchor;a&&XJ(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function PY(e,t,n,r){if(NJ(e))return e.toString(t,n,r);if(AJ(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=LJ(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=MY(t.doc.schema.tags,a);let o=NY(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):PJ(a)?AY(a,t,n,r):a.toString(t,n,r);return o?PJ(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function FY({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=LJ(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(IJ(e)||!LJ(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||IJ(e)||(PJ(e)?e.type===oY.BLOCK_FOLDED||e.type===oY.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=PY(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=hY(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=hY(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=hY(g,n.indent,l(f))));let _,v,y;LJ(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&PJ(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&FJ(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let ee=!1,b=PY(t,n,()=>ee=!0,()=>h=!0),te=` `;if(f||_||v){if(te=_?`
198
+ `:``,v){let e=l(v);te+=`\n${mY(e,n.indent)}`}b===``&&!n.inFlow?te===`
199
+ `&&y&&(te=`
200
+
201
+ `):te+=`\n${n.indent}`}else if(!p&&IJ(t)){let e=b[0],r=b.indexOf(`
202
+ `),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=b.indexOf(` `);e===`&`&&n!==-1&&n<r&&b[n+1]===`!`&&(n=b.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(te=`\n${n.indent}`)}}else(b===``||b[0]===`
203
+ `)&&(te=``);return g+=te+b,n.inFlow?ee&&r&&r():y&&!ee?g+=hY(g,n.indent,l(y)):h&&i&&i(),g}function IY(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var LY=`<<`,RY={identify:e=>e===LY||typeof e==`symbol`&&e.description===LY,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new oY(Symbol(LY)),{addToJSMap:BY}),stringify:()=>LY},zY=(e,t)=>(RY.identify(t)||PJ(t)&&(!t.type||t.type===oY.PLAIN)&&RY.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===RY.tag&&e.default);function BY(e,t,n){let r=HY(e,n);if(FJ(r))for(let n of r.items)VY(e,t,n);else if(Array.isArray(r))for(let n of r)VY(e,t,n);else VY(e,t,r)}function VY(e,t,n){let r=HY(e,n);if(!MJ(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function HY(e,t){return e&&AJ(t)?t.resolve(e.doc,e):t}function UY(e,t,{key:n,value:r}){if(LJ(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(zY(e,n))BY(e,t,r);else{let i=tY(n,``,e);if(t instanceof Map)t.set(i,tY(r,i,e));else if(t instanceof Set)t.add(i);else{let a=WY(n,i,e),o=tY(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function WY(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(LJ(e)&&n?.doc){let t=jY(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),IY(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function GY(e,t,n){return new KY(lY(e,void 0,n),lY(t,void 0,n))}var KY=class e{constructor(e,t=null){Object.defineProperty(this,kJ,{value:EJ}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return LJ(n)&&(n=n.clone(t)),LJ(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return UY(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?FY(this,e,t,n):JSON.stringify(this)}};function qY(e,t,n){return(t.inFlow??e.flow?YY:JY)(e,t,n)}function JY({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(LJ(i))!d&&i.spaceBefore&&f.push(``),XY(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(NJ(i)){let e=LJ(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),XY(n,f,e.commentBefore,d))}d=!1;let s=PY(i,u,()=>o=null,()=>d=!0);o&&(s+=hY(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
204
+ `}}return e?(p+=`
205
+ `+mY(l(e),c),s&&s()):d&&o&&o(),p}function YY({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(LJ(i))i.spaceBefore&&d.push(``),XY(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(NJ(i)){let e=LJ(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),XY(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=LJ(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=PY(i,c,()=>a=null);l||=d.length>u||o.includes(`
206
+ `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=hY(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
207
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function XY({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=mY(t(r),e);n.push(i.trimStart())}}function ZY(e,t){let n=PJ(t)?t.value:t;for(let r of e)if(NJ(r)&&(r.key===t||r.key===n||PJ(r.key)&&r.key.value===n))return r}var QY=class extends fY{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(TJ,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(GY(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=NJ(e)?e:!e||typeof e!=`object`||!(`key`in e)?new KY(e,e?.value):new KY(e.key,e.value);let r=ZY(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);PJ(r.value)&&aY(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=ZY(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=ZY(this.items,e)?.value;return(!t&&PJ(n)?n.value:n)??void 0}has(e){return!!ZY(this.items,e)}set(e,t){this.add(new KY(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)UY(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!NJ(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),qY(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},$Y={collection:`map`,default:!0,nodeClass:QY,tag:`tag:yaml.org,2002:map`,resolve(e,t){return MJ(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>QY.from(e,t,n)},eX=class extends fY{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(OJ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=tX(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=tX(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&PJ(r)?r.value:r}has(e){let t=tX(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=tX(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];PJ(r)&&aY(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(tY(e,String(r++),t));return n}toString(e,t,n){return e?qY(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(lY(a,void 0,n))}}return i}};function tX(e){let t=PJ(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var nX={collection:`seq`,default:!0,nodeClass:eX,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return FJ(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>eX.from(e,t,n)},rX={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),AY(e,t,n,r)}},iX={identify:e=>e==null,createNode:()=>new oY(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new oY(null),stringify:({source:e},t)=>typeof e==`string`&&iX.test.test(e)?e:t.options.nullStr},aX={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new oY(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&aX.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function oX({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var sX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:oX},cX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():oX(e)}},lX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new oY(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:oX},uX=e=>typeof e==`bigint`||Number.isInteger(e),dX=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function fX(e,t,n){let{value:r}=e;return uX(r)&&r>=0?n+r.toString(t):oX(e)}var pX={identify:e=>uX(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>dX(e,2,8,n),stringify:e=>fX(e,8,`0o`)},mX={identify:uX,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>dX(e,0,10,n),stringify:oX},hX={identify:e=>uX(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>dX(e,2,16,n),stringify:e=>fX(e,16,`0x`)},gX=[$Y,nX,rX,iX,aX,pX,mX,hX,sX,cX,lX];function _X(e){return typeof e==`bigint`||Number.isInteger(e)}var vX=({value:e})=>JSON.stringify(e),yX=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:vX},{identify:e=>e==null,createNode:()=>new oY(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:vX},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:vX},{identify:_X,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>_X(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:vX}],bX=[$Y,nX].concat(yX,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),xX={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=oY.BLOCK_LITERAL,t!==oY.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===oY.BLOCK_LITERAL?`
208
+ `:` `)}return AY({comment:e,type:t,value:s},r,i,a)}};function SX(e,t){if(FJ(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!NJ(r)){if(MJ(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new KY(new oY(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=NJ(r)?r:new KY(r)}}else t(`Expected a sequence for this tag`);return e}function CX(e,t,n){let{replacer:r}=n,i=new eX(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(GY(o,s,n))}return i}var wX={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:SX,createNode:CX},TX=class e extends eX{constructor(){super(),this.add=QY.prototype.add.bind(this),this.delete=QY.prototype.delete.bind(this),this.get=QY.prototype.get.bind(this),this.has=QY.prototype.has.bind(this),this.set=QY.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(NJ(e)?(r=tY(e.key,``,t),i=tY(e.value,r,t)):r=tY(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=CX(e,t,n),i=new this;return i.items=r.items,i}};TX.tag=`tag:yaml.org,2002:omap`;var EX={collection:`seq`,identify:e=>e instanceof Map,nodeClass:TX,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=SX(e,t),r=[];for(let{key:e}of n.items)PJ(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new TX,n)},createNode:(e,t,n)=>TX.from(e,t,n)};function DX({value:e,source:t},n){return t&&(e?OX:kX).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var OX={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new oY(!0),stringify:DX},kX={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new oY(!1),stringify:DX},AX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:oX},jX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():oX(e)}},MX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new oY(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:oX},NX=e=>typeof e==`bigint`||Number.isInteger(e);function PX(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function FX(e,t,n){let{value:r}=e;if(NX(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return oX(e)}var IX={identify:NX,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>PX(e,2,2,n),stringify:e=>FX(e,2,`0b`)},LX={identify:NX,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>PX(e,1,8,n),stringify:e=>FX(e,8,`0`)},RX={identify:NX,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>PX(e,0,10,n),stringify:oX},zX={identify:NX,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>PX(e,2,16,n),stringify:e=>FX(e,16,`0x`)},BX=class e extends QY{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=NJ(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new KY(e.key,null):new KY(e,null),ZY(this.items,t.key)||this.items.push(t)}get(e,t){let n=ZY(this.items,e);return!t&&NJ(n)?PJ(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=ZY(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new KY(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(GY(e,null,n));return i}};BX.tag=`tag:yaml.org,2002:set`;var VX={collection:`map`,identify:e=>e instanceof Set,nodeClass:BX,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>BX.from(e,t,n),resolve(e,t){if(MJ(e)){if(e.hasAllNullValues(!0))return Object.assign(new BX,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function HX(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function UX(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return oX(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var WX={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>HX(e,n),stringify:UX},GX={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>HX(e,!1),stringify:UX},KX={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(KX.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=HX(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``},qX=[$Y,nX,rX,iX,OX,kX,IX,LX,RX,zX,AX,jX,MX,xX,RY,EX,wX,VX,WX,GX,KX],JX=new Map([[`core`,gX],[`failsafe`,[$Y,nX,rX]],[`json`,bX],[`yaml11`,qX],[`yaml-1.1`,qX]]),YX={binary:xX,bool:aX,float:lX,floatExp:cX,floatNaN:sX,floatTime:GX,int:mX,intHex:hX,intOct:pX,intTime:WX,map:$Y,merge:RY,null:iX,omap:EX,pairs:wX,seq:nX,set:VX,timestamp:KX},XX={"tag:yaml.org,2002:binary":xX,"tag:yaml.org,2002:merge":RY,"tag:yaml.org,2002:omap":EX,"tag:yaml.org,2002:pairs":wX,"tag:yaml.org,2002:set":VX,"tag:yaml.org,2002:timestamp":KX};function ZX(e,t,n){let r=JX.get(t);if(r&&!e)return n&&!r.includes(RY)?r.concat(RY):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(JX.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(RY)),i.reduce((e,t)=>{let n=typeof t==`string`?YX[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(YX).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var QX=(e,t)=>e.key<t.key?-1:+(e.key>t.key),$X=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?ZX(e,`compat`):e?ZX(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?XX:{},this.tags=ZX(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,TJ,{value:$Y}),Object.defineProperty(this,DJ,{value:rX}),Object.defineProperty(this,OJ,{value:nX}),this.sortMapEntries=typeof a==`function`?a:a===!0?QX:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function eZ(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=jY(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(mY(t,``))}let o=!1,s=null;if(e.contents){if(LJ(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(mY(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=PY(e.contents,i,()=>s=null,t);s&&(c+=hY(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(PY(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
209
+ `)?(n.push(`...`),n.push(mY(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(mY(a(t),``)))}return n.join(`
210
+ `)+`
211
+ `}var tZ=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kJ,{value:wJ});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new YJ({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[kJ]:{value:wJ}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=LJ(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){nZ(this.contents)&&this.contents.add(e)}addIn(e,t){nZ(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=ZJ(this);e.anchor=!t||n.has(t)?QJ(t||`a`,n):t}return new rY(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=$J(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=lY(e,l,p);return o&&IJ(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new KY(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return nZ(this.contents)?this.contents.delete(e):!1}deleteIn(e){return dY(e)?this.contents!=null&&(this.contents=null,!0):nZ(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return IJ(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return dY(e)?!t&&PJ(this.contents)?this.contents.value:this.contents:IJ(this.contents)?this.contents.getIn(e,t):void 0}has(e){return IJ(this.contents)?this.contents.has(e):!1}hasIn(e){return dY(e)?this.contents!==void 0:IJ(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=uY(this.schema,[e],t):nZ(this.contents)&&this.contents.set(e,t)}setIn(e,t){dY(e)?this.contents=t:this.contents==null?this.contents=uY(this.schema,Array.from(e),t):nZ(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new YJ({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new YJ({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new $X(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=tY(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?eY(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return eZ(this,e)}};function nZ(e){if(IJ(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var rZ=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},iZ=class extends rZ{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},aZ=class extends rZ{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},oZ=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
212
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function sZ(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,ee=null,b=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!ee||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,b??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,b??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),ee=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let te=e[e.length-1],ne=te?te.offset+te.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:ee,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ne,start:b??ne}}function cZ(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
213
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(cZ(t.key)||cZ(t.value))return!0}return!1;default:return!0}}function lZ(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&cZ(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function uZ(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||PJ(e)&&PJ(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var dZ=`All mapping items must start at the same column`;function fZ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??QY)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=sZ(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,dZ)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
214
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||cZ(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,dZ);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&lZ(r.indent,u,i),n.atKey=!1,uZ(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=sZ(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&lZ(r.indent,f,i),s=c.range[2];let l=new KY(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
215
+ `+_.comment:g.comment=_.comment);let e=new KY(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function pZ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??eX)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=sZ(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&lZ(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function mZ(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var hZ=`Block collections are not allowed within flow collections`,gZ=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function _Z({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?QY:eX))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=sZ(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
216
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&cZ(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];NJ(t)&&(t=t.value??t.key),t.comment?t.comment+=`
217
+ `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],gZ(m)&&i(r.range,`BLOCK_IN_FLOW`,hZ)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);gZ(f)&&i(g.range,`BLOCK_IN_FLOW`,hZ),n.atKey=!1;let _=sZ(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?gZ(m)&&i(v.range,`BLOCK_IN_FLOW`,hZ):_.comment&&(g.comment?g.comment+=`
218
+ `+_.comment:g.comment=_.comment);let y=new KY(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;uZ(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new QY(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=mZ(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
219
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function vZ(e,t,n,r,i,a){let o=n.type===`block-map`?fZ(e,t,n,r,a):n.type===`block-seq`?pZ(e,t,n,r,a):_Z(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function yZ(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===QY.tagName&&s===`map`||o===eX.tagName&&s===`seq`)return vZ(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),vZ(e,t,n,i,o)}let l=vZ(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=LJ(u)?u:new oY(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function bZ(e,t,n){let r=t.offset,i=xZ(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?oY.BLOCK_FOLDED:oY.BLOCK_LITERAL,o=t.source?SZ(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
220
+ `.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
221
+ `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===oY.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
222
+ `):t.length>c||r[0]===` `?(f===` `?f=`
223
+ `:!p&&f===`
224
+ `&&(f=`
225
+
226
+ `),d+=f+t.slice(c)+r,f=`
227
+ `,p=!0):r===``?f===`
228
+ `?d+=`
229
+ `:f=`
230
+ `:(d+=f+r,f=` `,p=!1)}switch(i.chomp){case`-`:break;case`+`:for(let e=s;e<o.length;++e)d+=`
231
+ `+o[e][0].slice(c);d[d.length-1]!==`
232
+ `&&(d+=`
233
+ `);break;default:d+=`
234
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function xZ({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function SZ(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function CZ(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=oY.PLAIN,c=wZ(a,l);break;case`single-quoted-scalar`:s=oY.QUOTE_SINGLE,c=TZ(a,l);break;case`double-quoted-scalar`:s=oY.QUOTE_DOUBLE,c=DZ(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=mZ(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function wZ(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),EZ(e)}function TZ(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),EZ(e.slice(1,-1)).replace(/''/g,`'`)}function EZ(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
235
+ `?a+=o:o=`
236
+ `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function DZ(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
237
+ `){if(i===`
238
+ `){let{fold:t,offset:i}=OZ(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=kZ[i];if(a)n+=a;else if(i===`
239
+ `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
240
+ `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=AZ(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
241
+ `&&(a!==`\r`||e[r+2]!==`
242
+ `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function OZ(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
243
+ `||r===`\r`)&&(r!==`\r`||e[t+2]===`
244
+ `);)r===`
245
+ `&&(n+=`
246
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var kZ={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
247
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function AZ(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function jZ(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?bZ(e,t,r):CZ(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[DJ]:c?MZ(e.schema,i,c,n,r):t.type===`scalar`?NZ(e,i,t,r):e.schema[DJ];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=PJ(a)?a:new oY(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new oY(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function MZ(e,t,n,r,i){if(n===`!`)return e[DJ];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[DJ])}function NZ({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[DJ];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[DJ];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function PZ(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var FZ={composeNode:IZ,composeEmptyNode:LZ};function IZ(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=RZ(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=jZ(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=yZ(FZ,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=LZ(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!PJ(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function LZ(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=jZ(e,{type:`scalar`,offset:PZ(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function RZ({options:e},{offset:t,source:n,end:r},i){let a=new rY(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=mZ(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function zZ(e,t,{offset:n,start:r,value:i,end:a},o){let s=new tZ(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=sZ(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?IZ(c,i,l,o):LZ(c,l.end,r,null,l,o);let u=s.contents.range[2],d=mZ(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function BZ(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function VZ(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
248
+
249
+ `:`
250
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var HZ=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=BZ(e);r?this.warnings.push(new aZ(i,t,n)):this.errors.push(new iZ(i,t,n))},this.directives=new YJ({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=VZ(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(IJ(i)&&!i.flow&&i.items.length>0){let e=i.items[0];NJ(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:VZ(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=BZ(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=zZ(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new iZ(BZ(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new iZ(BZ(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=mZ(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new iZ(BZ(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new tZ(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},UZ=Symbol(`break visit`),WZ=Symbol(`skip children`),GZ=Symbol(`remove item`);function KZ(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),qZ(Object.freeze([]),e,t)}KZ.BREAK=UZ,KZ.SKIP=WZ,KZ.REMOVE=GZ,KZ.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},KZ.parentCollection=(e,t)=>{let n=KZ.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function qZ(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=qZ(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===UZ)return UZ;else r===GZ&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function JZ(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
251
+ `:case`\r
252
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function YZ(e){switch(e){case void 0:case` `:case`
253
+ `:case`\r`:case` `:return!0;default:return!1}}var XZ=new Set(`0123456789ABCDEFabcdef`),ZZ=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),QZ=new Set(`,[]{}`),$Z=new Set(` ,[]{}
254
+ \r `),eQ=e=>!e||$Z.has(e),tQ=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
255
+ `||t===`\r`&&this.buffer[e+1]===`
256
+ `}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
257
+ `||!t&&!this.atEnd)return e+n+1}return t===`
258
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&YZ(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
259
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&YZ(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!YZ(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&YZ(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(eQ),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&YZ(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(eQ),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||YZ(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
260
+ `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
261
+ `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>YZ(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
262
+ `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
263
+ `)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
264
+ `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
265
+ `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
266
+ `&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(YZ(r)||e&&QZ.has(r))break;t=n}else if(YZ(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
267
+ `?(n+=1,r=`
268
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&QZ.has(i))break;if(r===`
269
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&QZ.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(eQ),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(YZ(n)||t&&QZ.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!YZ(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(ZZ.has(t))t=this.buffer[++e];else if(t===`%`&&XZ.has(this.buffer[e+1])&&XZ.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
270
+ `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
271
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},nQ=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function rQ(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function iQ(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function aQ(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function oQ(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function sQ(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function cQ(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function lQ(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!rQ(t.start,`explicit-key-ind`)&&!rQ(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,aQ(t.value)?t.value.end?cQ(t.value.end,t.sep):t.value.end=t.sep:cQ(t.start,t.sep),delete t.sep)}var uQ=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new tQ,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=JZ(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&lQ(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&iQ(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:iQ(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=sQ(oQ(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
272
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
273
+ `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){cQ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(rQ(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=sQ(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(rQ(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(aQ(t.key)&&!rQ(t.sep,`newline`)){let e=sQ(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):rQ(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!rQ(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){cQ(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||rQ(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=sQ(oQ(t));lQ(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
274
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
275
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=sQ(oQ(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=sQ(oQ(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function dQ(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new nQ||null,prettyErrors:t}}function fQ(e,t={}){let{lineCounter:n,prettyErrors:r}=dQ(t),i=new uQ(n?.addNewLine),a=new HZ(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new iZ(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(oZ(e,n)),o.warnings.forEach(oZ(e,n))),o}var pQ=e=>E(QC(F({message:V}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),mQ=(e,t)=>O(function*(){let n=yield*mg({try:()=>fQ(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new SO({file:e,stage:`yaml`,expression:S(),message:pQ(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new SO({file:e,stage:`yaml`,expression:S(),message:r.message})}),hQ=cv(),gQ=L([P,_w]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(Aw(gO,{decode:Rv(e=>String(e)),encode:Rv(e=>e)})),_Q=L([WU.mapFields(TC({if:gQ})).pipe(Aw(WU)),GU.mapFields(TC({if:gQ})).pipe(Aw(GU)),KU.mapFields(TC({if:gQ})).pipe(Aw(KU))]),vQ=class extends H(`@usine/config/LoopFrontmatter`)({trigger:_Q,selector:iT(BU),approval:TD.pipe(Pw(D(`none`))),step:RO.pipe(Pw(D(`run`))),agent:DO,maxCycles:ZU.fields.maxCycles,permissions:ZU.fields.permissions}){}.pipe(Sw({maxCycles:`max_cycles`})),yQ=class extends H(`@usine/config/AgentFrontmatter`)({harness:wO,model:CO,effort:TO,parentModel:iT(CO),parentEffort:iT(TO)}){}.pipe(Sw({parentModel:`parent_model`,parentEffort:`parent_effort`})),bQ=(e,t)=>new SO({file:e,stage:`schema`,expression:S(),message:hQ(t.issue)}),xQ=qC(tE),SQ=(e,t)=>O(function*(){return yield*xQ((yield*mQ(e,t)).toJS()).pipe(Ag(t=>new SO({file:e,stage:`yaml`,expression:S(),message:hQ(t.issue)})))}),CQ=(e,t)=>new SO({file:e,stage:`expression`,expression:C(t.source),message:t.message}),wQ=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?D(t.slice(0,-3)):new SO({file:e,stage:`schema`,expression:S(),message:`Expected a .md filename`})},TQ=e=>wQ(e).pipe(k(t=>qC(ZU.fields.name)(t).pipe(Ag(t=>bQ(e,t))))),EQ=e=>wQ(e).pipe(k(t=>qC(DO)(t).pipe(Ag(t=>bQ(e,t))))),DQ=(e,t)=>O(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new SO({file:e,stage:`expression`,expression:S(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*qC(gO)(o).pipe(Ag(t=>bQ(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),OQ=(e,t,n)=>{let r=$U(t.name),i=xJ(t.trigger.on);return O(function*(){let a=yield*ng(yield*DQ(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(Ag(e=>CQ(r,e)),xg(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},kQ=j(`ConfigParser.parseUsineYaml`)((e,t)=>O(function*(){let n=yield*SQ(e,t);return yield*qC(zU)(n,{onExcessProperty:`error`}).pipe(Ag(t=>bQ(e,t)))})),AQ=j(`ConfigParser.parseAgentFile`)((e,t)=>O(function*(){let n=yield*EQ(e),r=yield*Iq(e,t),i=yield*SQ(e,r.yaml),a=yield*qC(yQ)(i,{onExcessProperty:`error`}).pipe(Ag(t=>bQ(e,t))),o=yield*qC(OO)(r.body).pipe(Ag(t=>bQ(e,t)));return new nU({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),jQ=e=>j(`ConfigParser.parseLoopFile`)((t,n)=>O(function*(){let r=yield*TQ(t),i=yield*Iq(t,n),a=yield*SQ(t,i.yaml),o=yield*qC(vQ)(a,{onExcessProperty:`error`}).pipe(Ag(e=>bQ(t,e))),s=yield*qC(XU)(i.body).pipe(Ag(e=>bQ(t,e))),c=xJ(o.trigger.on);return yield*e.checkBoolean(o.trigger.if,c).pipe(Ag(e=>CQ(t,e))),yield*ng(yield*DQ(t,s),({source:n})=>e.checkScalar(n,c).pipe(Ag(e=>CQ(t,e))),{discard:!0}),new ZU({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,step:o.step,agent:o.agent,body:s})})),MQ=QC(iU),NQ=e=>j(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>aU(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(aU(n.label))&&i.push(new Lq({repository:e.name,lane:t.name,label:n.label}));for(let t of n){let n=yield*e.relatedStringLiterals(t.trigger.if,[`item`,`labels`]);for(let e of n){let n=MQ(e);T(n)&&!r.has(aU(n.value))&&i.push(new Rq({loop:t.name,label:n.value}))}}return i}),PQ=class e extends ro()(`@usine/config/ConfigParser`){static layer=Op(e,O(function*(){let e=yield*yO;return{configWarnings:NQ(e),parseUsineYaml:kQ,parseAgentFile:AQ,parseLoopFile:jQ(e),renderPrompt:j(`ConfigParser.renderPrompt`)((t,n)=>OQ(e,t,n))}}))},FQ=(e,t)=>e.changes.pipe(_E(e=>e!==t),SE,k(E({onNone:()=>lg,onSome:e=>D(e)}))),IQ=hD.make(`HEAD`),LQ=class extends BT(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:CD,agent:DO,message:V}){},RQ=j(`TriggerRouting.resolveLoop`)(function*(e,t){yield*A({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new LQ({loop:t.name,agent:t.agent,message:`Loop "${t.name}" references agent "${t.agent}", which is not in the roster`});let r=n.agent;return{agent:r,loop:t,parentModel:AO(r,e.config.settings.parentModel)}}),zQ=j(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*yg(RQ(e,n));Gi(r)?t.push(r.success):yield*g_(`Loaded loop lost its rostered Agent; skipping the loop`,{loop:r.failure.loop,agent:r.failure.agent,errorTag:r.failure._tag,message:r.failure.message})}return t}),BQ=e=>e.trigger.on===`schedule`?S():C(e.maxCycles),VQ=e=>new rj({event:new SD({id:bD.make(e.dedupKey),dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),itemKey:e.itemKey,cycleGeneration:e.cycleGeneration,loop:e.loop.name,step:e.loop.step,approval:e.loop.approval,permissions:e.loop.permissions,cycleLimit:BQ(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),HQ=e=>$E(e,{Claimed:({runId:e})=>({runId:e}),Queued:()=>({}),Suppressed:({runId:e})=>({suppressedBy:e}),Ignored:({reason:e})=>({reason:e}),CycleBlocked:({ask:e})=>({askId:e.id,reason:`cycle-budget-exhausted`})}),UQ=e=>E(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),WQ=class extends H(`@usine/orchestrator/RepositoryPollFailure`)({repository:mD,errorTag:V,message:P}){},GQ=class extends H(`@usine/orchestrator/RepositoryPoll`)({repository:mD,completedAt:AT}){},KQ=class extends H(`@usine/orchestrator/PollCycle`)({repositoryPolls:I(GQ).pipe(Mw(D([]))),repositories:B.check(Yw(0)),changedItems:B.check(Yw(0)),submissions:I(mj),revokedRuns:B.check(Yw(0)),failures:I(WQ),preflightFindings:I(jq),nextPollAt:nT(AT)}){},qQ=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...UQ(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},JQ=e=>{let t=e.flatMap(e=>E(e,{onNone:()=>[],onSome:e=>[Dv(e)]}));return t.length===0?S():bv(Math.max(...t))},YQ=class extends H(`@usine/orchestrator/LoopEvaluationFailure`)({loop:CD,stage:Ow([`if`,`prompt`]),expression:rT(gO),errorTag:V,message:P}){},XQ=class extends H(`@usine/orchestrator/FailingItem`)({stream:Ow([`issue`,`pr`]),number:oA,updatedAt:jT,contentHash:xL,failures:Ew(YQ)}){},ZQ=e=>e.stream===`issue`?new bK({number:e.number,updatedAt:e.updatedAt}):new xK({number:e.number,updatedAt:e.updatedAt}),QQ=(e,t,n)=>{let[r,...i]=n;return r===void 0?S():C(new XQ({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:oA.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},$Q=e=>e.stage===`if`?`if:`:E(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),e$=(e,t)=>t.failures.map(n=>new WQ({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${$Q(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),t$=e=>E(e,{onNone:()=>[],onSome:({failures:e})=>e}),n$=(e,t)=>e.loop===t.loop&&e.stage===t.stage,r$=j(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*A({repository:e,item:t});for(let i of Pi(r)){let r=E(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:Di(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>n$(e,n))?yield*N(`Loop evaluation still fails on unchanged Item content`,a):yield*g_(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=t$(r);for(let r of t$(n))i.some(e=>n$(e,r))||(yield*M(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),i$=lw(aA).pipe(Aw(TT(Tw([dw(`github`),mD,oA])))),a$=iw(i$),o$=(e,t)=>a$([`github`,mD.make(yD(e)),oA.make(t)]),s$={labels:[],findings:[],catalogChanged:!1,nextPollAt:S()},c$=j(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*A({repository:e});let r=yield*JL,i=yield*YL,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:S(),failures:[],nextPollAt:S()};if(Wi(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*h_(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:kv(t.retryAt)}),{...a,nextPollAt:C(t.retryAt)}):(yield*g_(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...qQ(t)}),{...a,failures:[new WQ({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof kK)){let t=yield*r.get(e);return w(t)?(yield*h_(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:S(),entityTagChanged:!0}):(yield*N(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:C(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new FL({name:e,color:C(t),description:n}));return yield*i.replace(new RL({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:C(s)}}),l$=j(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*A({repository:e});let r=yield*kq,i=yield*Pq,a=yield*YL,o=yield*c$(e,n,yield*yg(r.labels(e,n))),s=yield*E(o.confirmedLabels,{onNone:()=>D(s$),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?S():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:JQ([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new RL({repository:e,labels:s.labels})).pipe(Ag(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),u$=j(`PollingTriggers.observeItem`)(function*(e,t){yield*A({repository:e,item:t.number});let n=yield*kq,r=yield*ML,i=yield*oR,a=o$(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new SL({itemKey:a,repository:e,source:bL.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:oA.make(t.number),contentHash:xL.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*N(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{projection:c,cycleGeneration:o}}),d$=j(`PollingTriggers.markItemGone`)(function*(e,t){return yield*A({repository:e,item:t}),yield*(yield*ML).markGone(o$(e,t),yield*xv)}),f$=(e,t,{projection:n,cycleGeneration:r})=>xD.make(JSON.stringify([e.name,yD(t.name),n.number,n.contentHash,...r===0?[]:[r]])),p$=(e,t,n)=>O(function*(){return yield*(yield*yO).evaluateBoolean(e.trigger.if,xJ(e.trigger.on),{repo:SJ(t),item:n})}),m$=(e,t,n)=>O(function*(){let r=yield*yO,i=SJ(t);return yield*r.evaluateBooleanEach(e.trigger.if,xJ(e.trigger.on),n.map(e=>({repo:i,item:e})))}),h$=j(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*A({repository:e.name,item:r.number});let a=yield*PQ,o=yield*DR,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:SJ(e),item:c};if(s.length===0)return yield*N(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?hD.make(yield*qC(gD)(c.headRefOid).pipe(Ag(()=>new JG({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):IQ,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*A({loop:m.name,agent:t.name});let s=yield*yg(p$(m,e,c));if(Wi(s)){f.push(new YQ({loop:m.name,stage:`if`,expression:C(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*N(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*M(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=f$(m,e,n),_=yield*xv,v=yield*yg(a.renderPrompt(m,l));if(Wi(v)){f.push(new YQ({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let y=yield*o.submit(VQ({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:Jk.make(v.success),agent:t,parentModel:h}));yield*M(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:y._tag,...HQ(y)}),u.push(y)}return{submissions:u,revokedRuns:p,failures:f}}),g$=j(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*A({repository:e.name,item:r});let i=yield*DR,a=o$(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*M(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),_$=O(function*(){let e=new Set,t=yield*_S({capacity:128,strategy:`dropping`}),n=yield*nD(0),r=({repository:e,item:t})=>`${yD(e)}:${t.number}`,i=e=>E(e,{onNone:()=>cg,onSome:e=>oD(n,t=>Math.max(t,Dv(e)))});return{offer:j(`PollingTriggers.hint`)(function*(n,a,o=S()){yield*A({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*N(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*vS(t,s))?yield*N(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*h_(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},n_),take:r_(n=>n(yS(t)).pipe(vg(t=>sg(()=>e.delete(r(t)))))),defer:i,awaitBackoff:O(function*(){for(;;){let e=yield*rD(n),t=yield*Lp;if(e<=t)return;yield*M(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*Fg(ss(e-t))}})}}),v$=class e extends ro()(`@usine/orchestrator/ItemHints`){static layer=Op(e,_$)},y$=ls(10),b$={revokedRuns:0,failures:[],nextPollAt:S()},x$=j(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*A({repository:e.name});let n=yield*jL,r=yield*kq,i=yield*n.openIssues(e.name);if(i.length===0)return yield*N(`No open issues to check against GitHub`,{repository:e.name}),b$;let a=yield*yg(r.missingIssues(e.name,i));if(Wi(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*h_(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:kv(t.retryAt)}),{...b$,nextPollAt:C(t.retryAt)}):(yield*g_(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...qQ(t)}),{...b$,failures:[new WQ({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*g$(e,t,`issue`,n),i=yield*d$(e.name,n);o+=r,yield*M(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*N(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...b$,revokedRuns:o}}),S$=4,C$=4,w$=V.pipe(z(`GitHubPollWatchKey`)),T$=class extends H(`@usine/orchestrator/StoredPollCursor`)({boardVersion:dw(5),openPullRequests:I(F({number:xK.fields.number,updatedAt:jT})),cursor:yK,labelEntityTag:rT(vK),watches:I(w$).check(tT()),failingItems:I(XQ).pipe(Pw(D([])))}){},E$=e=>ZL.make(`github-poll:${yD(e.name)}`),D$=({loop:e})=>w$.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),O$=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&VU(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(D$).sort()}}),k$=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),A$=class e extends ro()(`@usine/orchestrator/PollingTriggers`){static layer=Op(e,O(function*(){let e=yield*eR,t=yield*oR,n=yield*kq,r=yield*iR,i=yield*nD(S()),a=yield*nD(new Map),o=yield*v$,s=yield*NS(1),c=yield*nD({instance:S(),repositories:new Set}),l=yield*nD(new Map),u=e=>new T$({boardVersion:5,openPullRequests:[],cursor:yK.empty,labelEntityTag:S(),watches:e,failingItems:[]}),d=j(`PollingTriggers.readCursor`)(function*(t){yield*A({repository:t.repository.name});let n=yield*e.read(E$(t.repository),T$);return w(n)?u(t.watches):k$(n.value.watches,t.watches)?n.value:(yield*M(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=j(`PollingTriggers.writeCursor`)(function*(t,n){yield*A({repository:t.repository.name}),yield*e.write(E$(t.repository),T$,n)}),p=j(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*A({repository:e.repository.name});let t=E$(e.repository),n=yield*Lp,r=(yield*rD(l)).get(t);return r!==void 0&&n-r<ps(y$)?(yield*N(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:kv(yv(r))}),b$):(yield*oD(l,e=>new Map(e).set(t,n)),yield*x$(e.repository,e.loops))}),m=j(`PollingTriggers.pollRepository`)(function*(e){yield*A({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>yD(t)===yD(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*M(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*l$(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*O(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*rD(c)).repositories.has(E$(e.repository))?[]:i.failingItems,u=new Map([...l.map(e=>[e.number,ZQ(e)]),...i.openPullRequests.map(e=>[e.number,new xK(e)])]);if(s._tag===`RepositoryChanges`){for(let e of s.items)u.set(e.number,e);yield*M(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog})}let d=new Set((s._tag===`RepositoryChanges`?s.items:[]).map(({number:e})=>e)),m=new Set([...i.openPullRequests,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*M(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let h=JQ([s.nextPollAt,a.nextPollAt]);yield*N(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,items:u.size});let g=new Map(i.failingItems.map(e=>[e.number,e])),_=yield*ng(u.values(),t=>O(function*(){let n=yield*u$(e.repository.name,t),r=yield*h$(e.repository,e.loops,n),i=QQ(t,n.projection.contentHash,r.failures);return yield*r$(e.repository.name,t.number,wi(g.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(Eg(`GitHubItemNotFoundError`,n=>O(function*(){if(!m.has(t.number))return yield*n;let r=yield*g$(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*d$(e.repository.name,t.number);return yield*h_(`GitHub no longer has an Item the poll cursor kept; it is dropped from the cursor`,{repository:e.repository.name,item:t.number,openPullRequest:i.openPullRequests.some(({number:e})=>e===t.number),revokedRuns:r,projectionMarkedGone:a,errorTag:n._tag,message:n.message}),{_tag:`Missing`,revokedRuns:r}}))),{concurrency:C$}),v=_.flatMap(e=>e._tag===`Evaluated`?[e]:[]),y=_.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),ee=v.map(({cycle:e})=>e),b=yield*p(e);yield*o.defer(b.nextPollAt);let te=[...i.failingItems.filter(({number:e})=>!u.has(e)),...v.flatMap(({failing:e})=>Pi(e))].sort((e,t)=>e.number-t.number),ne=new T$({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:v.flatMap(({item:e,observation:t})=>e._tag===`ChangedPullRequest`&&t.projection.payload.state===`OPEN`?[{number:e.number,updatedAt:e.updatedAt}]:[]),failingItems:te});return(s._tag===`RepositoryChanges`||u.size>0||a.entityTagChanged)&&(yield*f(e,ne)),yield*oD(c,t=>({...t,repositories:new Set([...t.repositories,E$(e.repository)])})),yield*ng(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:ee.flatMap(({submissions:e})=>e),revokedRuns:ee.reduce((e,t)=>e+t.revokedRuns,y+b.revokedRuns),failures:[...a.failures,...b.failures,...te.flatMap(t=>e$(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:JQ([h,b.nextPollAt])}}).pipe(Ag(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>e$(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Vg()).pipe(Lo(PQ,oR,yO,kq,jL,ML,Pq,JL,YL,DR)),g=j(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*oD(c,t=>Li(t.instance,e)?t:{instance:C(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*N(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=O$(e,(yield*zQ(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*ng(n,e=>yg(m(e)).pipe(xg(t=>({repository:e,result:t}))),{concurrency:S$}),l=[],u=[],d=[],f=[],p=yield*xv;for(let{repository:e,result:t}of s){if(Gi(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*oD(a,t=>new Map(t).set(yD(e.repository.name),new GQ({repository:e.repository.name,completedAt:p})));continue}let n=t.failure._tag===`InterruptedRepositoryCycle`,r=n?t.failure.error:t.failure;n&&(u.push(...t.failure.failures),f.push(...t.failure.preflightFindings),d.push(t.failure.nextPollAt),yield*o.defer(t.failure.nextPollAt)),r._tag===`GitHubRateLimitError`?(yield*h_(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:kv(r.retryAt)}),d.push(C(r.retryAt)),yield*o.defer(C(r.retryAt))):(yield*g_(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...qQ(r)}),u.push(new WQ({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*rD(a),g=new KQ({repositoryPolls:n.flatMap(({repository:e})=>Pi(wi(h.get(yD(e.name))))),repositories:n.length,changedItems:l.reduce((e,t)=>e+t.changedItems,0),submissions:l.flatMap(({submissions:e})=>e),revokedRuns:l.reduce((e,t)=>e+t.revokedRuns,0),failures:[...l.flatMap(({failures:e})=>e),...u],preflightFindings:f,nextPollAt:JQ([...l.map(({nextPollAt:e})=>e),...d])});return yield*iD(i,C(g)),g},Wg(h),s.withPermits(1)),_=j(`PollingTriggers.refreshHint`)(function*(e,t){yield*A({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=O$(e,(yield*zQ(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>yD(e.name)===yD(t.repository));if(i===void 0){yield*M(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*u$(i.repository.name,t.item),s=yield*h$(i.repository,i.loops,a);for(let e of s.failures)yield*h_(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*M(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Wg(h),(e,t,n)=>e.pipe(Tg(e=>O(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(C(e.retryAt))),yield*h_(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...qQ(e)})})),s.withPermits(1))),v=(e,t,n,r)=>O(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*Lp);if(t<=0)return;let n=yield*Ig([Fg(ss(t)).pipe(xg(()=>({_tag:`Due`}))),o.take.pipe(xg(e=>({_tag:`Hint`,hint:e}))),FQ(e,a).pipe(xg(e=>({_tag:`Reloaded`,instance:e})))]);if(n._tag===`Due`)return;if(n._tag===`Hint`){yield*_(yield*e.get,n.hint);continue}a=n.instance,i=r;let s=r-(yield*Lp);s>0?yield*M(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*M(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:rD(i),poll:g,run:e=>O(function*(){let t=yield*e.get,n=yield*Lp,r=yield*yg(g(t));if(Wi(r)){let e=t.config.settings.pollInterval*1e3;yield*g_(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*Fg(ss(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=E(i.nextPollAt,{onNone:()=>0,onSome:Dv}),s=yield*Lp,c=Math.max(0,Math.max(a,o)-s);yield*M(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(i_),hint:o.offer}})).pipe(Fp(v$.layer))},j$=4,M$=6e4,N$=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...UQ(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},P$=class extends U(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:CD,agent:DO,message:P}){},F$=class extends U(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:CD,repository:mD,scheduledAt:AT,errorTag:V,message:P}){},I$=class extends U(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:CD,cron:P,tz:P,message:P}){},L$=L([P$,I$,F$]),R$=class extends H(`@usine/orchestrator/ScheduleCycle`)({loops:B.check(Yw(0)),fanout:B.check(Yw(0)),submissions:I(mj),skipped:B.check(Yw(0)),alreadyFired:B.check(Yw(0)),failures:I(L$),nextTickAt:nT(AT)}){},z$=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>VU(t.selector,e)),trigger:n}]:[]}),B$=(e,t)=>{let n=Tv(t);return n.setUTCSeconds(0,0),vv(sh(e,n)?n:uh(e,n))},V$=(e,t)=>vv(lh(e,Tv(t))),H$=(e,t)=>E(wv(e,t),{onNone:()=>kv(e),onSome:Av}),U$=e=>e.length===0?S():bv(Math.min(...e.map(Dv))),W$=e=>aA.make(JSON.stringify([`github`,yD(e.name)])),G$=(e,t,n)=>xD.make(JSON.stringify([e.name,yD(t.name),kv(n)])),K$=e=>({tick:{scheduledAt:kv(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends ro()(`@usine/orchestrator/ScheduleTriggers`){static layer=Op(e,O(function*(){let e=yield*PQ,t=yield*yO,n=yield*DR,r=yield*iR,i=yield*nD(S()),a=yield*nD({instance:S(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=oh(e.cron,e.tz);return o.set(e,n),n},c=j(`ScheduleTriggers.submitTick`)(function*(r,i){yield*A({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:kv(r.scheduledAt)});let a=K$(r),o={repo:SJ(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,xJ(`schedule`),o)))return yield*N(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:kv(r.scheduledAt)}),S();let s=G$(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(VQ({cycleGeneration:cA.make(0),agent:r.agent,dedupKey:s,itemKey:W$(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:IQ,task:Jk.make(c),parentModel:r.parentModel}));return yield*M(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:kv(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...HQ(l)}),C(l)}),l=j(`ScheduleTriggers.tick`)(function*(e){let t=yield*xv,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*N(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=z$(e).filter(({loop:e})=>!n.has(e.name)),l=yield*aD(a,t=>{let n=Li(t.instance,e)?t:{instance:C(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*h_(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*mg({try:()=>{let e=s(n.trigger),r=B$(e,t);return{latest:r,latestLocal:H$(r,n.trigger.tz),next:V$(e,t)}},catch:e=>e}).pipe(yg);if(Wi(r)){yield*g_(`Schedule cron boundaries could not be computed`,{loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}),f.push(new I$({loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}));continue}let i=r.success;m.push(i.next);let a=Dv(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*N(`Tick already fired`,{loop:n.loop.name,scheduledAt:kv(i.latest)});continue}let c=yield*yg(RQ(e,n.loop));if(Wi(c)){let e=c.failure;yield*g_(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new P$({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*M(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:kv(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:kv(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*A({schedules:o.length,fanout:u.length});let g=yield*ng(u,e=>yg(c(e,t)).pipe(xg(t=>({candidate:e,result:t}))),{concurrency:j$}),_=[],v=[],y=new Set,ee=new Set,b=0;for(let{candidate:e,result:t}of g){if(Gi(t)){T(t.success)?(_.push(t.success.value),y.add(e.loop.name)):b+=1;continue}let n=t.failure;ee.add(e.loop.name),yield*g_(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:kv(e.scheduledAt),...N$(n)}),v.push(new F$({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*oD(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)y.has(e)&&!ee.has(e)&&t.set(e,n);return{...e,ticks:t}});let te=new R$({loops:o.length,fanout:u.length,submissions:_,skipped:b,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:U$(m)});return yield*iD(i,C(te)),te}),u=(e,t,n)=>Lg(Fg(ss(n)),FQ(e,t).pipe(_g(M(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:rD(i),run:e=>O(function*(){let t=yield*e.get,n=yield*yg(l(t));if(Wi(n)){yield*g_(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:M$}),yield*u(e,t,M$);return}let r=n.success,i=yield*Lp,a=E(r.nextTickAt,{onNone:()=>i+M$,onSome:Dv}),o=Math.min(M$,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:E(r.nextTickAt,{onNone:()=>`none`,onSome:kv}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*N(`Schedule cycle complete`,s):yield*M(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(i_),tick:l}}))});var q$=class extends U(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:P,repository:mD,runId:oO,loop:CD,item:R(XW)}){},J$=class extends U(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:P,repository:mD,runId:oO,loop:CD,failure:uW}){},Y$=class extends U(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:P,failure:WQ}){},X$=class extends U(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:P,finding:jq}){},Z$=class extends U(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:P,failure:rG}){},Q$=class extends U(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:P,failure:L$}){},$$=class extends U(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:P,kind:Ow([`loop`,`agent`]),error:SO}){},e1=class extends U(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,F({id:P,worker:BO,attempts:B.check(Yw(1)),running:B.check(Yw(0))}).check(Bw(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},t1=L([class extends U(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:P,ask:pA,itemLabel:P,itemUrl:R(P)}){},q$,Z$,J$,Y$,X$,Q$,$$,e1]),n1=Ow([`clear`,`active`,`needs-you`]),r1=class extends H(`@usine/orchestrator/ProjectView`)({repository:mD,status:n1,runs:I(UW),board:iG,labels:I(aG),preflightFindings:I(jq)}){},i1=class extends H(`@usine/orchestrator/LoopView`)({name:CD,trigger:P,agent:DO,paused:_w}){},a1=class extends U(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:I(r1),loops:I(i1),needsYou:I(t1)}){},o1=class extends U(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:V,projects:I(r1),loops:I(i1),needsYou:I(t1)}){},s1=L([a1,o1]),c1=10,l1=class extends U(`@usine/github/LabelAdded`)(`LabelAdded`,{at:AT,label:DK}){},u1=class extends U(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:AT,label:DK}){},d1=class extends U(`@usine/github/Commented`)(`Commented`,{at:AT,url:V}){},f1=Ow([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),p1=class extends U(`@usine/github/Reviewed`)(`Reviewed`,{at:AT,url:V,state:f1}){};L([l1,u1,d1,p1]);var m1=`
276
+ __typename
277
+ ... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
278
+ ... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
279
+ ... on IssueComment { createdAt url author { __typename login } }`,h1=`
280
+ query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
281
+ repository(owner: $owner, name: $name) {
282
+ issueOrPullRequest(number: $number) {
283
+ ... on Issue {
284
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
285
+ pageInfo { hasNextPage endCursor }
286
+ nodes {${m1}
287
+ }
288
+ }
289
+ }
290
+ ... on PullRequest {
291
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
292
+ pageInfo { hasNextPage endCursor }
293
+ nodes {${m1}
294
+ ... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+ }
301
+ `,g1=R(F({__typename:P,login:P})),_1=F({name:TK,color:EK,description:R(P)}),v1=e=>F({__typename:dw(e),createdAt:jT,actor:g1,label:_1}),y1=L([v1(`LabeledEvent`),v1(`UnlabeledEvent`),F({__typename:dw(`IssueComment`),createdAt:jT,url:V,author:g1}),F({__typename:dw(`PullRequestReview`),createdAt:jT,submittedAt:R(jT),url:V,state:Ow([...f1.literals,`PENDING`]),author:g1})]),b1=F({repository:rT(F({issueOrPullRequest:rT(F({timelineItems:F({pageInfo:F({hasNextPage:_w,endCursor:R(P)}),nodes:I(R(y1))})}))}))}),x1=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new DK({name:e.name,color:e.color,description:wi(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new l1({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new u1({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new d1({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new p1({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},S1=class e extends ro()(`@usine/github/GitHubItemHistory`){static layer=Op(e,O(function*(){let e=yield*_K,t=yield*DB,n=j(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=vD(n),l=yield*zK(t,o,`fetch-item-timeline`,h1,{owner:c,name:s,number:r,since:i,after:a},b1);if(w(l.repository))return yield*nK(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(w(u))return yield*new YG({operation:`fetch-item-timeline`,item:r,message:`Issue or pull request ${n}#${r} was not found on GitHub. It was deleted or transferred, or the GitHub App can no longer read it.`});let{pageInfo:d,nodes:f}=u.value.timelineItems;return d.hasNextPage?d.endCursor===null?yield*nK(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:C(d.endCursor)}:{nodes:f,next:S()}});return{appChanges:j(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*A({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=kv(i),s=[],c=S(),l=0;do{let e=yield*n(t,r,o,Di(c));s.push(...e.nodes),c=e.next,l+=1}while(T(c)&&l<c1);if(T(c))return yield*nK(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${c1} pages`);let u=s.flatMap(e=>e===null?[]:x1(a,e));return yield*N(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},C1=class extends U(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:P,label:aG}){},w1=class extends U(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:P,label:aG}){},T1=class extends U(`@usine/orchestrator/CommentedView`)(`Commented`,{at:P,url:P}){},E1=class extends U(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:P,url:P,state:f1}){},D1=class extends U(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:P,fromLane:dU,toLane:dU}){},O1=L([C1,w1,T1,E1,D1]),k1=class extends H(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:Kk,changes:I(O1)}){},A1=class extends H(`@usine/orchestrator/RunGitHubChangesView`)({attempts:I(k1)}){},j1=1e3,M1=6e4,N1=1e3,P1=1e4,F1=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>tA(e,i.at));t!==void 0&&(a.length>0?r.push(i):n.set(t.attemptId,[...n.get(t.attemptId)??[],i]))}return{attributed:n,ambiguous:r}},I1=e=>t=>{let n=Dv(t.at),r=n-N1,i=Dv(e.at),a=aU(e.label.name);return r-r%1e3<=i&&i<=n+P1&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>aU(e)===a)},L1=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(I1(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},R1=e=>new aG({name:iU.make(e.name),color:e.color,description:Di(e.description)}),z1=e=>$E(e,{LabelAdded:({at:e,label:t})=>new C1({at:kv(e),label:R1(t)}),LabelRemoved:({at:e,label:t})=>new w1({at:kv(e),label:R1(t)}),Commented:({at:e,url:t})=>new T1({at:kv(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new E1({at:kv(e),url:t,state:n})}),B1=e=>new D1({at:kv(e.at),fromLane:dU.make(e.fromLane),toLane:dU.make(e.toLane)}),V1=O(function*(){let e=yield*yL,t=yield*S1,n=yield*mR,r=yield*nD(new Map),i=j(`RunGitHubChanges.windowFor`)(function*(t){let n=Qk(t);if(T(n))return n;let[r]=yield*e.transcript(new Oj({attemptId:t.id,before:S(),limit:1}));return r===void 0?(yield*M(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),S()):C(new Zk({attemptId:t.id,startedAt:t.startedAt,endedAt:C(r.receivedAt)}))});return{read:j(`RunGitHubChanges.read`)(function*(a){yield*A({runId:a});let o=yield*e.inspect(a),s=$C(i$)(o.itemKey);if(w(s))return yield*N(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new A1({attempts:[]});let[,,c]=s.value,l=o.repository;yield*A({repository:l,item:c});let u=e=>new A1({attempts:o.attempts.map(({id:t})=>new k1({attemptId:t,changes:e.get(t)??[]}))}),d=yield*rD(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*N(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*ng([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(Pi),h=yield*Lp,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>Dv(e))),r=yv(e-e%1e3),[i,s]=yield*tg([t.appChanges(l,c,r),n.onItem(o.itemKey,Ov(r,{milliseconds:P1}))],{concurrency:`unbounded`}),{moves:u,rest:d}=L1(s,i),{attributed:f,ambiguous:p}=F1(m,d);p.length>0&&(yield*M(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>kv(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:Dv(e.at),view:z1(e)})),...u.flatMap(t=>{let n=Dv(t.at);return Dv(e.startedAt)<=n&&E(e.endedAt,{onNone:()=>!0,onSome:e=>n<=Dv(e)})?[{at:n,view:B1(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),T(e.endedAt)&&h-Dv(e.endedAt.value)>=M1&&_.push(e.attemptId)}yield*M(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:kv(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let y=yield*sD(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-j1)))t.delete(e);return t});return u(new Map([...y,...g]))})}});(class e extends ro()(`@usine/orchestrator/RunGitHubChanges`){static layer=Op(e,V1)});var H1=qC(I(iU)),U1=F({labels:YK.fields.labels}),W1=F({labels:$K.fields.labels}),G1=(e,t)=>qC(e===`issue`?U1:W1)(t).pipe(k(({labels:e})=>H1(e.nodes.map(({name:e})=>e)))),K1=(e,t)=>new rG({repository:e.repository,itemKey:e.itemKey,message:t}),q1=e=>O(function*(){let t=T(e.goneAt);if(e.source===`issue`){let n=yield*qC(YK)(e.payload).pipe(Ag(t=>K1(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:oA.make(e.number),title:n.title,url:n.url,state:n.state===`OPEN`&&!t?`issue-open`:`issue-closed`,linkedPullRequests:n.closedByPullRequestsReferences.nodes.map(({url:e})=>e),labels:yield*H1(n.labels.nodes.map(({name:e})=>e)).pipe(Ag(t=>K1(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*qC($K)(e.payload).pipe(Ag(t=>K1(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:oA.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*H1(n.labels.nodes.map(({name:e})=>e)).pipe(Ag(t=>K1(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*K1(e,`Unsupported item projection source: ${e.source}`)}),J1=QC(ST),Y1=e=>new XW({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url}),X1=(e,t,n,r,i,a)=>{let o=Oa(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${yD(e)}/pull/`,l=new Map(s.filter(({item:e})=>e.kind===`pr`).map(e=>[`${c}${e.item.number}`,e])),u=new Set(r);for(let e of s){if(e.item.kind!==`issue`)continue;let t=[...e.item.linkedPullRequests,...e.runs.flatMap(({pullRequestUrl:e})=>e===null?[]:[e])];for(let n of t){let t=J1(n);if(w(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=xa(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||fi(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new ZW({number:e,url:t,state:n})]:[]),m=o.find(({run:e})=>e.canApprove||e.canResolveFailure)??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new QW({...Y1(l),title:r.item.title,state:l.state,labels:l.labels,items:n.map(({item:e})=>Y1(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({run:e})=>e.canApprove||e.canResolveFailure)||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:IW(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},Z1=e=>e.flatMap(e=>`label`in e?[e.label]:[]),Q1=e=>e.flatMap(e=>`state`in e?[e.state]:[]),$1=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>iU.make(e)).map(e=>({lane:new _U({name:dU.make(e),sources:[new hU({label:e})]}),origin:`proposed`})),e0=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):$1(t),t0=e=>JW.make(`${e.origin}:${e.lane.name}`),n0=(e,t)=>{let n=new Set(e.labels.map(aU));return t.find(({lane:e})=>Z1(e.sources).some(e=>n.has(aU(e))))},r0=(e,t)=>t.find(({lane:t})=>Q1(t.sources).includes(e.state)),i0=(e,t)=>mU(e.state)?r0(e,t):n0(e,t)??r0(e,t),a0=j(`Board.triggerLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*A(a),mU(t.state))return;let o=i.get(n.id);if(o===void 0){yield*N(`No Event read for the card's running Run; placing it by its Item's labels`,a);return}let s=yield*G1(t.kind,o.payload).pipe(xg(C),Tg(e=>h_(`The running Run's Event has no labels to read; placing its card by its Item's labels`,{...a,eventId:o.id,errorTag:e._tag,message:e.message}).pipe(Sg(S()))));if(w(s))return;let c=n0({labels:s.value},r);return yield*N(c===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's labels`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:c?.lane.name??`none`}),c}),o0=j(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>O(function*(){yield*A({repository:e.name});let c=yield*ng(n,e=>q1(e).pipe(yg)),l=[],u=[];for(let e of c)Gi(e)?l.push(e.success):(u.push(e.failure),yield*g_(`Item projection quarantined from Board; siblings continue`,{repository:e.failure.repository,itemKey:e.failure.itemKey,errorTag:e.failure._tag,message:e.failure.message}));let d=e0(e,t),f=X1(e.name,l,r,i,a,o);yield*N(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(t0(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*a0(e,t,n,d,s))??i0(t,d);r===void 0?m.push(t):p.get(t0(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new iG({failures:u,lanes:[...d.map(e=>{let t=Z1(e.lane.sources),n={id:t0(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(t0(e))??[])};return e.origin===`authored`&&t.length>0?new eG({...n,origin:e.origin,labels:t}):new tG(n)}),new tG({id:JW.make(`fallback:unmapped`),name:dU.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),s0=500,c0=500,l0=e=>$E(e,{InfraFailure:({message:e})=>new rW({message:e}),DefectFailure:({message:e})=>new iW({message:e}),AgentFailure:({message:e})=>new aW({message:e}),BlockedFailure:({message:e})=>new oW({message:e}),QuestionFailure:({question:e})=>new sW({question:e}),RunawayFailure:({ceiling:e})=>new cW({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new lW({attemptedChildren:e,maxChildren:t})}),u0=e=>$E(e,{Succeeded:()=>new dW,Failed:({failure:e})=>new fW({failure:l0(e)}),Canceled:()=>new pW}),d0=e=>{switch(e.kind){case`local`:return new hW;case`ssh`:return new gW({destination:e.destination,port:Di(e.port)});case`exe.dev`:return new gW({destination:UO.make(`${e.name}.exe.xyz`),port:null})}},f0=e=>new Map(e.map(e=>[e.name,d0(e)])),p0=(e,t)=>new vW({id:e.id,number:e.number,worker:e.worker,workerAccess:t.get(e.worker)??null,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,startedAt:kv(e.startedAt),outcome:E(e.outcome,{onNone:()=>null,onSome:u0}),endedAt:E(e.endedAt,{onNone:()=>null,onSome:kv}),salvage:Di(e.salvage),start:Di(e.start),reattachedAt:E(e.reattachedAt,{onNone:()=>null,onSome:kv})});j(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*ng(t.attempts.filter(e=>T(e.outcome)&&w(e.endedAt)),t=>e.transcript(new Oj({attemptId:t.id,before:S(),limit:1})).pipe(xg(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var m0=j(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*N(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),h0=(e,t,n)=>{let r=KD(e.run.state),i=Di(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new UW({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:kv(e.run.openedAt),closedAt:E(e.closedAt,{onNone:()=>null,onSome:kv}),task:e.task,attempts:e.attempts.map(e=>p0(e,n)),approval:E(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new HW({approvedAt:kv(e),source:Di(t)})}),runAgain:Di(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!Li(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},g0=e=>$E(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new yW({failure:l0(e)}),Interrupted:e=>e,Steer:e=>e,Interrupt:e=>e,OperatorMessage:e=>e,Release:e=>e,Cancel:e=>e,InterventionApplied:e=>e,InterventionRejected:e=>e,WorkerUnresponsive:e=>e,WorkerResponsive:e=>e}),_0=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:kv(e.receivedAt),direction:e.direction,payload:g0(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new xW({...t,target:e.envelope.target,operator:e.envelope.operator}):new xW(t)},v0=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(_0),y0=j(`Operator.readTranscriptPage`)(function*(e,t,n){yield*A({attemptId:t,before:Di(n)});let r=yield*e.transcript(new Oj({attemptId:t,before:n,limit:501})),i=r.length>s0,a=i?r.slice(1):r,o=a[0];return yield*N(`Read operator transcript page`,{attemptId:t,before:Di(n),returned:a.length,hasEarlier:i}),{events:v0(a),earlier:i&&o!==void 0?[new SW({attemptId:t,before:o.sequence})]:[]}});j(`Operator.readTranscript`)(function*(e,t,n){yield*A({runId:t.run.id,request:n._tag});let r=yield*$E(n,{ColdTranscriptRequest:()=>ng(t.attempts,t=>y0(e,t.id,S()),{concurrency:4}).pipe(xg(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>ng(t.attempts,t=>e.transcript(new Dj({attemptId:t.id,after:n,limit:c0})),{concurrency:4}).pipe(xg(e=>({events:v0(e.flat()).slice(0,c0),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?y0(e,n,C(r)):new EW({runId:t.run.id,attemptId:n})});return yield*N(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var b0=500,x0=class extends H(`@usine/orchestrator/TaskItemView`)({...XW.fields,state:fU,labels:I(iU),conflicting:_w}){},S0=class extends H(`@usine/orchestrator/TaskLaneView`)({id:JW,name:dU}){},C0=class extends H(`@usine/orchestrator/TaskCommentView`)({runId:oO,kind:PO,url:P,postedAt:R(P),attemptEndedAt:R(P)}){},w0=class extends H(`@usine/orchestrator/TaskView`)({repository:mD,number:oA,title:P,current:aA,lane:S0,needsYou:_w,items:Ew(x0),runs:I(UW),comments:I(C0)}){},T0=E({onNone:()=>null,onSome:kv}),E0=e=>{let t=(t,n)=>new C0({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:T0(t.at),attemptEndedAt:T0(n)}),n=ba(e.attempts,e=>Ri(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(ji(({endedAt:e})=>e)),r=E(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return Ia([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},D0=O(function*(){let e=yield*yL,t=yield*iR,n=yield*jL,r=yield*JL,i=yield*oR;return{read:j(`TaskReader.read`)(function*(a,o,s){yield*A({repository:o,item:s});let c=a.config.repos.find(({name:e})=>yD(e)===yD(o));if(c===void 0)return yield*M(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new oG({repository:o});let[l,u,d,f]=yield*tg([n.list(c.name,{limit:b0}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*m0(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=f0(a.config.workers),_=(yield*o0(c,E(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>h0(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*M(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:b0}),yield*new sG({repository:c.name,item:s});let{lane:v,task:y}=_,ee=new Set(y.items.map(({itemKey:e})=>e)),b=yield*ng(l.filter(({itemKey:e})=>ee.has(e)),e=>q1(e).pipe(yg)),te=new Map;for(let e of b){if(Wi(e)){yield*g_(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;te.set(t,new x0({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ne,...re]=y.items.flatMap(({itemKey:e})=>{let t=te.get(e);return t===void 0?[]:[t]});if(ne===void 0)return yield*new sG({repository:c.name,item:s});let ie=new Set(y.runs.map(({id:e})=>e)),ae=p.filter(({run:e})=>ie.has(e.id)).sort((e,t)=>Dv(t.run.openedAt)-Dv(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(E0),oe=new w0({repository:c.name,number:ne.number,title:y.title,current:y.itemKey,lane:new S0({id:v.id,name:v.name}),needsYou:y.needsYou,items:[ne,...re],runs:[...y.runs].reverse(),comments:ae});return yield*N(`Read a Task`,{repository:c.name,item:s,origin:oe.number,lane:v.name,items:oe.items.length,runs:oe.runs.length,comments:ae.length}),oe})}});(class e extends ro()(`@usine/orchestrator/TaskReader`){static layer=Op(e,D0)});var O0=Ow([`binary`,`version`,`login`]),k0=class extends BT(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:wO,capability:O0,message:V}){};L([class extends U(`HarnessReady`)(`HarnessReady`,{harness:wO}){},k0]),KC(k0),hi(di,({harness:e})=>e);var A0=class e extends ro()(`@usine/orchestrator/WorkerStatus`){static idle=Ep(e)({slots:D([]),preflights:D([])})},j0=class extends H(`@usine/orchestrator/LoopSelectorView`)({repos:R(I(mD)),tags:R(I(vU))}){},M0=class extends H(`@usine/orchestrator/LoopFileView`)({name:CD,file:bO,stream:Ow([`issue`,`pr`,`schedule`]),condition:gO,cron:R(HU),timeZone:R(UU),selector:R(j0),repositories:I(mD),approval:TD,maxCycles:sA,permissions:DD,step:RO,agent:DO,prompt:XU,paused:_w,undeclaredLabels:I(iU)}){},N0=class extends H(`@usine/orchestrator/QuarantinedLoopView`)({name:V,file:bO,error:SO}){},P0=class extends H(`@usine/orchestrator/AgentFileView`)({name:DO,file:bO,harness:wO,model:CO,effort:TO,parentModel:R(CO),parentEffort:R(TO),resolvedParentModel:R(CO),resolvedParentEffort:TO,persona:OO,loops:I(CD)}){},F0=class extends H(`@usine/orchestrator/InvalidAgentView`)({name:V,file:bO,error:SO}){},I0=class extends H(`@usine/orchestrator/GatewayView`)({domain:qO,destination:UO,adminPort:JO,adminTokenEnv:V,llmProviders:I(YO)}){},L0=class extends H(`@usine/orchestrator/WorkerSlotsView`)({capacity:B,leased:B}){},R0=class extends U(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:P}){},z0=class extends U(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:P,capability:R(kR),message:P}){},B0=L([R0,z0]),V0=class extends H(`@usine/orchestrator/HarnessPreflightView`)({harness:wO,check:B0}){},H0=class extends H(`@usine/orchestrator/WorkerConfigurationView`)({name:BO,kind:VO,maxConcurrentAttempts:B,destination:R(UO),port:R(WO),identityFile:R(GO),root:R(KO),gateway:R(I0),slots:R(L0),prerequisites:R(B0),harnesses:I(V0)}){},U0=class extends H(`@usine/orchestrator/RemovedWorkerView`)({name:BO,running:B}){},W0=class extends H(`@usine/orchestrator/LabelStateView`)({name:iU,onGitHub:R(_w),color:R(P),description:R(P),declared:_w,failure:R(jq)}){},G0=class extends U(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:W0}){},K0=class extends U(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:fU}){},q0=L([G0,K0]),J0=class extends H(`@usine/orchestrator/LaneConfigurationView`)({name:dU,sources:I(q0)}){},Y0=class extends H(`@usine/orchestrator/RepositoryConfigurationView`)({name:mD,tags:I(vU),lanes:I(J0),declaredLabels:I(W0),loops:I(CD)}){},X0=class extends H(`@usine/orchestrator/SettingsView`)({pollInterval:B,maxChildren:B,maxAttemptMinutes:R(B),maxAttemptTokens:R(B),parentModel:R(CO),parentEffort:R(TO),operator:R(Rk),webhooks:Ow([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:R(P)}){},Z0=class extends H(`@usine/orchestrator/ConfigurationView`)({loops:I(M0),quarantinedLoops:I(N0),agents:I(P0),invalidAgents:I(F0),workers:I(H0),removedWorkers:I(U0),repositories:I(Y0),settings:X0}){},Q0=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},$0=e=>$E(e,{Passed:({checkedAt:e})=>new R0({checkedAt:kv(e)}),Failed:({checkedAt:e,capability:t,message:n})=>new z0({checkedAt:kv(e),capability:Di(t),message:n})}),e2=e=>e.kind===`ssh`?{destination:e.destination,port:Di(e.port),identityFile:Di(e.identityFile),root:e.root,gateway:E(e.gateway,{onNone:()=>null,onSome:e=>new I0({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})})}:{destination:null,port:null,identityFile:null,root:null,gateway:null},t2=O(function*(){let e=yield*iR,t=yield*JL,n=yield*A$,r=yield*A0,i=j(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Ai(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[aU(e.name),e]))),a=new Map(e.config.labels.map(e=>[aU(e.name),e])),o=e=>{let t=aU(e),o=ji(i,e=>wi(e.get(t))),s=a.get(t);return new W0({name:e,onGitHub:E(i,{onNone:()=>null,onSome:()=>T(o)}),color:Di(Si(ji(o,({color:e})=>e),()=>ji(wi(s),({color:e})=>e))),description:Di(Si(ji(o,({description:e})=>e),()=>ji(wi(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&aU(e.label)===t)??null})};return new Y0({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new J0({name:e.name,sources:e.sources.map(e=>`label`in e?new G0({label:o(e.label)}):new K0({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>VU(e.selector,n)).map(({name:e})=>e)})});return{view:j(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l]=yield*tg([e.states,n.latest,r.slots,r.preflights],{concurrency:`unbounded`}),u=new Set(o.filter(e=>e.paused).map(e=>e.loop)),d=E(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),f=yield*ng(a.repos,e=>i(t,e,d),{concurrency:4}),p=e=>t.warnings.flatMap(t=>t._tag===`UndeclaredTriggerLabelWarning`&&t.loop===e?[t.label]:[]),m=t.loops.map(e=>new M0({name:e.name,file:bO.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:E(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new j0({repos:Di(e),tags:Di(t)})}),repositories:a.repos.filter(t=>VU(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,step:e.step,agent:e.agent,prompt:e.body,paused:u.has(e.name),undeclaredLabels:p(e.name)})),h=t.agents.map(e=>new P0({name:e.name,file:bO.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:Di(e.parentModel),parentEffort:Di(e.parentEffort),resolvedParentModel:Di(AO(e.agent,a.settings.parentModel)),resolvedParentEffort:jO(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),g=new Map(c.map(e=>[e.worker,e])),_=new Map(l.map(e=>[e.worker,e])),v=new Set(a.workers.map(({name:e})=>e)),y=a.workers.map(e=>{let t=g.get(e.name),n=_.get(e.name);return new H0({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...e2(e),slots:t===void 0?null:new L0({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:Di(Ai(n.prerequisites,$0)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new V0({harness:e,check:$0(t)}))})}),{settings:ee,webhooks:b}=a,te=new Z0({loops:m,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new N0({name:Q0(e),file:e,error:t})),agents:h,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new F0({name:Q0(e),file:e,error:t})),workers:y,removedWorkers:c.filter(({worker:e,leased:t})=>!v.has(e)&&t>0).map(({worker:e,leased:t})=>new U0({name:e,running:t})),repositories:f,settings:new X0({pollInterval:ee.pollInterval,maxChildren:ee.maxChildren,maxAttemptMinutes:Di(ee.maxAttemptMinutes),maxAttemptTokens:Di(ee.maxAttemptTokens),parentModel:Di(ee.parentModel),parentEffort:Di(ee.parentEffort),operator:Di(a.operator),webhooks:b.mode,webhooksPublicUrl:b.mode===`endpoint`?b.publicUrl.href:null})});return yield*N(`Read the configuration view`,{loops:m.length,quarantinedLoops:te.quarantinedLoops.length,agents:h.length,invalidAgents:te.invalidAgents.length,workers:y.length,runningWorkers:c.length,repositories:f.length}),te})}});(class e extends ro()(`@usine/orchestrator/OperatorConfiguration`){static layer=Op(e,t2)});var n2=class e extends ro()(`@usine/orchestrator/LoopMatches`){static layer=Op(e,O(function*(){let e=yield*yO;return{matching:j(`LoopMatches.matching`)(function*(e,t,n){yield*A({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&VU(e.selector,t)),i=n.filter(({goneAt:e})=>w(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*yg(m$(e,t,n.map(({payload:e})=>e)));if(Wi(r)){o+=n.length,yield*N(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of Sa(n,r.success))Gi(a)?a.success&&s.add(i):(o+=1,yield*N(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*N(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},qg(yO,e))}}))},r2=200,i2=10,a2=100,o2=500,s2=class extends U(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:BO,lastAnsweredAt:P}){},c2=class extends U(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:DO,message:V,retries:bk,since:P}){},l2=L([s2,c2]),u2=class extends H(`@usine/orchestrator/RunningAttemptView`)({run:UW,attempt:vW,item:R(XW),lastActivityAt:R(P),warnings:I(l2)}){},d2=class extends U(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:UW}){},f2=class extends U(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:UW}){},p2=class extends U(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:UW}){},m2=class extends U(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},h2=class extends U(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:pA}){},g2=class extends U(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:UW}){},_2=class extends U(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:UW}){},v2=class extends U(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},y2=L([g2,d2,h2,p2,f2,m2,_2,v2]),b2=class extends H(`@usine/orchestrator/StalledItemView`)({repository:mD,loop:CD,item:XW,reason:y2}){},x2=class extends H(`@usine/orchestrator/ClosedRunView`)({run:UW,item:R(XW),closedAt:P}){},S2=class extends H(`@usine/orchestrator/WorkerView`)({name:BO,slots:L0,preflight:R(B0)}){},C2=class extends H(`@usine/orchestrator/RepositoryPollView`)({repository:mD,polledAt:R(P)}){},w2=class extends H(`@usine/orchestrator/DeskView`)({running:I(u2),notMoving:I(b2),lastOutcomes:I(x2),workers:I(S2),polls:I(C2)}){},T2=({runs:e,sighting:t,paused:n,ask:r})=>{let i=e.find(({state:e})=>JD.some(t=>t===e));if(i!==void 0)switch(i.state){case`Running`:return S();case`Waiting`:return C(new g2({run:i}));default:return C(new _2({run:i}))}if(n)return C(new m2);let a=t=>wi(e.find(({id:e})=>e===t)),o=ji(ji(t,({suppressedBy:e})=>e),a);if(T(o))return C(new d2({run:o.value}));if(T(r))return C(new h2({ask:r.value}));let s=ji(ji(t,({run:e})=>e),a);return T(s)?C(s.value.state===`Failed`?new p2({run:s.value}):new f2({run:s.value})):C(new v2)},E2=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`QueuedForWorker`,`AwaitingPoll`],D2=mi([hi(fi,({reason:e})=>E2.indexOf(e._tag)),hi(di,({repository:e})=>e),hi(pi(fi),({item:e})=>e.number),hi(di,({loop:e})=>e)]),O2=({direction:e,envelope:t})=>{let n=t.payload;return e===`outbound`&&n._tag!==`WorkerUnresponsive`&&n._tag!==`WorkerResponsive`&&(n._tag!==`SessionEvent`||n.event._tag!==`PoolRateLimitsUpdated`&&n.event._tag!==`ProviderRetrying`)},k2=e=>{let t=null,n=new Map,r=null;for(let i of e){O2(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new s2({worker:e.worker,lastAnsweredAt:kv(e.lastAnsweredAt)});else if(e._tag===`WorkerResponsive`)t=null;else if(e._tag===`SessionEvent`){let t=e.event;t._tag===`ProviderRetrying`?n.set(t.session.id,new c2({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??kv(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:kv(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},A2=e=>Dv(e.checkedAt),j2=e=>{let t=[...Pi(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`);return wi((n.length>0?n:t).reduce((e,t)=>e===void 0||A2(t)>A2(e)?t:e,void 0))},M2=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},N2=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,P2=O(function*(){let e=yield*yL,t=yield*iR,n=yield*oR,r=yield*jL,i=yield*A$,a=yield*n2,o=yield*A0,s=j(`Operator.desk.recentActivity`)(function*(t){return yield*A({attemptId:t.id}),k2(yield*e.transcript(new Oj({attemptId:t.id,before:S(),limit:r2})))});return{desk:j(`Operator.desk`)(function*(c){let[l,u,d,f,p,m,h]=yield*tg([e.list({closedLimit:0}),e.closed({limit:a2}),t.states,n.asks(),o.slots,o.preflights,i.latest],{concurrency:`unbounded`}),g=new Set(d.filter(e=>e.paused).map(e=>e.loop)),_=f0(c.config.workers),v=yield*ng(c.config.repos,e=>O(function*(){let t=yield*r.list(e.name,{limit:o2});return{repository:e,items:t,matches:yield*a.matching(c,e,t)}}),{concurrency:4}),y=new Map;for(let{items:e}of v)for(let t of e){let e=yield*yg(q1(t));if(Wi(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o}=e.success;y.set(n,new XW({itemKey:n,kind:r,number:i,title:a,url:o}))}let ee=v.flatMap(({matches:e})=>e),b=[...new Set(ee.map(({item:e})=>e.itemKey))],[te,ne]=yield*tg([e.forItems(b),e.sightings(b)],{concurrency:`unbounded`}),re=[...new Map([...l,...te].map(e=>[e.run.id,h0(e,g,_)])).values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),ie=[];for(let{loop:e,item:t}of ee){let n=y.get(t.itemKey);if(n===void 0)continue;let r=T2({runs:re.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:wi(ne.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:g.has(e.name),ask:wi(f.find(({itemKey:e})=>e===t.itemKey))});w(r)||(yield*N(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...$E(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),QueuedForWorker:({run:e})=>({runId:e.id}),AwaitingPoll:()=>({})})}),ie.push(new b2({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let ae=yield*ng(re.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>xg(s(t),n=>new u2({run:e,attempt:t,item:y.get(e.itemKey)??null,...n})),{concurrency:4}),oe=u.filter(e=>!N2(e)).map(e=>{let t=h0(e,g,_);return new x2({run:t,item:y.get(t.itemKey)??null,closedAt:M2(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,i2),se=new Map(p.map(e=>[e.worker,e])),ce=new Map(m.map(e=>[e.worker,e])),le=new Set(c.config.workers.map(({name:e})=>e)),ue=[...c.config.workers.map(({name:e})=>e),...p.map(({worker:e})=>e).filter(e=>!le.has(e))].map(e=>{let t=se.get(e),n=ce.get(e);return new S2({name:e,slots:new L0({capacity:t?.capacity??c.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:Di(Ai(ji(wi(n),j2),$0))})}),de=E(h,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),fe=c.config.repos.map(({name:e})=>{let t=de.find(({repository:t})=>yD(t)===yD(e));return new C2({repository:e,polledAt:t===void 0?null:kv(t.completedAt)})});return yield*N(`Built the operator desk`,{running:ae.length,matches:ee.length,notMoving:ie.length,lastOutcomes:oe.length,workers:ue.length}),new w2({running:ae,notMoving:[...ie].sort(D2),lastOutcomes:oe,workers:ue,polls:fe})})}});(class e extends ro()(`@usine/orchestrator/OperatorDesk`){static layer=Op(e,P2).pipe(Fp(n2.layer))});var F2={SchemaError:400,InvalidRequestError:400,CrossSiteRequestError:403,RunNotFoundError:404,TranscriptAttemptNotFoundError:404,BoardProjectNotFoundError:404,BoardItemNotFoundError:404,BoardLaneNotFoundError:404,GitHubItemNotFoundError:404,RunOperationRejectedError:409,RunRetryBlockedError:409,RunInterventionRejectedError:409,LeftoversDiscardRejectedError:409,RosterAgentNotFoundError:404,LoopNotFoundError:404,CycleBudgetResetRejectedError:409,BoardLaneReadOnlyError:409,RestartRequiredError:409,ReloadPreflightError:409,FactoryConfigError:422,EnginePersistenceError:500,AttemptCancellationError:500,HttpBodyError:500,GitHubApiError:502,InvalidGitHubResponseError:502,BackendUnavailableError:503,InstallationDiscoveryError:503,AppPermissionError:503,GitHubRateLimitError:503},I2=class extends zT(`@usine/orchestrator/OperatorHttpError`)({error:Ow(ra(F2)),message:P}){get status(){return F2[this.error]}},L2=[...new Set(Object.values(F2))].map(e=>I2.check(Bw(t=>t.status===e)).annotate({httpApiStatus:e})),R2=class extends xH()(`@usine/orchestrator/OperatorHttpPolicy`,{error:L2}){},z2=L([Lw(`WorkerCapabilityError`,{worker:BO,capability:kR,message:P}),Lw(`ExecutorOperationError`,{operation:OR,message:P}),Lw(`CredentialUnavailableError`,{repository:mD,message:P})]),B2=class extends zT(`@usine/orchestrator/RestartRequiredRefusal`)({error:dw(`RestartRequiredError`),message:P,blocks:Ew(eW),fields:Ew(V)},{httpApiStatus:409}){},V2=class extends zT(`@usine/orchestrator/ReloadPreflightRefusal`)({error:dw(`ReloadPreflightError`),message:P,agents:I(DO),workers:I(BO),cause:z2},{httpApiStatus:409}){},H2=class extends zT(`@usine/orchestrator/FactoryConfigRefusal`)({error:dw(`FactoryConfigError`),message:P,file:bO,stage:xO},{httpApiStatus:422}){},U2=sw(fw),W2=L([P,Ew(P).pipe(Aw(P,ty({decode:e=>e[0],encode:e=>[e]})))]),G2=W2.pipe(Aw(DT),Aw(_j)),K2=L([F({after:U2,before:U2,attempt:U2}).pipe(Aw(lw(CW),ty({decode:()=>new CW,encode:()=>({})}))),F({after:G2,before:U2,attempt:U2}).pipe(Aw(lw(wW),ty({decode:({after:e})=>new wW({after:e}),encode:({after:e})=>({after:e})}))),F({after:U2,before:G2,attempt:W2.pipe(Aw(Kk))}).pipe(Aw(lw(TW),ty({decode:({before:e,attempt:t})=>new TW({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),q2=P.check(Vw(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),J2=F({ok:dw(!0)}),Y2={runId:oO},X2={loop:CD},Z2=aH(`OperatorApi`).add(tU(`operator`).add($V(`overview`,`/api/overview`,{success:s1}),$V(`agents`,`/api/agents`,{success:I(DO)}),eH(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:Y2,payload:BW.annotate({parseOptions:{onExcessProperty:`error`}}),success:J2}),eH(`runAgain`,`/api/runs/:runId/run-again`,{params:Y2,payload:BW.annotate({parseOptions:{onExcessProperty:`error`}}),success:Ij}),eH(`intervene`,`/api/runs/:runId/intervene`,{params:Y2,payload:VW.annotate({parseOptions:{onExcessProperty:`error`}}),success:J2}),eH(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:F({askId:fA}).annotate({parseOptions:{onExcessProperty:`error`}}),success:J2}),$V(`detail`,`/api/runs/:runId`,{params:Y2,query:K2,success:qW}),$V(`githubChanges`,`/api/runs/:runId/github-changes`,{params:Y2,success:A1}),eH(`approve`,`/api/runs/:runId/approve`,{params:Y2,success:J2}),eH(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:Y2,payload:F({attemptId:Kk}).annotate({parseOptions:{onExcessProperty:`error`}}),success:J2}),eH(`retry`,`/api/runs/:runId/retry`,{params:Y2,success:J2}),eH(`cancel`,`/api/runs/:runId/cancel`,{params:Y2,success:J2}),eH(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:q2,repository:q2,item:DT.pipe(Aw(oA))},payload:F({toLane:JW}).annotate({parseOptions:{onExcessProperty:`error`}}),success:J2}),eH(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:BO},success:J2}),eH(`pause`,`/api/loops/:loop/pause`,{params:X2,success:J2}),eH(`unpause`,`/api/loops/:loop/unpause`,{params:X2,success:J2}),eH(`reload`,`/api/instance/reload`,{success:nW,error:[B2,V2,H2]})).add($V(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:q2,repository:q2,item:DT.pipe(Aw(oA))},success:w0})).add($V(`configuration`,`/api/configuration`,{success:Z0})).add($V(`desk`,`/api/desk`,{success:w2})).middleware(R2)),Q2=()=>wH(Z2,{baseUrl:globalThis.location.origin}),$2=e=>d_(k(Q2(),t=>e(t.operator)).pipe(Ug(uG))),e4=e=>e instanceof Error?e.message:String(e),t4=e=>`${e.harness} · ${e.model} · ${e.effort}`,n4={approve:`Approve`,retry:`Retry`,runAgain:`Run again`,cancel:`Cancel run`,confirmCancel:`Confirm cancel`,keepRunning:`Keep running`},r4=`Opening a run…`,i4=`No run opened: cycle budget used up. Reset it in Needs attention`,a4=e=>e===`pr`?`Pull request`:`Issue`,o4=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},s4=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},c4=(e,t)=>{let n=s4(e,t);return n===`now`?`just now`:`${n} ago`},l4=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},u4=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],d4=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${u4[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},f4=e=>`${e.getDate()} ${u4[e.getMonth()]}`,p4=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},m4=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},h4=e=>$E(e,{Event:()=>`From the event`,OperatorRetry:({operator:e})=>E(e,{onNone:()=>`Retried`,onSome:e=>`Retried by ${e}`}),EditAndRetry:({operator:e})=>E(e,{onNone:()=>`Edited and retried`,onSome:e=>`Edited and retried by ${e}`}),InfraRetry:()=>`Retried after an infrastructure failure`,AfterRestart:()=>`Started again after a restart`}),g4=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),_4=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,v4=e=>{let t=e.attempts.length,n=t===0?``:` after ${t} ${t===1?`attempt`:`attempts`}`;switch(e.state){case`Pending`:return`Pending`;case`Waiting`:return`Waiting for approval`;case`Queued`:return`Queued, no free worker`;case`Running`:return`Running, attempt ${e.attempts.at(-1)?.number??1}`;case`Succeeded`:return t>1?`Succeeded${n}`:`Succeeded`;case`Failed`:return`Failed${n}`;case`Canceled`:return`Canceled${n}`}},y4=e=>$E(e,{InfraFailure:()=>`Infrastructure failure`,DefectFailure:()=>`Executor defect`,AgentFailure:()=>`Agent failure`,BlockedFailure:()=>`Agent blocked`,QuestionFailure:()=>`Question from the agent`,RunawayFailure:()=>`Runaway guard`,ChildSessionBudgetFailure:()=>`Child session budget exhausted`}),b4=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],x4=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],S4=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,C4=e=>`Opened ${l4(e)}`,w4=(e,t)=>e===`Running`?`Running since ${l4(t)}`:e===`Failed`?`Failed at ${l4(t)}`:C4(t),T4={ui:`from the UI`,"github-ask":`from GitHub`},E4={approve:`Approving…`,retry:`Retrying…`,cancel:`Canceling…`,resolveFailure:`Marking resolved…`},D4=e=>e===`saving`?`Moving…`:`Saved on GitHub · syncing…`,O4=e=>$E(e,{InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e,BlockedFailure:({message:e})=>e,QuestionFailure:({question:e})=>e,RunawayFailure:({ceiling:e})=>e===`wall-clock`?`Time limit reached: settings.max_attempt_minutes`:`Token limit reached: settings.max_attempt_tokens`,ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>`Child session budget of ${t} used; child ${e} did not start`}),k4=e=>e===`parent`?`Queued until the delegated task ends`:`Queued until the current child step ends`,A4=({ref:e,commit:t})=>`Not applied: the previous attempt's work on ${e} at ${t.slice(0,7)} conflicts with the current revision. It is still on ${e}`,j4=e=>$E(e,{CycleBudgetNeed:({ask:e,itemLabel:t})=>({title:`Cycle budget exhausted`,detail:`${t}: ${e.completedCycles} completed rounds. ${e.counts.map(({loop:e,admitted:t})=>`${e}: ${t} ${t===1?`run`:`runs`}`).join(`; `)}`,repository:e.repository,runId:null}),ApprovalNeed:({loop:e,repository:t,runId:n,item:r})=>({title:`${e}: approval needed`,detail:r===null?`Open the run for the task text`:`#${r.number} ${r.title}`,repository:t,runId:n}),RunFailureNeed:({failure:e,loop:t,repository:n,runId:r})=>({title:e._tag===`QuestionFailure`?`Question from ${t}`:e._tag===`BlockedFailure`?`${t}: blocked`:`${t}: ${y4(e).toLowerCase()}`,detail:O4(e),repository:n,runId:r}),BoardProjectionNeed:({failure:e})=>({title:`Item not shown on the board`,detail:e.message,repository:e.repository,runId:null}),PollFailureNeed:({failure:e})=>({title:e.errorTag,detail:e.message,repository:e.repository,runId:null}),PreflightFindingNeed:({finding:e})=>({title:`Label preflight failed`,detail:`${e.label}: ${e.message}`,repository:e.repository,runId:null}),ScheduleFailureNeed:({failure:e})=>({title:$E(e,{ScheduleTickFailure:({errorTag:e})=>e,ScheduleAgentFailure:({loop:e})=>`${e}: agent not loaded`,ScheduleCronFailure:({loop:e})=>`${e}: schedule not computed`}),detail:e.message,repository:e._tag===`ScheduleTickFailure`?e.repository:null,runId:null}),ConfigFileNeed:({kind:e,error:t})=>({title:e===`loop`?`Loop file not loaded`:`Agent file not loaded`,detail:`${t.file}: ${t.message.replace(/\.$/u,``)}. Fix the file, then reload the configuration from Configuration > Loops`,repository:null,runId:null}),UnconfiguredWorkerNeed:({worker:e,attempts:t,running:n})=>({title:`Worker not configured`,detail:n>0?`${e} is not in usine.yaml. ${n} ${n===1?`attempt`:`attempts`} still running on it. Discard the leftovers after they end`:`${e} is not in usine.yaml. Startup does not reconcile the ${t} recorded ${t===1?`attempt`:`attempts`} on it. Add the worker back and restart usine up, or discard the leftovers`,repository:null,runId:null})}),M4=e=>{let t=[[`Loops`,e.loops],[`Agents`,e.agents],[`Labels`,e.labels],[`Repositories`,e.repos],[`Workers`,e.workers]].flatMap(([e,{added:t,removed:n,changed:r}])=>[[`added`,t],[`removed`,n],[`changed`,r]].flatMap(([t,n])=>n.length===0?[]:[`${e} ${t}: ${n.join(`, `)}`]));return e.settingsChanged&&t.push(`Settings changed`),e.operatorChanged&&t.push(`Operator login changed`),t.length===0&&t.push(`Nothing changed`),t},N4=e=>{let t=[...M4(e)],n=e.quarantinedLoops.length+e.invalidAgents.length;return n>0&&t.push(n===1?`1 file not loaded, listed in Needs attention`:`${n} files not loaded, listed in Needs attention`),t};export{AA as $,w as $t,o4 as A,o as An,Yw as At,a1 as B,Tg as Bt,E4 as C,b as Cn,Aw as Ct,v4 as D,me as Dn,KC as Dt,w4 as E,re as En,TT as Et,H2 as F,GC as Ft,CW as G,Pa as Gt,BW as H,f_ as Ht,I2 as I,kv as It,mU as J,ji as Jt,TW as K,Ni as Kt,V2 as L,Ev as Lt,S4 as M,Qw as Mt,$2 as N,cw as Nt,l4 as O,fe as On,Xw as Ot,e4 as P,sw as Pt,EA as Q,Oi as Qt,B2 as R,Dv as Rt,n4 as S,f as Sn,$C as St,r4 as T,g as Tn,iw as Tt,qW as U,mg as Ut,i$ as V,h_ as Vt,VW as W,o_ as Wt,jA as X,xi as Xt,_j as Y,wi as Yt,wA as Z,Di as Zt,C4 as _,ee as _n,gw as _t,p4 as a,C as an,JD as at,M4 as b,v as bn,F as bt,d4 as c,Ie as cn,$E as ct,O4 as d,De as dn,DT as dt,T as en,DA as et,y4 as f,Ce as fn,B as ft,j4 as g,p as gn,R as gt,D4 as h,ve as hn,Ow as ht,t4 as i,Si as in,oO as it,_4 as j,eT as jt,g4 as k,s as kn,Uw as kt,m4 as l,Me as ln,I as lt,a4 as m,ye as mn,dw as mt,T4 as n,E as nn,Jk as nt,A4 as o,tt as on,mD as ot,b4 as p,Se as pn,tE as pt,wW as q,Fi as qt,h4 as r,S as rn,DO as rt,f4 as s,et as sn,vD as st,c4 as t,Ai as tn,oA as tt,s4 as u,Oe as un,_w as ut,x4 as v,y as vn,Cw as vt,i4 as w,ne as wn,QC as wt,N4 as x,_ as xn,L as xt,k4 as y,le as yn,P as yt,o1 as z,Sg as zt};