pine2profit 0.0.0-stage → 1.1.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 (63) hide show
  1. package/README.md +243 -2
  2. package/build/.gitkeep +0 -0
  3. package/build/index.cjs +1152 -0
  4. package/build/index.mjs +1142 -0
  5. package/build/modules/frontend/build/.nojekyll +0 -0
  6. package/build/modules/frontend/build/404/index.html +1 -0
  7. package/build/modules/frontend/build/404.html +1 -0
  8. package/build/modules/frontend/build/_next/static/_d4V5OqT091alEqu95MT1/_buildManifest.js +1 -0
  9. package/build/modules/frontend/build/_next/static/_d4V5OqT091alEqu95MT1/_ssgManifest.js +1 -0
  10. package/build/modules/frontend/build/_next/static/chunks/11.78c5bec5897e1148.js +1 -0
  11. package/build/modules/frontend/build/_next/static/chunks/195.64632be71175c993.js +63 -0
  12. package/build/modules/frontend/build/_next/static/chunks/204.008bcbcf48844ee2.js +1 -0
  13. package/build/modules/frontend/build/_next/static/chunks/255-da04dc9178303a31.js +1 -0
  14. package/build/modules/frontend/build/_next/static/chunks/2738385b.306f7750ad5b8be4.js +372 -0
  15. package/build/modules/frontend/build/_next/static/chunks/338-31711140cb6d61e5.js +1 -0
  16. package/build/modules/frontend/build/_next/static/chunks/4bd1b696-c023c6e3521b1417.js +1 -0
  17. package/build/modules/frontend/build/_next/static/chunks/50e49f97.75feacc2b3cc7709.js +433 -0
  18. package/build/modules/frontend/build/_next/static/chunks/554.dd4ac9a0aff9b782.js +1 -0
  19. package/build/modules/frontend/build/_next/static/chunks/570-33c81efca66c4bc9.js +3 -0
  20. package/build/modules/frontend/build/_next/static/chunks/5957d0c3.7b96612772854e2d.js +2 -0
  21. package/build/modules/frontend/build/_next/static/chunks/619-f09bc47e24909021.js +1 -0
  22. package/build/modules/frontend/build/_next/static/chunks/7589b812.60f2b16513f3aa42.js +1 -0
  23. package/build/modules/frontend/build/_next/static/chunks/771.5c62ba94f930669e.js +1 -0
  24. package/build/modules/frontend/build/_next/static/chunks/796.4b04b2b64c066b03.js +1 -0
  25. package/build/modules/frontend/build/_next/static/chunks/897-b727cc7229802490.js +1 -0
  26. package/build/modules/frontend/build/_next/static/chunks/app/_not-found/page-b6d9300903c2ab41.js +1 -0
  27. package/build/modules/frontend/build/_next/static/chunks/app/layout-0da8bd54f47c9e1b.js +1 -0
  28. package/build/modules/frontend/build/_next/static/chunks/app/page-7ab911a70ef48cfe.js +1 -0
  29. package/build/modules/frontend/build/_next/static/chunks/app/run/page-42836fc705c46a59.js +1 -0
  30. package/build/modules/frontend/build/_next/static/chunks/c525c9ef.018edb9552a70fc2.js +143 -0
  31. package/build/modules/frontend/build/_next/static/chunks/e1865c21-8d63eb0f5b25cb0c.js +1 -0
  32. package/build/modules/frontend/build/_next/static/chunks/framework-28b60818f5cffd83.js +1 -0
  33. package/build/modules/frontend/build/_next/static/chunks/main-45ecedd1f28e3a74.js +1 -0
  34. package/build/modules/frontend/build/_next/static/chunks/main-app-4ff0bbe1b367fcb5.js +1 -0
  35. package/build/modules/frontend/build/_next/static/chunks/pages/_app-7d307437aca18ad4.js +1 -0
  36. package/build/modules/frontend/build/_next/static/chunks/pages/_error-cb2a52f75f2162e2.js +1 -0
  37. package/build/modules/frontend/build/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  38. package/build/modules/frontend/build/_next/static/chunks/webpack-bb5ccf34ea47f1d7.js +1 -0
  39. package/build/modules/frontend/build/_next/static/css/91363587ff8467b5.css +1 -0
  40. package/build/modules/frontend/build/_next/static/media/29b98dbfba401fa9-s.p.woff2 +0 -0
  41. package/build/modules/frontend/build/_next/static/media/313510e2713fb214-s.p.woff2 +0 -0
  42. package/build/modules/frontend/build/_next/static/media/558ca1a6aa3cb55e-s.p.woff2 +0 -0
  43. package/build/modules/frontend/build/_next/static/media/64d784ea54a4acde-s.woff2 +0 -0
  44. package/build/modules/frontend/build/_next/static/media/6d831b18ae5b01dc-s.woff2 +0 -0
  45. package/build/modules/frontend/build/_next/static/media/8048a25e80cc4179-s.woff2 +0 -0
  46. package/build/modules/frontend/build/_next/static/media/851c4691abdf3def-s.woff2 +0 -0
  47. package/build/modules/frontend/build/_next/static/media/87bc17f7c8b98e48-s.woff2 +0 -0
  48. package/build/modules/frontend/build/_next/static/media/982ceffe7b733b3b-s.p.woff2 +0 -0
  49. package/build/modules/frontend/build/_next/static/media/a6c19694cd327cd4-s.woff2 +0 -0
  50. package/build/modules/frontend/build/_next/static/media/a8a8dd7277bab4cf-s.woff2 +0 -0
  51. package/build/modules/frontend/build/_next/static/media/ac0e76ddaeeb7981-s.woff2 +0 -0
  52. package/build/modules/frontend/build/_next/static/media/b8bfb68ab9ab617c-s.woff2 +0 -0
  53. package/build/modules/frontend/build/_next/static/media/d76fe899475ae4d7-s.woff2 +0 -0
  54. package/build/modules/frontend/build/_next/static/media/e546cf32c9d4702c-s.woff2 +0 -0
  55. package/build/modules/frontend/build/_next/static/media/edc640959b0c7826-s.woff2 +0 -0
  56. package/build/modules/frontend/build/_next/static/media/ff71da380fbe67dd-s.woff2 +0 -0
  57. package/build/modules/frontend/build/icon.svg +1 -0
  58. package/build/modules/frontend/build/index.html +1 -0
  59. package/build/modules/frontend/build/index.txt +23 -0
  60. package/build/modules/frontend/build/run/index.html +1 -0
  61. package/build/modules/frontend/build/run/index.txt +23 -0
  62. package/package.json +93 -4
  63. package/types.d.ts +124 -0
@@ -0,0 +1,433 @@
1
+ "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[902],{9338:(e,t,i)=>{let r,n,s,a,o,l;i.d(t,{C1:()=>u2,TU:()=>uX,k6:()=>u5,ob:()=>o5,yD:()=>dM});var h=i(5704),c=Object.defineProperty;class p{constructor(e,t,i){for(let i in this._definition=e,this.context=t,((e,t,i)=>((e,t,i)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_udt"),e)this[i]=e[i];this._udt=i}get __def__(){return this._definition}copy(){return new p(this._fieldValues(),this.context,this._udt)}_fieldValues(){let e=new Set([...this._udt?._definitionKeys??[],...Object.keys(this._definition)]),t={};for(let i of e)Object.prototype.hasOwnProperty.call(this,i)&&(t[i]=this[i]);return t}toString(){let e={};for(let t in this.__def__){let i=this[t];null==i||"object"!=typeof i||"function"!=typeof i.toString||i instanceof Array?e[t]=i:e[t]=i.toString()}try{return JSON.stringify(e)}catch{return"{"+Object.keys(e).map(t=>`"${t}":${String(e[t])}`).join(",")+"}"}}}var u=Object.defineProperty,d=(e,t,i)=>((e,t,i)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class m{constructor(e,t=0){this.data=e,this.offset=t,d(this,"beforeStart",NaN),d(this,"varip")}get(e){(null==e||Number.isNaN(e))&&(e=0);let t=this.offset+e;Number.isInteger(t)||(t=Math.trunc(t));let i=this.data.length-1-t;return i<0?this.beforeStart:i>=this.data.length?NaN:this.data[i]}set(e,t){let i=this.data.length-1-(this.offset+e);i>=0&&i<this.data.length&&(this.data[i]=t)}get length(){return this.data.length}toArray(){return this.data}static from(e){if(e instanceof m)return e;if(Array.isArray(e))return new m(e);if(null!=e&&"object"==typeof e&&"__value"in e){let t=e.__value;if(t instanceof m)return t;if(null===t||"object"!=typeof t)return new m([t])}return new m([e])}}let f={aqua:"#00BCD4",black:"#363A45",blue:"#2962FF",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#F23645",silver:"#B2B5BE",teal:"#089981",white:"#FFFFFF",yellow:"#FDD835"};function y(e){if("string"!=typeof e)return null;let t=e.trim(),i=t.startsWith("color.")?t.slice(6):t;return Object.prototype.hasOwnProperty.call(f,i)&&(t=f[i]),function(e){if(!e||"string"!=typeof e)return null;if(e.startsWith("#")){let t=e.slice(1);return 6===t.length?[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),1]:8===t.length?[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),parseInt(t.slice(6,8),16)/255]:null}let t=e.match(/rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\s*\)/);return t?[parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4]?parseFloat(t[4]):1]:null}(t)}function _(e,t,i,r){let n=e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(i)}${n(255*r)}`.toUpperCase()}function g(e){return"function"==typeof e&&(e=e()),e&&"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get&&(e=e.get(0)),e}let x=e=>null==e||"number"==typeof e&&isNaN(e),b=(e,t,i)=>Math.min(i,Math.max(t,e)),v="#00000000";function w(e){if(x(e=g(e)))return[0,0,0,0];let t=y(e);return t?[t[0],t[1],t[2],Math.round(255*t[3])/255]:null}class S{constructor(e){this.context=e}any(e){let t=m.from(e).get(0);return"number"==typeof t&&isNaN(t)?null:t}param(e,t=0){return m.from(e).get(t)}new(e,t){if(e=g(e),void 0===(t=g(t))||(t=x(t)?100:b(Math.trunc(t),0,100),x(e)&&(e="#000000"),"string"!=typeof e))return e;let i=Math.round(255*(100-t)/100).toString(16).padStart(2,"0").toUpperCase();if(e.startsWith("#")){let t=e.slice(1);return`#${8===t.length?t.slice(0,6):t}${i}`}let r=f[e];if(r)return`#${r.slice(1)}${i}`;let n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);if(n){let[e,t,r]=[n[1],n[2],n[3]].map(e=>parseInt(e).toString(16).padStart(2,"0"));return`#${e}${t}${r}${i}`}return`rgba(${e}, ${(100-t)/100})`}rgb(e,t,i,r){let n=e=>x(e=g(e))?0:b(Math.trunc(e),0,255),[s,a,o]=[n(e),n(t),n(i)];if(void 0===(r=g(r)))return`rgb(${s}, ${a}, ${o})`;let l=x(r)?100:b(r,0,100);return`rgba(${s}, ${a}, ${o}, ${(100-l)/100})`}from_gradient(e,t,i,r,n){if(e=g(e),t=g(t),i=g(i),x(e)||x(t)||x(i)||i===t)return v;if(i<t)return x(r=g(r))?v:r;let s=w(r)??[0,0,0,0],a=w(n)??[0,0,0,0],o=1-b((e-t)/(i-t),0,1),l=1-o,h=s[3]*o+a[3]*l;if(0===h)return v;let c=e=>Math.trunc((s[e]*s[3]*o+a[e]*a[3]*l)/h);return function(e,t,i,r){let n=Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0"),s=Math.round(Math.max(0,Math.min(255,t))).toString(16).padStart(2,"0"),a=Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0");if(r>=1)return`#${n}${s}${a}`.toUpperCase();let o=Math.round(Math.max(0,Math.min(255,255*r))).toString(16).padStart(2,"0");return`#${n}${s}${a}${o}`.toUpperCase()}(c(0),c(1),c(2),Math.trunc(255*h)/255)}r(e){return w(e)?.[0]??NaN}g(e){return w(e)?.[1]??NaN}b(e){return w(e)?.[2]??NaN}t(e){let t=w(e);return t?Math.round((1-t[3])*100):NaN}aqua(){return f.aqua}black(){return f.black}blue(){return f.blue}fuchsia(){return f.fuchsia}gray(){return f.gray}green(){return f.green}lime(){return f.lime}maroon(){return f.maroon}navy(){return f.navy}olive(){return f.olive}orange(){return f.orange}purple(){return f.purple}red(){return f.red}silver(){return f.silver}teal(){return f.teal}white(){return f.white}yellow(){return f.yellow}}var E=(e=>(e[e.ascending=1]="ascending",e[e.descending=0]="descending",e))(E||{}),N=(e=>(e.AED="AED",e.ARS="ARS",e.AUD="AUD",e.BDT="BDT",e.BHD="BHD",e.BRL="BRL",e.BTC="BTC",e.CAD="CAD",e.CHF="CHF",e.CLP="CLP",e.CNY="CNY",e.COP="COP",e.CZK="CZK",e.DKK="DKK",e.EGP="EGP",e.ETH="ETH",e.EUR="EUR",e.GBP="GBP",e.HKD="HKD",e.HUF="HUF",e.IDR="IDR",e.ILS="ILS",e.INR="INR",e.ISK="ISK",e.JPY="JPY",e.KES="KES",e.KRW="KRW",e.KWD="KWD",e.LKR="LKR",e.MAD="MAD",e.MXN="MXN",e.MYR="MYR",e.NGN="NGN",e.NOK="NOK",e.NONE="NONE",e.NZD="NZD",e.PEN="PEN",e.PHP="PHP",e.PKR="PKR",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RSD="RSD",e.RUB="RUB",e.SAR="SAR",e.SEK="SEK",e.SGD="SGD",e.THB="THB",e.TND="TND",e.TRY="TRY",e.TWD="TWD",e.USD="USD",e.USDT="USDT",e.VES="VES",e.VND="VND",e.ZAR="ZAR",e))(N||{}),T=(e=>(e[e.sunday=1]="sunday",e[e.monday=2]="monday",e[e.tuesday=3]="tuesday",e[e.wednesday=4]="wednesday",e[e.thursday=5]="thursday",e[e.friday=6]="friday",e[e.saturday=7]="saturday",e))(T||{}),k=(e=>(e.all="all",e.data_window="data_window",e.none="none",e.pane="pane",e.price_scale="price_scale",e.status_line="status_line",e))(k||{});let A=["pane","data_window","status_line","price_scale"],I=[...A,"all","none"];function C(e){let t=new Set;if("string"!=typeof e)return t;for(let i=0;i<e.length;){let r=I.find(t=>e.startsWith(t,i));if(!r)break;if("all"===r)return new Set(A);"none"!==r&&t.add(r),i+=r.length}return t}function M(e){let t=A.filter(t=>e.has(t));return t.length===A.length?"all":0===t.length?"none":t.join("")}function P(e,t){return M(new Set([...C(e),...C(t)]))}function D(e,t){let i=C(e);for(let e of C(t))i.delete(e);return M(i)}var R=(e=>(e.flag="shape_flag",e.arrowdown="shape_arrow_down",e.arrowup="shape_arrow_up",e.circle="shape_circle",e.cross="shape_cross",e.diamond="shape_diamond",e.labeldown="shape_label_down",e.labelup="shape_label_up",e.square="shape_square",e.triangledown="shape_triangle_down",e.triangleup="shape_triangle_up",e.xcross="shape_xcross",e))(R||{}),O=(e=>(e.abovebar="AboveBar",e.belowbar="BelowBar",e.absolute="Absolute",e.bottom="Bottom",e.top="Top",e))(O||{}),j=(e=>(e.auto="auto",e.tiny="tiny",e.small="small",e.normal="normal",e.large="large",e.huge="huge",e))(j||{}),V=(e=>(e.inherit="inherit",e.mintick="mintick",e.percent="percent",e.price="price",e.volume="volume",e))(V||{}),$=(e=>(e.linestyle_dashed="linestyle_dashed",e.linestyle_dotted="linestyle_dotted",e.linestyle_solid="linestyle_solid",e.style_area="style_area",e.style_areabr="style_areabr",e.style_circles="style_circles",e.style_columns="style_columns",e.style_cross="style_cross",e.style_histogram="style_histogram",e.style_line="style_line",e.style_linebr="style_linebr",e.style_stepline="style_stepline",e.style_stepline_diamond="style_stepline_diamond",e.style_steplinebr="style_steplinebr",e))($||{}),L=(e=>(e.gaps_on="gaps_on",e.gaps_off="gaps_off",e.lookahead_on="lookahead_on",e.lookahead_off="lookahead_off",e))(L||{}),B=(e=>(e.bar_index="bi",e.bar_time="bt",e))(B||{}),F=(e=>(e.price="pr",e.abovebar="ab",e.belowbar="bl",e))(F||{}),q=(e=>(e.left="l",e.right="r",e.both="b",e.none="n",e))(q||{}),z=(e=>(e.align_bottom="bottom",e.align_top="top",e.align_left="left",e.align_center="center",e.align_right="right",e.wrap_auto="auto",e.wrap_none="none",e.format_bold="bold",e.format_italic="italic",e.format_none="none",e))(z||{}),U=(e=>(e.family_default="default",e.family_monospace="monospace",e))(U||{}),W=(e=>(e.none="none",e.splits="splits",e.dividends="dividends",e))(W||{}),K=(e=>(e.inherit="inherit",e.off="off",e.on="on",e))(K||{}),G=(e=>(e.actual="earnings_actual",e.estimate="earnings_estimate",e.standardized="earnings_standardized",e.future_eps="earnings_future_eps",e.future_period_end_time="earnings_future_period_end_time",e.future_revenue="earnings_future_revenue",e.future_time="earnings_future_time",e))(G||{}),H=(e=>(e.gross="dividends_gross",e.net="dividends_net",e.future_amount="dividends_future_amount",e.future_ex_date="dividends_future_ex_date",e.future_pay_date="dividends_future_pay_date",e))(H||{}),Y=(e=>(e.denominator="splits_denominator",e.numerator="splits_numerator",e))(Y||{}),Z=(e=>(e.top_left="top_left",e.top_center="top_center",e.top_right="top_right",e.middle_left="middle_left",e.middle_center="middle_center",e.middle_right="middle_right",e.bottom_left="bottom_left",e.bottom_center="bottom_center",e.bottom_right="bottom_right",e))(Z||{}),J=(e=>(e.left="left",e.none="none",e.right="right",e))(J||{}),Q=(e=>(e.inherit="inherit",e.off="off",e.on="on",e))(Q||{});let X={order:E,currency:N,dayofweek:T,display:{...k,__union:P,__minus:D},shape:R,location:O,size:j,format:V,barmerge:L,xloc:B,yloc:F,extend:q,text:z,font:U,adjustment:W,backadjustment:K,earnings:G,dividends:H,splits:Y,position:Z,scale:J,settlement_as_close:Q};var ee=Object.freeze({__proto__:null,order:E,currency:N,dayofweek:T,display:k,displayUnion:P,displayMinus:D,shape:R,location:O,size:j,format:V,plot:$,barmerge:L,xloc:B,yloc:F,extend:q,text:z,font:U,adjustment:W,backadjustment:K,earnings:G,dividends:H,splits:Y,position:Z,scale:J,settlement_as_close:Q,default:X}),et=Object.defineProperty;class ei extends Error{constructor(e,t){super(e),((e,t,i)=>((e,t,i)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"method"),this.name="PineRuntimeError",this.method=t}}function er(e){return null==e||"number"==typeof e&&isNaN(e)}let en=/^(#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?|rgba?\(.*\))$/;function es(e){if("string"!=typeof e||!en.test(e))return null;let t=y(e);return t?_(t[0],t[1],t[2],t[3]):null}function ea(e,t){if("number"==typeof e&&"number"==typeof t)return 1e-10>=Math.abs(e-t);if(e===t)return!0;if("string"==typeof e&&"string"==typeof t){let i=es(e);return null!==i&&i===es(t)}return!1}function eo(e,t){if(e.type===eR.string){let e=er(t)?"":t;return t=>ea(er(t)?"":t,e)}return er(t)?e.type!==eR.color||e.context?.pineVersion>=6?()=>!1:er:e=>!er(e)&&ea(e,t)}function el(e,t){let i,r;for(let t=0;t<e.length;t++)if(e[t]instanceof p){i=e[t];break}return i?(r="string"==typeof t?t:(i._udt?._definitionKeys??Object.keys(i.__def__))[t??0],e=>e instanceof p?e[r]:NaN):null}function eh(e,t,i){let r=er(e),n=er(t);return r||n?r&&n?0:(r?1:-1)*(i?-1:1):i?e<t?-1:+(e>t):e-t}function ec(e,t=E.ascending){let i=e.some(e=>"string"==typeof e),r=e.map((e,t)=>t);return r.sort((t,r)=>eh(e[t],e[r],i)||t-r),t!==E.ascending&&r.reverse(),r}function ep(e,t,i){throw new ei(`Index ${e} is out of bounds, array size is ${t}.`,i)}function eu(e){throw new ei(`Cannot call \`${e}()\` if array is empty.`,`array.${e}`)}function ed(e,t){if(e<0||e>100)throw new ei(`Invalid value of the 'percentage' argument (${e}) in the '${t}' function. It must be in the range [0..100].`,t)}function em(e){return"number"==typeof e?Number.isInteger(e)?eR.int:eR.float:"string"==typeof e?eR.string:"boolean"==typeof e?eR.bool:eR.any}function ef(e,t){if(void 0===e||"number"==typeof e&&isNaN(e)||t===eR.any)return!0;switch(t){case eR.int:return Number.isInteger(e)||isNaN(e);case eR.float:return"number"==typeof e;case eR.string:return"string"==typeof e;case eR.bool:return"boolean"==typeof e;case eR.box:case eR.label:case eR.line:case eR.linefill:case eR.table:case eR.color:return null===e||"object"==typeof e||"string"==typeof e}return!1}function ey(e,t=0){let i=String(e).match(/^(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/);if(!i)return[String(e),""];let r=i[1]+(i[2]??""),n=i[1].length+Number(i[3]??0)+t;return n<=0&&(r="0".repeat(1-n)+r,n=1),n>r.length&&(r+="0".repeat(n-r.length)),[r.slice(0,n),r.slice(n)]}function e_(e,t,i,r,n){let s;if(i.length<=r)return[t,i];let a=t+i.slice(0,r),o=Number(i[r]),l=i.slice(r+1);if(5!==o||/[1-9]/.test(l))s=o>=5;else if("halfUp"===n)s=!0;else if(/[1-9]/.test(a)){let r=function(e,t,i){let r=new DataView(new ArrayBuffer(8));r.setFloat64(0,e);let n=r.getBigUint64(0),s=Number(n>>52n&2047n),a=n&(1n<<52n)-1n,o;0===s?o=-1074:(a|=1n<<52n,o=s-1075);let l=a*10n**BigInt(i.length),h=BigInt(t+i||"0");return o>=0?l<<=BigInt(o):h<<=BigInt(-o),l>h?1:l<h?-1:0}(e,t,i);s=r>0||0===r&&Number(a[a.length-1])%2==1}else s=!1;if(s){let e=a.split(""),t=e.length-1;for(;t>=0&&"9"===e[t];)e[t--]="0";t>=0?e[t]=String(Number(e[t])+1):e.unshift("1"),a=e.join("")}let h=a.length-r;return[a.slice(0,h),a.slice(h)]}function eg(e,t,i){if(!Number.isFinite(e))return String(e);let{prefix:r,number:n,suffix:s,percent:a}=function(e){let t=0,i=!1,r=r=>{let n="",s=!1;for(;t<e.length;){let a=e[t];if("'"===a){if("'"===e[t+1]){n+="'",t+=2;continue}s=!s,t++;continue}if(!s&&r(a))break;s||"%"!==a||(i=!0),n+=a,t++}return n},n=r(e=>/[#0,.]/.test(e)),s="";for(;t<e.length&&/[#0,.]/.test(e[t]);)s+=e[t++];return{prefix:n,number:s,suffix:r(()=>!1),percent:i}}(t),[o,l=""]=n.split(".");if(!/[#0]/.test(n)){let[t]=e_(Math.abs(e),...ey(Math.abs(e)),0,i);return(e<0?"-":"")+r+s+(t.replace(/^0+(?=\d)/,"")||"0")}let h=a?100:1,c=(o.match(/0/g)??[]).length,p=o.lastIndexOf(","),u=p>=0?o.length-p-1:0,d=(l.match(/0/g)??[]).length,m=l.length,f=Math.abs(e),[y,_]=ey(f,2*(100===h)),[g,x]=e_(f*h,y,_,m,i),b=!/[1-9]/.test(g+x),v=g.replace(/^0+/,""),w=x.padEnd(m,"0");for(;w.length>d&&w.endsWith("0");)w=w.slice(0,-1);return v.length<c&&(v=v.padStart(c,"0")),v||0!==d||(v="0"),u>0&&(v=v.replace(RegExp(`\\B(?=(\\d{${u}})+(?!\\d))`,"g"),",")),(e<0&&("halfEven"===i||!b)?"-":"")+r+v+(w?"."+w:"")+s}function ex(e){if(!Number.isFinite(e))return String(e);let t=Math.abs(e),i=e<0?"-":"";if(t>=1e21){let[e,r]=t.toExponential().split("e"),[n,s]=e_(t,e.split(".")[0],e.split(".")[1]??"",10,"halfUp"),a=Number(r);return n.length>1&&(s=n.slice(1)+s,n=n[0],a++),i+n+((s=s.replace(/0+$/,""))?"."+s:"")+"E"+a}let[r,n]=e_(t,...ey(t),10,"halfEven"),s=n.replace(/0+$/,""),a=r.replace(/^0+(?=\d)/,"");return/[1-9]/.test(a+s)?i+a+(s?"."+s:""):"0"}let eb=[[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"K"]],ev=e=>null==e||"number"==typeof e&&Number.isNaN(e);function ew(e,t,i){return"string"===e.type?ev(t)?"":String(t):"number"==typeof t?i(t):ev(t)?"NaN":String(t)}function eS(e){let t="float"===e.type||"int"!==e.type&&e.array.some(e=>"number"==typeof e&&!Number.isInteger(e)&&!Number.isNaN(e));return Array.from(e.array,i=>ew(e,i,e=>Number.isNaN(e)?"NaN":t?function(e){if(Number.isNaN(e))return"NaN";if(!Number.isFinite(e))return e>0?"Infinity":"-Infinity";if(0===e)return"0.0";let t=Math.abs(e),i=e<0?"-":"";if(t>=.001&&t<1e7){let[e,r]=ey(t);return i+e+"."+(r||"0")}let[r,n]=t.toExponential().split("e"),[s,a]=r.split(".");return i+s+"."+(a||"0")+"E"+Number(n)}(e):String(e)))}function eE(e){if("string"!=typeof e||!/^(0|[1-9]\d*)$/.test(e))return -1;let t=Number(e);return t<=0xfffffffe?t:-1}function eN(e,t,i=0){if(!t)return e;let r=e.length;for(;r>0&&void 0===e[r-1];)r--;let n=e[r-1];if(null===n||"object"!=typeof n||Object.getPrototypeOf(n)!==Object.prototype)return e;let s=Object.keys(n);if(!s.some(e=>t.indexOf(e)>=i))return e;let a=e.slice(0,r-1);for(let e of s){let r=t.indexOf(e)-i;r>=0&&(a[r]=n[e]instanceof m?n[e].get(0):n[e])}return a}function eT(e,t){return t?(...i)=>e(...eN(i,t)):e}let ek=["id"],eA=e=>["id",e],eI={abs:ek,avg:ek,binary_search:["id","val","sort_field"],binary_search_leftmost:["id","val","sort_field"],binary_search_rightmost:["id","val","sort_field"],clear:ek,concat:["id1","id2"],copy:ek,covariance:["id1","id2","biased"],every:ek,fill:["id","value","index_from","index_to"],first:ek,get:eA("index"),includes:eA("value"),indexof:eA("value"),insert:["id","index","value"],join:eA("separator"),last:ek,lastindexof:eA("value"),max:eA("nth"),median:ek,min:eA("nth"),mode:ek,percentile_linear_interpolation:eA("percentage"),percentile_nearest_rank:eA("percentage"),percentrank:eA("index"),pop:ek,push:eA("value"),range:ek,remove:eA("index"),reverse:ek,set:["id","index","value"],shift:ek,size:ek,slice:["id","index_from","index_to"],some:ek,sort:["id","order","sort_field"],sort_indices:["id","order","sort_field"],standardize:ek,stdev:eA("biased"),sum:ek,unshift:eA("value"),variance:eA("biased")},eC={add_col:["id","column","array_id"],add_row:["id","row","array_id"],avg:ek,col:eA("column"),columns:ek,concat:["id1","id2"],copy:ek,det:ek,diff:["id1","id2"],eigenvalues:ek,eigenvectors:ek,elements_count:ek,fill:["id","value","from_row","to_row","from_column","to_column"],get:["id","row","column"],inv:ek,is_antidiagonal:ek,is_antisymmetric:ek,is_binary:ek,is_diagonal:ek,is_identity:ek,is_square:ek,is_stochastic:ek,is_symmetric:ek,is_triangular:ek,is_zero:ek,kron:["id1","id2"],max:ek,median:ek,min:ek,mode:ek,mult:["id1","id2"],pinv:ek,pow:eA("power"),rank:ek,remove_col:eA("column"),remove_row:eA("row"),reshape:["id","rows","columns"],reverse:ek,row:eA("row"),rows:ek,set:["id","row","column","value"],sort:["id","column","order","sort_field"],submatrix:["id","from_row","to_row","from_column","to_column"],sum:["id1","id2"],swap_columns:["id","column1","column2"],swap_rows:["id","row1","row2"],trace:ek,transpose:ek},eM={clear:ek,contains:eA("key"),copy:ek,get:eA("key"),keys:ek,put:["id","key","value"],put_all:["id","id2"],remove:eA("key"),size:ek,values:ek};var eP=Object.defineProperty,eD=(e,t,i)=>((e,t,i)=>t in e?eP(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i),eR=(e=>(e.any="",e.box="box",e.bool="bool",e.color="color",e.float="float",e.int="int",e.label="label",e.line="line",e.linefill="linefill",e.string="string",e.table="table",e))(eR||{});class eO{constructor(e,t,i){var r,n,s,a,o,l,h,c,p,u,d,m,f;this.array=e,this.type=t,this.context=i,eD(this,"_abs"),eD(this,"_avg"),eD(this,"_binary_search"),eD(this,"_binary_search_leftmost"),eD(this,"_binary_search_rightmost"),eD(this,"_clear"),eD(this,"_concat"),eD(this,"_copy"),eD(this,"_covariance"),eD(this,"_every"),eD(this,"_fill"),eD(this,"_first"),eD(this,"_get"),eD(this,"_includes"),eD(this,"_indexof"),eD(this,"_insert"),eD(this,"_join"),eD(this,"_last"),eD(this,"_lastindexof"),eD(this,"_max"),eD(this,"_median"),eD(this,"_min"),eD(this,"_mode"),eD(this,"_percentile_linear_interpolation"),eD(this,"_percentile_nearest_rank"),eD(this,"_percentrank"),eD(this,"_pop"),eD(this,"_push"),eD(this,"_range"),eD(this,"_remove"),eD(this,"_reverse"),eD(this,"_set"),eD(this,"_shift"),eD(this,"_size"),eD(this,"_slice"),eD(this,"_some"),eD(this,"_sort"),eD(this,"_sort_indices"),eD(this,"_standardize"),eD(this,"_stdev"),eD(this,"_sum"),eD(this,"_unshift"),eD(this,"_variance"),this._abs=(r=this.context,e=>new eO(e.array.map(e=>Math.abs(e)),e.type,r)),this._avg=(n=this.context,e=>{let t=0,i=0;for(let r of e.array){let e=Number(r);isNaN(e)||(i++,t+=(e-t)/i)}return 0===i?NaN:n.precision(t)}),this._binary_search=(this.context,(e,t,i)=>{let r=e.array,n=el(r,i)??(e=>e),s=0,a=r.length-1;for(;s<=a;){let e=Math.floor((s+a)/2),i=n(r[e]);if(i===t)return e;i<t?s=e+1:a=e-1}return -1}),this._binary_search_leftmost=(this.context,(e,t,i)=>{let r=e.array,n=el(r,i)??(e=>e),s=0,a=r.length;for(;s<a;){let e=Math.floor((s+a)/2);n(r[e])<t?s=e+1:a=e}return s<r.length&&n(r[s])===t?s:Math.max(s-1,0)}),this._binary_search_rightmost=(this.context,(e,t,i)=>{let r=e.array,n=el(r,i)??(e=>e),s=0,a=r.length;for(;s<a;){let e=Math.floor((s+a)/2);n(r[e])<=t?s=e+1:a=e}return s>0&&n(r[s-1])===t?s-1:s}),this._clear=(this.context,e=>{e.array.length=0}),this._concat=(this.context,(e,t)=>(e.array.push(...t.array),e)),this._copy=(s=this.context,e=>new eO([...e.array],e.type,s)),this._covariance=(a=this.context,(e,t,i=!0)=>{let r=e.array,n=t.array;if(r.length!==n.length)return NaN;let s=0,o=0,l=0,h=[];for(let e=0;e<r.length;e++){let t=Number(r[e]),i=Number(n[e]);isNaN(t)||null==t||isNaN(i)||null==i||(s+=t,o+=i,l++,h.push(e))}if(0===l)return NaN;let c=s/l,p=o/l,u=0;for(let e of h)u+=(Number(r[e])-c)*(Number(n[e])-p);let d=i?l:l-1;return d<=0?NaN:a.precision(u/d)}),this._every=(this.context,e=>0!==e.array.length&&e.array.every(e=>!isNaN(e)&&e)),this._fill=(o=this.context,(e,t,i=0,r)=>{let n=e.array.length,s=er(i)?0:i,a=void 0===r||er(r)?n:r;if((s<0||s>=n)&&ep(s,n,"array.fill"),(a<0||a>n)&&ep(a,n,"array.fill"),!ef(t,e.type))throw Error(`Cannot call 'array.fill' with argument 'value'='${t}'. An argument of 'literal ${typeof t}' type was used but a '${e.type}' is expected.`);let l="number"==typeof t?o.precision(t):t;for(let t=s;t<a;t++)e.array[t]=l}),this._first=(this.context,e=>(0===e.array.length&&eu("first"),e.array[0])),this._get=(this.context,(e,t)=>{let i=t<0?e.array.length+t:t;if(i<0||i>=e.array.length)throw new ei(`Index ${t} is out of bounds, array size is ${e.array.length}.`,"array.get");return e.array[i]}),this._includes=(this.context,(e,t)=>e.array.some(eo(e,t))),this._indexof=(this.context,(e,t)=>e.array.findIndex(eo(e,t))),this._insert=(this.context,(e,t,i)=>{if(!ef(i,e.type))throw Error(`Cannot call 'array.insert' with argument 'value'='${i}'. An argument of 'literal ${typeof i}' type was used but a '${e.type}' is expected.`);let r=t<0?e.array.length+t:t;if(r<0||r>e.array.length)throw new ei(`Index ${t} is out of bounds, array size is ${e.array.length}.`,"array.insert");e.array.splice(r,0,i)}),this._join=(this.context,(e,t="")=>eS(e).join(t)),this._last=(this.context,e=>(0===e.array.length&&eu("last"),e.array[e.array.length-1])),this._lastindexof=(this.context,(e,t)=>{let i=e.array,r=eo(e,t);for(let e=i.length-1;e>=0;e--)if(r(i[e]))return e;return -1}),this._max=function(e){return(t,i=0)=>{let r=t.array,n=r.length;if(0===n)return e.NA;if(er(i)&&(i=0),(i<0||i>=n)&&ep(i,n,"array.max"),0===i){let e=NaN;for(let t=0;t<n;t++){let i=r[t];er(i)||i<=e||(e=i)}return e}let s=r.filter(e=>!er(e)).sort((e,t)=>t-e);return s.length?s[Math.min(i,s.length-1)]:e.NA}}(this.context),this._median=(this.context,e=>{let t=e.array.filter(e=>!er(e)).sort((e,t)=>e-t);if(0===t.length)return NaN;let i=Math.floor(t.length/2);return t.length%2!=0?t[i]:(t[i-1]+t[i])/2}),this._min=function(e){return(t,i=0)=>{let r=t.array,n=r.length;if(0===n)return e.NA;if(er(i)&&(i=0),(i<0||i>=n)&&ep(i,n,"array.min"),0===i){let e=NaN;for(let t=0;t<n;t++){let i=r[t];er(i)||i>=e||(e=i)}return e}let s=r.filter(e=>!er(e)).sort((e,t)=>e-t);return s.length?s[Math.min(i,s.length-1)]:e.NA}}(this.context),this._mode=(this.context,e=>{let t=new Map,i=0;for(let r of e.array){if(er(r))continue;let e=(t.get(r)||0)+1;t.set(r,e),e>i&&(i=e)}let r=[];for(let[e,n]of t)n===i&&r.push(e);return r.sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:"string"==typeof e&&"string"==typeof t?e<t?-1:+(e>t):0),r.length?r[0]:NaN}),this._percentile_linear_interpolation=function(e){return(t,i)=>{if(er(i))return NaN;ed(i,"array.percentile_linear_interpolation");let r=t.array,n=r.length;if(0===n)return NaN;let s=[];for(let e=0;e<n;e++){let t=r[e];er(t)||s.push(Number(t))}let a=s.length<n;for(s.sort((e,t)=>e-t);s.length<n;)s.push(NaN);let o=i*n/100-.5;if(o<=0)return e.precision(s[0]);if(o>=n-1)return e.precision(s[n-1]);let l=Math.floor(o),h=o-l;return 0===h?e.precision(s[l]):a?NaN:e.precision(s[l]*(1-h)+s[l+1]*h)}}(this.context),this._percentile_nearest_rank=(this.context,(e,t)=>{if(er(t))return NaN;ed(t,"array.percentile_nearest_rank");let i=e.array,r=i.length;if(0===r)return NaN;let n=[];for(let e=0;e<r;e++){let t=Number(i[e]);isNaN(t)||null==t||n.push(t)}if(0===n.length)return NaN;n.sort((e,t)=>e-t);let s=Math.ceil(t/100*r);return s<=0?n[0]:s>n.length?NaN:n[s-1]}),this._percentrank=(this.context,(e,t)=>{let i=e.array.length;if(0===i)return NaN;(t<0||t>=i)&&ep(t,i,"array.percentrank");let r=e.array[Math.floor(t)];if(er(r))return NaN;let n=0;for(let t of e.array)!er(t)&&t<=r&&n++;let s=i-1;return s<=0?NaN:(n-1)/s*100}),this._pop=(this.context,e=>(0===e.array.length&&eu("pop"),e.array.pop())),this._push=(l=this.context,(e,t)=>{if(!ef(t,e.type))throw Error(`Cannot call 'array.push' with argument 'value'='${t}'. An argument of 'literal ${typeof t}' type was used but a '${e.type}' is expected.`);e.array.push("number"==typeof t?l.precision(t):t)}),this._range=function(e){return t=>e.precision(e.pine.array.max(t)-e.pine.array.min(t))}(this.context),this._remove=(this.context,(e,t)=>{let i=t<0?e.array.length+t:t;if(i<0||i>=e.array.length)throw new ei(`Index ${t} is out of bounds, array size is ${e.array.length}.`,"array.remove");return e.array.splice(i,1)[0]}),this._reverse=(this.context,e=>{e.array.reverse()}),this._set=(h=this.context,(e,t,i)=>{if(!ef(i,e.type))throw Error(`Cannot call 'array.set' with argument 'value'='${i}'. An argument of 'literal ${typeof i}' type was used but a '${e.type}' is expected.`);let r=t<0?e.array.length+t:t;if(r<0||r>=e.array.length)throw new ei(`Index ${t} is out of bounds, array size is ${e.array.length}.`,"array.set");e.array[r]="number"==typeof i?h.precision(i):i}),this._shift=(this.context,e=>(0===e.array.length&&eu("shift"),e.array.shift())),this._size=(this.context,e=>e.array.length),this._slice=(c=this.context,(e,t=0,i)=>{let r=e.array.length,n=er(t)?0:t,s=void 0===i||er(i)?r:i;if((n<0||n>=r)&&ep(n,r,"array.slice"),(s<0||s>r)&&ep(s,r,"array.slice"),n>s)throw new ei("Index 'from' should be less than index 'to'.","array.slice");return new eO(function(e,t,i){let r=[];r.length=i;let n=i=>{let n=r.length;i<n?e.splice(t+i,n-i):i>n&&e.splice(t+n,0,...Array(i-n)),r.length=i};return new Proxy(r,{get(i,r,n){let s=eE(r);return -1!==s?s<i.length?e[t+s]:void 0:Reflect.get(i,r,n)},set(i,r,s,a){if("length"===r)return n(Number(s)),!0;let o=eE(r);return -1!==o?(o>=i.length&&n(o+1),e[t+o]=s,!0):Reflect.set(i,r,s,a)},has(e,t){let i=eE(t);return -1!==i?i<e.length:Reflect.has(e,t)},deleteProperty(i,r){let n=eE(r);return -1!==n?(n<i.length&&(e[t+n]=void 0),!0):Reflect.deleteProperty(i,r)},ownKeys(e){let t=[];for(let i=0;i<e.length;i++)t.push(String(i));return t.concat(Reflect.ownKeys(e))},getOwnPropertyDescriptor(i,r){let n=eE(r);return -1!==n?n>=i.length?void 0:{value:e[t+n],writable:!0,enumerable:!0,configurable:!0}:Reflect.getOwnPropertyDescriptor(i,r)}})}(e.array,n,s-n),e.type,c)}),this._some=(this.context,e=>e.array.some(e=>!isNaN(e)&&e)),this._sort=(this.context,(e,t=E.ascending,i)=>{let r=e.array,n=Array.from(r),s=el(n,i),a=s?ec(n.map(s),t).map(e=>n[e]):function(e,t=E.ascending){let i=e.some(e=>"string"==typeof e);return e.sort((e,t)=>eh(e,t,i)),t!==E.ascending&&e.reverse(),e}(n,t);for(let e=0;e<a.length;e++)r[e]=a[e]}),this._sort_indices=(p=this.context,(e,t=E.ascending,i)=>{let r=Array.from(e.array),n=el(r,i);return new eO(ec(n?r.map(n):r,t),eR.int,p)}),this._standardize=function(e){return t=>{let i=e.array.avg(t),r=e.array.stdev(t);return isNaN(r)?new eO(t.array.map(()=>NaN),eR.float,e):0===r?new eO(t.array.map(()=>1),eR.float,e):new eO(t.array.map(e=>(e-i)/r),eR.float,e)}}(this.context),this._stdev=(u=this.context,(e,t=!0)=>{let i=e.array,r=i.length;if(0===r)return NaN;let n=0,s=0,a=0;for(let e=0;e<r;e++){let t=Number(i[e]);!isNaN(t)&&null!=t&&(n+=t,s+=t*t,a++)}if(0===a)return NaN;let o=n/a,l=s/a-o*o;return l<0?NaN:(!t&&a>1&&(l=l*a/(a-1)),t||1!==a?u.precision(Math.sqrt(l)):NaN)}),this._sum=(d=this.context,e=>{let t=0,i=0;for(let r of e.array){let e=Number(r);isNaN(e)||(t+=e,i++)}return 0===i?NaN:d.precision(t)}),this._unshift=(m=this.context,(e,t)=>{if(!ef(t,e.type))throw Error(`Cannot call 'array.unshift' with argument 'value'='${t}'. An argument of 'literal ${typeof t}' type was used but a '${e.type}' is expected.`);e.array.unshift("number"==typeof t?m.precision(t):t)}),this._variance=(f=this.context,(e,t=!0)=>{let i=0,r=0;for(let t of e.array){let e=Number(t);!isNaN(e)&&null!=e&&(i+=e,r++)}if(0===r)return NaN;let n=i/r,s=0;for(let t of e.array){let e=Number(t);isNaN(e)||null==e||(s+=(e-n)*(e-n))}let a=t?r:r-1;return a<=0?NaN:f.precision(s/a)})}get length(){return this.array.length}toString(){var e;return"["+(e=this,Array.from(e.array,t=>ew(e,t,ex))).join(", ")+"]"}[Symbol.iterator](){return this.array[Symbol.iterator]()}abs(...e){return this._abs(this,...eN(e,eI.abs,1))}avg(...e){return this._avg(this,...eN(e,eI.avg,1))}binary_search(...e){return this._binary_search(this,...eN(e,eI.binary_search,1))}binary_search_leftmost(...e){return this._binary_search_leftmost(this,...eN(e,eI.binary_search_leftmost,1))}binary_search_rightmost(...e){return this._binary_search_rightmost(this,...eN(e,eI.binary_search_rightmost,1))}clear(...e){return this._clear(this,...eN(e,eI.clear,1))}concat(...e){return this._concat(this,...eN(e,eI.concat,1))}copy(...e){return this._copy(this,...eN(e,eI.copy,1))}covariance(...e){return this._covariance(this,...eN(e,eI.covariance,1))}every(...e){return this._every(this,...eN(e,eI.every,1))}fill(...e){return this._fill(this,...eN(e,eI.fill,1))}first(...e){return this._first(this,...eN(e,eI.first,1))}get(...e){return this._get(this,...eN(e,eI.get,1))}includes(...e){return this._includes(this,...eN(e,eI.includes,1))}indexof(...e){return this._indexof(this,...eN(e,eI.indexof,1))}insert(...e){return this._insert(this,...eN(e,eI.insert,1))}join(...e){return this._join(this,...eN(e,eI.join,1))}last(...e){return this._last(this,...eN(e,eI.last,1))}lastindexof(...e){return this._lastindexof(this,...eN(e,eI.lastindexof,1))}max(...e){return this._max(this,...eN(e,eI.max,1))}median(...e){return this._median(this,...eN(e,eI.median,1))}min(...e){return this._min(this,...eN(e,eI.min,1))}mode(...e){return this._mode(this,...eN(e,eI.mode,1))}percentile_linear_interpolation(...e){return this._percentile_linear_interpolation(this,...eN(e,eI.percentile_linear_interpolation,1))}percentile_nearest_rank(...e){return this._percentile_nearest_rank(this,...eN(e,eI.percentile_nearest_rank,1))}percentrank(...e){return this._percentrank(this,...eN(e,eI.percentrank,1))}pop(...e){return this._pop(this,...eN(e,eI.pop,1))}push(...e){return this._push(this,...eN(e,eI.push,1))}range(...e){return this._range(this,...eN(e,eI.range,1))}remove(...e){return this._remove(this,...eN(e,eI.remove,1))}reverse(...e){return this._reverse(this,...eN(e,eI.reverse,1))}set(...e){return this._set(this,...eN(e,eI.set,1))}shift(...e){return this._shift(this,...eN(e,eI.shift,1))}size(...e){return this._size(this,...eN(e,eI.size,1))}slice(...e){return this._slice(this,...eN(e,eI.slice,1))}some(...e){return this._some(this,...eN(e,eI.some,1))}sort(...e){return this._sort(this,...eN(e,eI.sort,1))}sort_indices(...e){return this._sort_indices(this,...eN(e,eI.sort_indices,1))}standardize(...e){return this._standardize(this,...eN(e,eI.standardize,1))}stdev(...e){return this._stdev(this,...eN(e,eI.stdev,1))}sum(...e){return this._sum(this,...eN(e,eI.sum,1))}unshift(...e){return this._unshift(this,...eN(e,eI.unshift,1))}variance(...e){return this._variance(this,...eN(e,eI.variance,1))}}function ej(e,t){if(!Number.isFinite(e)||e>1e5)throw new ei("The requested size exceeds the 100000 element limit.",t)}function eV(e,t){if(e.secondaryContextCount=(e.secondaryContextCount||0)+1,e.secondaryContextCount>40)throw new ei("The script executes too many request.*() function calls.",t)}class e${constructor(e){this.context=e,this.abs=eT((e,...t)=>e.abs(...t),eI.abs),this.avg=eT((e,...t)=>e.avg(...t),eI.avg),this.binary_search=eT((e,...t)=>e.binary_search(...t),eI.binary_search),this.binary_search_leftmost=eT((e,...t)=>e.binary_search_leftmost(...t),eI.binary_search_leftmost),this.binary_search_rightmost=eT((e,...t)=>e.binary_search_rightmost(...t),eI.binary_search_rightmost),this.clear=eT((e,...t)=>e.clear(...t),eI.clear),this.concat=eT((e,...t)=>e.concat(...t),eI.concat),this.copy=eT((e,...t)=>e.copy(...t),eI.copy),this.covariance=eT((e,...t)=>e.covariance(...t),eI.covariance),this.every=eT((e,...t)=>e.every(...t),eI.every),this.fill=eT((e,...t)=>e.fill(...t),eI.fill),this.first=eT((e,...t)=>e.first(...t),eI.first),this.from=(...t)=>{let i=t.every(e=>"number"==typeof e)?t.every(e=>Number.isInteger(e))?eR.int:eR.float:t.every(e=>"string"==typeof e)?eR.string:t.every(e=>"boolean"==typeof e)?eR.bool:eR.any;return new eO([...t],i===eR.int?eR.float:i,e)},this.get=eT((e,...t)=>e.get(...t),eI.get),this.includes=eT((e,...t)=>e.includes(...t),eI.includes),this.indexof=eT((e,...t)=>e.indexof(...t),eI.indexof),this.insert=eT((e,...t)=>e.insert(...t),eI.insert),this.join=eT((e,...t)=>e.join(...t),eI.join),this.last=eT((e,...t)=>e.last(...t),eI.last),this.lastindexof=eT((e,...t)=>e.lastindexof(...t),eI.lastindexof),this.max=eT((e,...t)=>e.max(...t),eI.max),this.median=eT((e,...t)=>e.median(...t),eI.median),this.min=eT((e,...t)=>e.min(...t),eI.min),this.mode=eT((e,...t)=>e.mode(...t),eI.mode),this.new=function(e){return(t,i)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return(ej(r,"array.new"),void 0===i)?new eO(r?Array(r).fill(NaN):[],eR.any,e):new eO(Array(r).fill(e.precision(i||0)),em(i||0),e)}}(e),this.new_bool=function(e){return(t=0,i)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;ej(r,"array.new");let n=void 0===i?!(e.pineVersion>=6)&&NaN:i;return new eO(Array(r).fill(n),eR.bool,e)}}(e),this.new_box=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.box,e)},this.new_color=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.color,e)},this.new_float=function(e){return(t=0,i=NaN)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(e.precision(i)),eR.float,e)}}(e),this.new_int=function(e){return(t=0,i=NaN)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(e.precision(i)),eR.int,e)}}(e),this.new_label=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.label,e)},this.new_line=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.line,e)},this.new_linefill=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.linefill,e)},this.new_string=(t=0,i="")=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.string,e)},this.new_table=(t=0,i=null)=>{let r="number"==typeof t&&t>0&&!isNaN(t)?Math.floor(t):0;return ej(r,"array.new"),new eO(Array(r).fill(i),eR.table,e)},this.param=(e,t=0)=>m.from(e).get(t),this.percentile_linear_interpolation=eT((e,...t)=>e.percentile_linear_interpolation(...t),eI.percentile_linear_interpolation),this.percentile_nearest_rank=eT((e,...t)=>e.percentile_nearest_rank(...t),eI.percentile_nearest_rank),this.percentrank=eT((e,...t)=>e.percentrank(...t),eI.percentrank),this.pop=eT((e,...t)=>e.pop(...t),eI.pop),this.push=eT((e,...t)=>e.push(...t),eI.push),this.range=eT((e,...t)=>e.range(...t),eI.range),this.remove=eT((e,...t)=>e.remove(...t),eI.remove),this.reverse=eT((e,...t)=>e.reverse(...t),eI.reverse),this.set=eT((e,...t)=>e.set(...t),eI.set),this.shift=eT((e,...t)=>e.shift(...t),eI.shift),this.size=eT((e,...t)=>e.size(...t),eI.size),this.slice=eT((e,...t)=>e.slice(...t),eI.slice),this.some=eT((e,...t)=>e.some(...t),eI.some),this.sort=eT((e,...t)=>e.sort(...t),eI.sort),this.sort_indices=eT((e,...t)=>e.sort_indices(...t),eI.sort_indices),this.standardize=eT((e,...t)=>e.standardize(...t),eI.standardize),this.stdev=eT((e,...t)=>e.stdev(...t),eI.stdev),this.sum=eT((e,...t)=>e.sum(...t),eI.sum),this.unshift=eT((e,...t)=>e.unshift(...t),eI.unshift),this.variance=eT((e,...t)=>e.variance(...t),eI.variance),this.__from_int=(...t)=>new eO([...t],eR.int,e)}}function eL(e,t){if(e.has(t))return t;let i=es(t);if(null===i)return t;for(let t of e.keys())if(es(t)===i)return t;return t}var eB=Object.defineProperty,eF=(e,t,i)=>((e,t,i)=>t in e?eB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class eq{constructor(e){var t,i,r;this.context=e,eF(this,"map"),eF(this,"valueType"),eF(this,"_clear"),eF(this,"_contains"),eF(this,"_copy"),eF(this,"_get"),eF(this,"_keys"),eF(this,"_put"),eF(this,"_put_all"),eF(this,"_remove"),eF(this,"_size"),eF(this,"_values"),this.map=new Map,this._clear=(this.context,e=>{e.map.clear()}),this._contains=(this.context,(e,t)=>e.map.has(eL(e.map,t))),this._copy=(t=this.context,e=>{let i=new eq(t);return i.map=new Map(e.map),i.valueType=e.valueType,i}),this._get=(this.context,(e,t)=>{let i=e.map.get(eL(e.map,t));return void 0===i?"string"===e.valueType?"":NaN:i}),this._keys=(i=this.context,e=>{let t=Array.from(e.map.keys()),r=em(t[0]);return new eO(t,r,i)}),this._put=(this.context,(e,t,i)=>{let r=eL(e.map,t),n=e.map.get(r);return e.map.set(r,i),void 0===n?NaN:n}),this._put_all=(this.context,(e,t)=>{for(let[i,r]of t.map)e.map.set(eL(e.map,i),r)}),this._remove=(this.context,(e,t)=>{let i=eL(e.map,t),r=e.map.get(i);return e.map.delete(i)?r:NaN}),this._size=(this.context,e=>e.map.size),this._values=(r=this.context,e=>{let t=Array.from(e.map.values()),i=em(t[0]);return new eO(t,i,r)})}toString(){return`PineMapObject(${this.map.size})`}clear(...e){return this._clear(this,...eN(e,eM.clear,1))}contains(...e){return this._contains(this,...eN(e,eM.contains,1))}copy(...e){return this._copy(this,...eN(e,eM.copy,1))}get(...e){return this._get(this,...eN(e,eM.get,1))}keys(...e){return this._keys(this,...eN(e,eM.keys,1))}put(...e){return this._put(this,...eN(e,eM.put,1))}put_all(...e){return this._put_all(this,...eN(e,eM.put_all,1))}remove(...e){return this._remove(this,...eN(e,eM.remove,1))}size(...e){return this._size(this,...eN(e,eM.size,1))}values(...e){return this._values(this,...eN(e,eM.values,1))}}class ez{constructor(e){this.context=e,this.clear=eT((e,...t)=>e.clear(...t),eM.clear),this.contains=eT((e,...t)=>e.contains(...t),eM.contains),this.copy=eT((e,...t)=>e.copy(...t),eM.copy),this.get=eT((e,...t)=>e.get(...t),eM.get),this.keys=eT((e,...t)=>e.keys(...t),eM.keys),this.new=t=>{let i=new eq(e);return"string"===t&&(i.valueType=t),i},this.param=(e,t=0)=>m.from(e).get(t),this.put=eT((e,...t)=>e.put(...t),eM.put),this.put_all=eT((e,...t)=>e.put_all(...t),eM.put_all),this.remove=eT((e,...t)=>e.remove(...t),eM.remove),this.size=eT((e,...t)=>e.size(...t),eM.size),this.values=eT((e,...t)=>e.values(...t),eM.values)}}function eU(e){let t=e.length;if(0===t)return[];let i=Array(t);for(let r=0;r<t;r++){i[r]=Array(2*t);for(let n=0;n<t;n++)i[r][n]=e[r][n];for(let e=0;e<t;e++)i[r][t+e]=+(r===e)}for(let r=0;r<t;r++){let n=Math.abs(i[r][r]),s=r;for(let e=r+1;e<t;e++){let t=Math.abs(i[e][r]);t>n&&(n=t,s=e)}if(n<1e-14)return e.map(e=>e.map(()=>NaN));if(s!==r){let e=i[r];i[r]=i[s],i[s]=e}let a=i[r][r];for(let e=r;e<2*t;e++)i[r][e]/=a;for(let e=0;e<t;e++){if(e===r)continue;let n=i[e][r];if(0!==n)for(let s=r;s<2*t;s++)i[e][s]-=n*i[r][s]}}let r=Array(t);for(let e=0;e<t;e++){r[e]=Array(t);for(let n=0;n<t;n++)r[e][n]=i[e][t+n]}return r}var eW=Object.defineProperty,eK=(e,t,i)=>((e,t,i)=>t in e?eW(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class eG{constructor(e=0,t=0,i=NaN,r){var n,s,a,o,l,h;if(this.context=r,eK(this,"matrix"),eK(this,"_add_col"),eK(this,"_add_row"),eK(this,"_avg"),eK(this,"_col"),eK(this,"_columns"),eK(this,"_concat"),eK(this,"_copy"),eK(this,"_det"),eK(this,"_diff"),eK(this,"_eigenvalues"),eK(this,"_eigenvectors"),eK(this,"_elements_count"),eK(this,"_fill"),eK(this,"_get"),eK(this,"_inv"),eK(this,"_is_antidiagonal"),eK(this,"_is_antisymmetric"),eK(this,"_is_binary"),eK(this,"_is_diagonal"),eK(this,"_is_identity"),eK(this,"_is_square"),eK(this,"_is_stochastic"),eK(this,"_is_symmetric"),eK(this,"_is_triangular"),eK(this,"_is_zero"),eK(this,"_kron"),eK(this,"_max"),eK(this,"_median"),eK(this,"_min"),eK(this,"_mode"),eK(this,"_mult"),eK(this,"_pinv"),eK(this,"_pow"),eK(this,"_rank"),eK(this,"_remove_col"),eK(this,"_remove_row"),eK(this,"_reshape"),eK(this,"_reverse"),eK(this,"_row"),eK(this,"_rows"),eK(this,"_set"),eK(this,"_sort"),eK(this,"_submatrix"),eK(this,"_sum"),eK(this,"_swap_columns"),eK(this,"_swap_rows"),eK(this,"_trace"),eK(this,"_transpose"),this.matrix=[],e>0&&t>0)for(let r=0;r<e;r++)this.matrix.push(Array(t).fill(i));this._add_col=(this.context,(e,t,i)=>{let r=e.matrix.length,n=[];if(i&&(n=i instanceof eO?i.array:Array.isArray(i)?i:[i]),0===r){for(let t=0;t<n.length;t++){let i=n[t];i instanceof m&&(i=i.get(0)),e.matrix.push([i])}return}let s=e.matrix[0].length,a=void 0!==t?t:s;for(let t=0;t<r;t++){let i=t<n.length?n[t]:NaN;i instanceof m&&(i=i.get(0)),e.matrix[t].splice(a,0,i)}}),this._add_row=(this.context,(e,t,i)=>{let r=e.matrix.length,n=[];if(i)if(i instanceof eO)n=i.array;else if(Array.isArray(i))n=i;else if(i instanceof m){let e=i.get(0);n=Array.isArray(e)?e:[e]}else n=[i];let s=r>0?e.matrix[0].length:n.length,a=[];for(let e=0;e<s;e++)if(e<n.length){let t=n[e];t instanceof m&&(t=t.get(0)),a.push(t)}else a.push(NaN);e.matrix.splice(void 0!==t?t:r,0,a)}),this._avg=(this.context,e=>{let t=e.matrix.length;if(0===t)return NaN;let i=e.matrix[0].length;if(0===i)return NaN;let r=0,n=0;for(let s=0;s<t;s++)for(let t=0;t<i;t++){let i=e.matrix[s][t];isNaN(i)||(r+=i,n++)}return 0===n?NaN:r/n}),this._col=(n=this.context,(e,t)=>{let i=e.matrix.length,r=i>0?e.matrix[0].length:0;if(t<0||t>=r)throw new ei(`Column index ${t} is out of bounds, matrix has ${r} columns.`,"matrix.col");let s=[];for(let r=0;r<i;r++)s.push(e.matrix[r][t]);let a=em(s[0]);return new eO(s,a,n)}),this._columns=(this.context,e=>0===e.matrix.length?0:e.matrix[0].length),this._concat=(this.context,(e,t)=>{let i=e.matrix.length,r=t.matrix.length;if(0===i){for(let i=0;i<r;i++)e.matrix.push([...t.matrix[i]]);return}let n=e.matrix[0].length,s=r>0?t.matrix[0].length:0;if(n!==s&&r>0)return void console.error(`matrix.concat: Column count mismatch ${n} vs ${s}`);for(let i=0;i<r;i++)e.matrix.push([...t.matrix[i]])}),this._copy=(s=this.context,e=>{let t=e.matrix.length,i=t>0?e.matrix[0].length:0,r=new eG(t,i,NaN,s);return r.matrix=e.matrix.map(e=>[...e]),r}),this._det=(this.context,e=>{let t=e.matrix.length,i=t>0?e.matrix[0].length:0;return t!==i?NaN:function(e){let t=e.length;if(0===t)return 0;if(1===t)return e[0][0];if(2===t)return e[0][0]*e[1][1]-e[0][1]*e[1][0];let i=e.map(e=>[...e]),r=1;for(let e=0;e<t;e++){let n=e;for(;n<t&&0===i[n][e];)n++;if(n===t)return 0;n!==e&&([i[e],i[n]]=[i[n],i[e]],r*=-1),r*=i[e][e];for(let r=e+1;r<t;r++){let n=i[r][e]/i[e][e];for(let s=e;s<t;s++)i[r][s]-=n*i[e][s]}}return r}(e.matrix)}),this._diff=function(e){return(t,i)=>{let r=t.matrix.length;if(0===r)return new eG(0,0,NaN,e);let n=t.matrix[0].length,s=new eG(r,n,NaN,e);if(i instanceof eG)for(let e=0;e<r;e++)for(let r=0;r<n;r++){let n=t.matrix[e][r],a=i.matrix[e]&&void 0!==i.matrix[e][r]?i.matrix[e][r]:NaN;s.matrix[e][r]=n-a}else for(let e=0;e<r;e++)for(let r=0;r<n;r++)s.matrix[e][r]=t.matrix[e][r]-i;return s}}(this.context),this._eigenvalues=function(e){return t=>{let i=t.matrix.length,r=i>0?t.matrix[0].length:0;if(i!==r)return new eO([],em(t.matrix[0][0]),e);let n=function(e){let t=e.length;if(2!==t)return Array(t).fill(NaN);let i=e[0][0],r=e[0][1],n=e[1][0],s=e[1][1],a=i+s,o=a*a-4*(i*s-r*n);return o<0?[NaN,NaN]:[(a+Math.sqrt(o))/2,(a-Math.sqrt(o))/2]}(t.matrix),s=em(n[0]);return new eO(n,s,e)}}(this.context),this._eigenvectors=function(e){return t=>{let i=t.matrix.length,r=i>0?t.matrix[0].length:0;if(i!==r)return new eG(0,0,NaN,e);let n=new eG(i,r,0,e);for(let e=0;e<i;e++)n.matrix[e][e]=1;return n}}(this.context),this._elements_count=(this.context,e=>{let t=e.matrix.length;return 0===t?0:t*e.matrix[0].length}),this._fill=(this.context,(e,t,i,r,n,s)=>{let a=e.matrix.length;if(0===a)return;let o=e.matrix[0].length,l=void 0!==i?i:0,h=void 0!==r?r:a,c=void 0!==n?n:0,p=void 0!==s?s:o;for(let i=l;i<h&&!(i>=a);i++)for(let r=c;r<p&&!(r>=o);r++)e.matrix[i][r]=t}),this._get=(this.context,(e,t,i)=>{let r=e.matrix.length,n=r>0?e.matrix[0].length:0;if(t<0||t>=r)throw new ei(`Row index ${t} is out of bounds, matrix has ${r} rows.`,"matrix.get");if(i<0||i>=n)throw new ei(`Column index ${i} is out of bounds, matrix has ${n} columns.`,"matrix.get");let s=e.matrix[t][i];return void 0===s?NaN:s}),this._inv=function(e){return t=>{let i=t.matrix.length,r=i>0?t.matrix[0].length:0;if(i!==r)return new eG(i,r,NaN,e);let n=eU(t.matrix),s=new eG(i,r,NaN,e);return s.matrix=n,s}}(this.context),this._is_antidiagonal=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;if(t!==i)return!1;for(let r=0;r<t;r++)for(let n=0;n<i;n++)if(r+n!==t-1&&0!==e.matrix[r][n])return!1;return!0}),this._is_antisymmetric=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;if(t!==i)return!1;for(let r=0;r<t;r++)for(let t=0;t<i;t++)if(e.matrix[t][r]!==-e.matrix[r][t])return!1;return!0}),this._is_binary=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;for(let r=0;r<t;r++)for(let t=0;t<i;t++){let i=e.matrix[r][t];if(0!==i&&1!==i)return!1}return!0}),this._is_diagonal=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;if(t!==i)return!1;for(let r=0;r<t;r++)for(let t=0;t<i;t++)if(r!==t&&0!==e.matrix[r][t])return!1;return!0}),this._is_identity=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;if(t!==i)return!1;for(let r=0;r<t;r++)for(let t=0;t<i;t++)if(r===t){if(1!==e.matrix[r][t])return!1}else if(0!==e.matrix[r][t])return!1;return!0}),this._is_square=(this.context,e=>{let t=e.matrix.length;return 0!==t&&t===e.matrix[0].length}),this._is_stochastic=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;for(let r=0;r<t;r++){let t=0;for(let n=0;n<i;n++){let i=e.matrix[r][n];if(i<0)return!1;t+=i}if(Math.abs(t-1)>1e-10)return!1}return!0}),this._is_symmetric=(this.context,e=>{let t=e.matrix.length;if(0===t||t!==e.matrix[0].length)return!1;for(let i=0;i<t;i++)for(let t=0;t<i;t++)if(e.matrix[i][t]!==e.matrix[t][i])return!1;return!0}),this._is_triangular=(this.context,e=>{let t=e.matrix.length;if(0===t)return!1;let i=e.matrix[0].length;if(t!==i)return!1;let r=!0,n=!0;for(let s=0;s<t;s++)for(let t=0;t<i;t++)s>t&&0!==e.matrix[s][t]&&(r=!1),s<t&&0!==e.matrix[s][t]&&(n=!1);return r||n}),this._is_zero=(this.context,e=>{let t=e.matrix.length;if(0===t)return!0;let i=e.matrix[0].length;for(let r=0;r<t;r++)for(let t=0;t<i;t++)if(0!==e.matrix[r][t])return!1;return!0}),this._kron=(a=this.context,(e,t)=>{let i=e.matrix.length,r=i>0?e.matrix[0].length:0,n=t.matrix.length,s=n>0?t.matrix[0].length:0,o=new eG(i*n,r*s,NaN,a);for(let a=0;a<i;a++)for(let i=0;i<r;i++){let r=e.matrix[a][i];for(let e=0;e<n;e++)for(let l=0;l<s;l++){let h=t.matrix[e][l];o.matrix[a*n+e][i*s+l]=r*h}}return o}),this._max=(this.context,e=>{let t=e.matrix.length;if(0===t)return NaN;let i=e.matrix[0].length,r=-1/0,n=!1;for(let s=0;s<t;s++)for(let t=0;t<i;t++){let i=e.matrix[s][t];isNaN(i)||(i>r&&(r=i),n=!0)}return n?r:NaN}),this._median=(this.context,e=>{let t=e.matrix.length;if(0===t)return NaN;let i=e.matrix[0].length,r=[];for(let n=0;n<t;n++)for(let t=0;t<i;t++){let i=e.matrix[n][t];isNaN(i)||r.push(i)}if(0===r.length)return NaN;r.sort((e,t)=>e-t);let n=Math.floor(r.length/2);return r.length%2!=0?r[n]:(r[n-1]+r[n])/2}),this._min=(this.context,e=>{let t=e.matrix.length;if(0===t)return NaN;let i=e.matrix[0].length,r=1/0,n=!1;for(let s=0;s<t;s++)for(let t=0;t<i;t++){let i=e.matrix[s][t];isNaN(i)||(i<r&&(r=i),n=!0)}return n?r:NaN}),this._mode=(this.context,e=>{let t=e.matrix.length;if(0===t)return NaN;let i=e.matrix[0].length,r=new Map,n=0,s=NaN;for(let a=0;a<t;a++)for(let t=0;t<i;t++){let i=e.matrix[a][t];if(!isNaN(i)){let e=(r.get(i)||0)+1;r.set(i,e),e>n?(n=e,s=i):e===n&&i<s&&(s=i)}}return s}),this._mult=function(e){return(t,i)=>{let r=t.matrix.length,n=r>0?t.matrix[0].length:0;if(i instanceof eG){let s=i.matrix.length,a=s>0?i.matrix[0].length:0;if(n!==s)return new eG(0,0,NaN,e);let o=new eG(r,a,0,e);for(let e=0;e<r;e++)for(let r=0;r<a;r++){let s=0;for(let a=0;a<n;a++)s+=t.matrix[e][a]*i.matrix[a][r];o.matrix[e][r]=s}return o}if(i instanceof eO||Array.isArray(i.array||i)){let s=i.array||i;if(n!==s.length)return new eO([],"float",e);let a=[];for(let e=0;e<r;e++){let i=0;for(let r=0;r<n;r++)i+=t.matrix[e][r]*s[r];a.push(i)}return new eO(a,"float",e)}{let s=new eG(r,n,NaN,e);for(let e=0;e<r;e++)for(let r=0;r<n;r++)s.matrix[e][r]=t.matrix[e][r]*i;return s}}}(this.context),this._pinv=function(e){return t=>{let i,r=t.matrix.length;if(0===r)return new eG(0,0,NaN,e);let n=t.matrix[0].length;if(r===n){let i=eU(t.matrix),s=new eG(r,n,NaN,e);return s.matrix=i,s}let s=(e,t)=>{let i=e.length,r=e[0].length,n=t[0].length,s=Array(i);for(let a=0;a<i;a++){s[a]=Array(n).fill(0);for(let i=0;i<r;i++){let r=e[a][i];if(0!==r)for(let e=0;e<n;e++)s[a][e]+=r*t[i][e]}}return s},a=t.matrix,o=(e=>{let t=e.length,i=e[0].length,r=Array(i);for(let n=0;n<i;n++){r[n]=Array(t);for(let i=0;i<t;i++)r[n][i]=e[i][n]}return r})(a);if(r>n){let e=eU(s(o,a));i=s(e,o)}else{let e=eU(s(a,o));i=s(o,e)}let l=new eG(n,r,NaN,e);return l.matrix=i,l}}(this.context),this._pow=function(e){return(t,i)=>{let r=t.matrix.length,n=r>0?t.matrix[0].length:0;if(r!==n)return new eG(0,0,NaN,e);let s=new eG(r,n,0,e);for(let e=0;e<r;e++)s.matrix[e][e]=1;let a=new eG(r,n,NaN,e);for(let e=0;e<r;e++)a.matrix[e]=[...t.matrix[e]];let o=Math.floor(i);if(!Number.isFinite(o)||o<0)return new eG(r,n,NaN,e);for(;o>0;){if(o%2==1){let t=new eG(r,n,0,e);for(let e=0;e<r;e++)for(let i=0;i<n;i++){let n=0;for(let t=0;t<r;t++)n+=s.matrix[e][t]*a.matrix[t][i];t.matrix[e][i]=n}s=t}let t=new eG(r,n,0,e);for(let e=0;e<r;e++)for(let i=0;i<n;i++){let n=0;for(let t=0;t<r;t++)n+=a.matrix[e][t]*a.matrix[t][i];t.matrix[e][i]=n}a=t,o=Math.floor(o/2)}return s}}(this.context),this._rank=(this.context,e=>{let t=e.matrix.length;if(0===t)return 0;let i=e.matrix[0].length,r=e.matrix.map(e=>[...e]),n=0;for(let e=0;e<i&&n<t;e++){let s=n;for(;s<t&&1e-10>Math.abs(r[s][e]);)s++;if(s<t){[r[n],r[s]]=[r[s],r[n]];let a=r[n][e];for(let t=e;t<i;t++)r[n][t]/=a;for(let s=0;s<t;s++)if(s!==n){let t=r[s][e];for(let a=e;a<i;a++)r[s][a]-=t*r[n][a]}n++}}return n}),this._remove_col=function(e){return(t,i)=>{let r=t.matrix.length;if(0===r)return new eO([],em(t.matrix[0][0]),e);let n=[];for(let e=0;e<r;e++){let r=t.matrix[e].splice(i,1);n.push(r[0])}let s=em(n[0]);return new eO(n,s,e)}}(this.context),this._remove_row=(o=this.context,(e,t)=>{let i=e.matrix.splice(t,1),r=em(i[0][0]);return new eO(i[0]||[],r,o)}),this._reshape=(this.context,(e,t,i)=>{let r=e.matrix.length,n=r>0?e.matrix[0].length:0,s=t*i,a=[];for(let t=0;t<r;t++)for(let i=0;i<n;i++)a.push(e.matrix[t][i]);for(;a.length<s;)a.push(NaN);a.length>s&&(a.length=s);let o=[],l=0;for(let e=0;e<t;e++){let e=[];for(let t=0;t<i;t++)e.push(a[l++]);o.push(e)}e.matrix=o}),this._reverse=(this.context,e=>{for(let t of(e.matrix.reverse(),e.matrix))t.reverse()}),this._row=(l=this.context,(e,t)=>{let i=e.matrix.length;if(t<0||t>=i)throw new ei(`Row index ${t} is out of bounds, matrix has ${i} rows.`,"matrix.row");let r=em(e.matrix[t][0]);return new eO([...e.matrix[t]],r,l)}),this._rows=(this.context,e=>e.matrix.length),this._set=(this.context,(e,t,i,r)=>{let n=e.matrix.length,s=n>0?e.matrix[0].length:0;if(t<0||t>=n)throw new ei(`Row index ${t} is out of bounds, matrix has ${n} rows.`,"matrix.set");if(i<0||i>=s)throw new ei(`Column index ${i} is out of bounds, matrix has ${s} columns.`,"matrix.set");e.matrix[t][i]=r}),this._sort=(this.context,(e,t=0,i=E.ascending,r)=>{if(0===e.matrix.length)return;let n=e.matrix.map(e=>e[t]),s=el(n,r),a=ec(s?n.map(s):n,i).map(t=>e.matrix[t]);e.matrix.splice(0,a.length,...a)}),this._submatrix=(h=this.context,(e,t,i,r,n)=>{let s=i-t,a=n-r,o=new eG(s,a,NaN,h);for(let i=0;i<s;i++){let n=t+i;if(n>=e.matrix.length)break;for(let t=0;t<a;t++){let s=r+t;if(s>=e.matrix[n].length)break;o.matrix[i][t]=e.matrix[n][s]}}return o}),this._sum=function(e){return(t,i)=>{let r=t.matrix.length;if(0===r)return new eG(0,0,NaN,e);let n=t.matrix[0].length,s=new eG(r,n,NaN,e);if(i instanceof eG)for(let e=0;e<r;e++)for(let r=0;r<n;r++){let n=t.matrix[e][r],a=i.matrix[e]&&void 0!==i.matrix[e][r]?i.matrix[e][r]:NaN;s.matrix[e][r]=n+a}else for(let e=0;e<r;e++)for(let r=0;r<n;r++)s.matrix[e][r]=t.matrix[e][r]+i;return s}}(this.context),this._swap_columns=(this.context,(e,t,i)=>{let r=e.matrix.length;for(let n=0;n<r;n++){let r=e.matrix[n][t];e.matrix[n][t]=e.matrix[n][i],e.matrix[n][i]=r}}),this._swap_rows=(this.context,(e,t,i)=>{let r=e.matrix[t];e.matrix[t]=e.matrix[i],e.matrix[i]=r}),this._trace=(this.context,e=>{let t=e.matrix.length;if(0===t)return 0;let i=Math.min(t,e.matrix[0].length),r=0;for(let t=0;t<i;t++)r+=e.matrix[t][t];return r}),this._transpose=function(e){return t=>{let i=t.matrix.length;if(0===i)return new eG(0,0,NaN,e);let r=t.matrix[0].length,n=new eG(r,i,NaN,e);for(let e=0;e<i;e++)for(let i=0;i<r;i++)n.matrix[i][e]=t.matrix[e][i];return n}}(this.context)}toString(){let e="";for(let t=0;t<this.matrix.length;t++)e+=(""===e?"":`
2
+ `)+("["+this.matrix[t].join(", "))+"]";return e}add_col(...e){return this._add_col(this,...eN(e,eC.add_col,1))}add_row(...e){return this._add_row(this,...eN(e,eC.add_row,1))}avg(...e){return this._avg(this,...eN(e,eC.avg,1))}col(...e){return this._col(this,...eN(e,eC.col,1))}columns(...e){return this._columns(this,...eN(e,eC.columns,1))}concat(...e){return this._concat(this,...eN(e,eC.concat,1))}copy(...e){return this._copy(this,...eN(e,eC.copy,1))}det(...e){return this._det(this,...eN(e,eC.det,1))}diff(...e){return this._diff(this,...eN(e,eC.diff,1))}eigenvalues(...e){return this._eigenvalues(this,...eN(e,eC.eigenvalues,1))}eigenvectors(...e){return this._eigenvectors(this,...eN(e,eC.eigenvectors,1))}elements_count(...e){return this._elements_count(this,...eN(e,eC.elements_count,1))}fill(...e){return this._fill(this,...eN(e,eC.fill,1))}get(...e){return this._get(this,...eN(e,eC.get,1))}inv(...e){return this._inv(this,...eN(e,eC.inv,1))}is_antidiagonal(...e){return this._is_antidiagonal(this,...eN(e,eC.is_antidiagonal,1))}is_antisymmetric(...e){return this._is_antisymmetric(this,...eN(e,eC.is_antisymmetric,1))}is_binary(...e){return this._is_binary(this,...eN(e,eC.is_binary,1))}is_diagonal(...e){return this._is_diagonal(this,...eN(e,eC.is_diagonal,1))}is_identity(...e){return this._is_identity(this,...eN(e,eC.is_identity,1))}is_square(...e){return this._is_square(this,...eN(e,eC.is_square,1))}is_stochastic(...e){return this._is_stochastic(this,...eN(e,eC.is_stochastic,1))}is_symmetric(...e){return this._is_symmetric(this,...eN(e,eC.is_symmetric,1))}is_triangular(...e){return this._is_triangular(this,...eN(e,eC.is_triangular,1))}is_zero(...e){return this._is_zero(this,...eN(e,eC.is_zero,1))}kron(...e){return this._kron(this,...eN(e,eC.kron,1))}max(...e){return this._max(this,...eN(e,eC.max,1))}median(...e){return this._median(this,...eN(e,eC.median,1))}min(...e){return this._min(this,...eN(e,eC.min,1))}mode(...e){return this._mode(this,...eN(e,eC.mode,1))}mult(...e){return this._mult(this,...eN(e,eC.mult,1))}pinv(...e){return this._pinv(this,...eN(e,eC.pinv,1))}pow(...e){return this._pow(this,...eN(e,eC.pow,1))}rank(...e){return this._rank(this,...eN(e,eC.rank,1))}remove_col(...e){return this._remove_col(this,...eN(e,eC.remove_col,1))}remove_row(...e){return this._remove_row(this,...eN(e,eC.remove_row,1))}reshape(...e){return this._reshape(this,...eN(e,eC.reshape,1))}reverse(...e){return this._reverse(this,...eN(e,eC.reverse,1))}row(...e){return this._row(this,...eN(e,eC.row,1))}rows(...e){return this._rows(this,...eN(e,eC.rows,1))}set(...e){return this._set(this,...eN(e,eC.set,1))}sort(...e){return this._sort(this,...eN(e,eC.sort,1))}submatrix(...e){return this._submatrix(this,...eN(e,eC.submatrix,1))}sum(...e){return this._sum(this,...eN(e,eC.sum,1))}swap_columns(...e){return this._swap_columns(this,...eN(e,eC.swap_columns,1))}swap_rows(...e){return this._swap_rows(this,...eN(e,eC.swap_rows,1))}trace(...e){return this._trace(this,...eN(e,eC.trace,1))}transpose(...e){return this._transpose(this,...eN(e,eC.transpose,1))}}function eH(e){return(t,i,r)=>(ej(("number"==typeof t&&t>0?t:0)*("number"==typeof i&&i>0?i:0),"matrix.new"),new eG(t,i,r,e))}class eY{constructor(e){this.context=e,this.add_col=eT((e,...t)=>e.add_col(...t),eC.add_col),this.add_row=eT((e,...t)=>e.add_row(...t),eC.add_row),this.avg=eT((e,...t)=>e.avg(...t),eC.avg),this.col=eT((e,...t)=>e.col(...t),eC.col),this.columns=eT((e,...t)=>e.columns(...t),eC.columns),this.concat=eT((e,...t)=>e.concat(...t),eC.concat),this.copy=eT((e,...t)=>e.copy(...t),eC.copy),this.det=eT((e,...t)=>e.det(...t),eC.det),this.diff=eT((e,...t)=>e.diff(...t),eC.diff),this.eigenvalues=eT((e,...t)=>e.eigenvalues(...t),eC.eigenvalues),this.eigenvectors=eT((e,...t)=>e.eigenvectors(...t),eC.eigenvectors),this.elements_count=eT((e,...t)=>e.elements_count(...t),eC.elements_count),this.fill=eT((e,...t)=>e.fill(...t),eC.fill),this.get=eT((e,...t)=>e.get(...t),eC.get),this.inv=eT((e,...t)=>e.inv(...t),eC.inv),this.is_antidiagonal=eT((e,...t)=>e.is_antidiagonal(...t),eC.is_antidiagonal),this.is_antisymmetric=eT((e,...t)=>e.is_antisymmetric(...t),eC.is_antisymmetric),this.is_binary=eT((e,...t)=>e.is_binary(...t),eC.is_binary),this.is_diagonal=eT((e,...t)=>e.is_diagonal(...t),eC.is_diagonal),this.is_identity=eT((e,...t)=>e.is_identity(...t),eC.is_identity),this.is_square=eT((e,...t)=>e.is_square(...t),eC.is_square),this.is_stochastic=eT((e,...t)=>e.is_stochastic(...t),eC.is_stochastic),this.is_symmetric=eT((e,...t)=>e.is_symmetric(...t),eC.is_symmetric),this.is_triangular=eT((e,...t)=>e.is_triangular(...t),eC.is_triangular),this.is_zero=eT((e,...t)=>e.is_zero(...t),eC.is_zero),this.kron=eT((e,...t)=>e.kron(...t),eC.kron),this.max=eT((e,...t)=>e.max(...t),eC.max),this.median=eT((e,...t)=>e.median(...t),eC.median),this.min=eT((e,...t)=>e.min(...t),eC.min),this.mode=eT((e,...t)=>e.mode(...t),eC.mode),this.mult=eT((e,...t)=>e.mult(...t),eC.mult),this.new=eH(e),this.param=(e,t=0)=>m.from(e).get(t),this.pinv=eT((e,...t)=>e.pinv(...t),eC.pinv),this.pow=eT((e,...t)=>e.pow(...t),eC.pow),this.rank=eT((e,...t)=>e.rank(...t),eC.rank),this.remove_col=eT((e,...t)=>e.remove_col(...t),eC.remove_col),this.remove_row=eT((e,...t)=>e.remove_row(...t),eC.remove_row),this.reshape=eT((e,...t)=>e.reshape(...t),eC.reshape),this.reverse=eT((e,...t)=>e.reverse(...t),eC.reverse),this.row=eT((e,...t)=>e.row(...t),eC.row),this.rows=eT((e,...t)=>e.rows(...t),eC.rows),this.set=eT((e,...t)=>e.set(...t),eC.set),this.sort=eT((e,...t)=>e.sort(...t),eC.sort),this.submatrix=eT((e,...t)=>e.submatrix(...t),eC.submatrix),this.sum=eT((e,...t)=>e.sum(...t),eC.sum),this.swap_columns=eT((e,...t)=>e.swap_columns(...t),eC.swap_columns),this.swap_rows=eT((e,...t)=>e.swap_rows(...t),eC.swap_rows),this.trace=eT((e,...t)=>e.trace(...t),eC.trace),this.transpose=eT((e,...t)=>e.transpose(...t),eC.transpose),this.new_float=eH(e),this.new_int=eH(e),this.new_string=eH(e),this.new_bool=eH(e),this.new_color=eH(e),this.new_line=eH(e),this.new_label=eH(e),this.new_box=eH(e),this.new_linefill=eH(e),this.new_table=eH(e)}}var eZ=Object.defineProperty;class eJ{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?eZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_live",!1)}setLive(){this._live=!0}get isnew(){return!this._live}get islast(){return this.context.idx===this.context.length-1}get isfirst(){return 0===this.context.idx}get ishistory(){return this.context.idx<this.context.length-1}get isrealtime(){return this.context.idx===this.context.length-1}get isconfirmed(){return this.context.data.closeTime.data[this.context.idx]<=Date.now()}get islastconfirmedhistory(){let e=this.context.idx,t=this.context.length;if(e===t-1)return this.context.data.closeTime.data[e]<=Date.now();if(e===t-2){let e=this.context.marketData?.[t-1]?.closeTime;return void 0!==e&&e>Date.now()}return!1}}var eQ=Object.defineProperty,eX=(e,t,i)=>((e,t,i)=>t in e?eQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class e0{constructor(e,t,i){eX(this,"time"),eX(this,"index"),eX(this,"price"),this.time=e,this.index=t,this.price=i}copy(){return new e0(this.time,this.index,this.price)}toString(){return JSON.stringify({time:this.time,index:this.index,price:this.price})}}function e1(e){return null!==e&&"object"==typeof e&&"__value"in e&&(null===e.__value||"object"!=typeof e.__value)}let e2={series:e=>e instanceof m||"number"==typeof e||"string"==typeof e||"boolean"==typeof e||e1(e),string:e=>"string"==typeof e,color:e=>"string"==typeof e||null===e||"number"==typeof e&&isNaN(e)||e instanceof m,number:e=>"number"==typeof e,size:e=>"string"==typeof e||"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),object:e=>"object"==typeof e,point:e=>e instanceof e0,primitive:e=>"object"!=typeof e&&"function"!=typeof e,function:e=>"function"==typeof e,undefined:e=>void 0===e,null:e=>null===e,NaN:e=>isNaN(e),any:()=>!0,remaining_options:e=>null!==e&&"object"==typeof e&&!Array.isArray(e)&&!(e instanceof m)&&!(e instanceof e0)&&!function(e){return"object"==typeof e&&e&&(void 0!==e.title||void 0!==e._plotKey)&&void 0!==e.data&&void 0!==e.options}(e)&&!e1(e)},e3=new Set(["number","string","boolean","size"]);function e4(e){return e2.remaining_options(e)}function e6(e){let t=e[e.length-1];if(t&&"object"==typeof t&&"__callsiteId"in t)return e.pop().__callsiteId}function e5(e,t,i,r){Array.isArray(t)&&"string"==typeof t[0]&&(t=[t]);let n={},s={},a=e=>e instanceof m||e1(e),o=(e,t)=>e3.has(t)&&a(e)?m.from(e).get(0):e,l=(e,t)=>void 0!==t&&"series"!==t&&"any"!==t&&a(e)?m.from(e).get(0):e,h=Array(t.length).fill(!0);for(let r=0;r<e.length;r++){let a=e[r];if(void 0===a)continue;if(e2.remaining_options(a)){for(let e of(s={},Object.keys(a)))s[e]=l(a[e],i[e]);break}let c=t.map((e,t)=>h[t]?e[r]:void 0);for(let e=0;e<c.length;e++){let t=c[e];if(void 0===t){h[e]=!1;continue}let r=i[t];if("number"==typeof a&&isNaN(a)&&("number"===r||"series"===r))n[t]=a;else{let s=e2[i[t]],l="function"!=typeof s||s(a)?a:o(a,r);"function"==typeof s&&s(l)?n[t]=l:h[e]=!1}}}return{...n,...s,...r}}let e9=/^(\d{2})(\d{2})-(\d{2})(\d{2})$/;function e8(e){if("string"!=typeof e)return null;let t=e.trim();if(!t)return null;if("24x7"===t)return{windows:[{start:0,end:1440}],days:new Set([1,2,3,4,5,6,7])};let i=t.split(":");if(i.length>2)return null;let r=new Set;if(2===i.length){if(!/^[1-7]+$/.test(i[1]))return null;for(let e of i[1])r.add(parseInt(e,10))}else for(let e=1;e<=7;e++)r.add(e);let n=[];for(let e of i[0].split(",")){let t=e.match(e9);if(!t)return null;let i=parseInt(t[1],10),r=parseInt(t[2],10),s=parseInt(t[3],10),a=parseInt(t[4],10);if(i>23||r>59||s>23||a>59)return null;let o=60*i+r,l=0===s&&0===a?1440:60*s+a;n.push({start:o,end:l})}return{windows:n,days:r}}let e7=new Map;function te(e){if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;if(e7.has(e))return e7.get(e);let t=function(e){let t,i=/^(\d*)([a-zA-Z]?)$/.exec(e);if(!i||""===e)return null;let r=i[1],n=i[2],s=""===r?1:parseInt(r,10);if(!(s>=1))return null;switch(n){case"":t={unit:"",multiplier:s};break;case"S":case"s":t={unit:"S",multiplier:s};break;case"D":case"d":t={unit:"D",multiplier:s};break;case"W":case"w":t={unit:"W",multiplier:s};break;case"M":t={unit:"M",multiplier:s};break;case"m":t=""===r?{unit:"M",multiplier:1}:{unit:"",multiplier:s};break;case"H":case"h":t={unit:"",multiplier:60*s};break;default:t=null}return t&&""===t.unit&&t.multiplier>1440?null:t}(e.trim());return e7.set(e,t),t}function tt(e,t=!1){return""===e.unit?String(e.multiplier):"S"===e.unit?`${e.multiplier}S`:1!==e.multiplier||t?`${e.multiplier}${e.unit}`:e.unit}function ti(e){let t=te(e);return t?tt(t):null}function tr(e){switch(e.unit){case"S":return e.multiplier;case"":return 60*e.multiplier;case"D":return 86400*e.multiplier;case"W":return 604800*e.multiplier;case"M":return 2628003*e.multiplier}}function tn(e){let t=Date.UTC(e,0,1),i=new Date(t).getUTCDay();return t+(8-i)%7*864e5}function ts(e,t){let i=t.multiplier,r=new Date(e),n=r.getUTCFullYear();switch(t.unit){case"S":case"":{let i=1e3*tr(t),r=864e5*Math.floor(e/864e5);return r+Math.floor((e-r)/i)*i}case"D":{let t=Date.UTC(n,0,1),r=Math.floor((e-t)/864e5);return t+Math.floor(r/i)*i*864e5}case"W":{let t=864e5*Math.floor(e/864e5)-(r.getUTCDay()+6)%7*864e5,n=tn(new Date(t).getUTCFullYear()),s=Math.round((t-n)/6048e5);return n+Math.floor(s/i)*i*6048e5}case"M":return Date.UTC(n,Math.floor(r.getUTCMonth()/i)*i,1)}}let ta={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6};function to(e,t,i=1){if("month"===t){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+i,1,t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())}return e+i*({second:1e3,minute:6e4,hour:36e5,day:864e5,week:7*864e5})[t]}function tl(e,t,i){let[r,n,s]=e.split("-").map(Number),[a,o]=t.split(":").map(Number),l=Date.UTC(r,n-1,s,a,o,0,0),h=new Intl.DateTimeFormat("en-US",{timeZone:i,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(l)),c=e=>parseInt(h.find(t=>t.type===e).value,10),p=c("year"),u=c("month"),d=c("day"),m=c("hour");24===m&&(m=0);let f=Date.UTC(p,u-1,d,m,c("minute"),0,0)-l;return l-f}function th(e,t,i,r,n=1){if("24x7"===t)return to(e,r,n);let s=t.split("-")[1];if(!s||4!==s.length)return to(e,r,n);let a=s.slice(0,2),o=s.slice(2,4),l=`${a}:${o}`,h=tc(e,i);if("second"===r||"minute"===r||"hour"===r)return Math.min(e+n*({second:1e3,minute:6e4,hour:36e5})[r],tl(h,l,i));if("day"===r)return tl(h,l,i);if("week"===r){let t=new Date(e).getUTCDay();return tl(tc(e+864e5*(t<=5?5-t:5-t+7),i),l,i)}if("month"===r){let t=new Date(e),r=new Date(new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+n,1)).getTime()-864e5);for(;0===r.getUTCDay()||6===r.getUTCDay();)r.setUTCDate(r.getUTCDate()-1);return tl(r.toISOString().split("T")[0],l,i)}return to(e,r,n)}function tc(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}let tp=new Map;function tu(e){let t=e??"",i=tp.get(t);if(!i){let e=e8(t)?.windows[0];i=e?{open:e.start%1440,overnight:e.start>=e.end&&e.end<1440}:{open:0,overnight:!1},tp.set(t,i)}return i}let td=new Map,tm=new Map,tf=(e,t,i)=>(e.size>=4096&&e.clear(),e.set(t,i),i);function ty(e,t,i,r){return"D"!==t.unit&&"W"!==t.unit&&"M"!==t.unit?ts(e,t):ts(function(e,t,i){let r=`${t}|${i}|${e}`,n=td.get(r);if(void 0!==n)return n;let s=tb(e,t),a=Date.UTC(s.year,s.month-1,s.day),{open:o,overnight:l}=tu(i);return tf(td,r,l&&60*s.hour+s.minute>=o?a+864e5:a)}(e,i,r),t)}var t_=Object.defineProperty,tg=(e,t,i)=>((e,t,i)=>t in e?t_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function tx(e){let t=e=>e instanceof m?e.get(0):e;return e.map(e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype?Object.fromEntries(Object.entries(e).map(([e,i])=>[e,t(i)])):t(e))}function tb(e,t){let i=t.trim();if("UTC"===i||"GMT"===i||"Etc/UTC"===i){let t=new Date(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),dayOfWeek:t.getUTCDay()}}let r=i.match(/^(?:UTC|GMT)([+-])(\d{1,2})(?::(\d{2}))?$/i);if(r){let t="+"===r[1]?1:-1,i=new Date(e+t*(60*parseInt(r[2],10)+parseInt(r[3]||"0",10))*6e4);return{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),hour:i.getUTCHours(),minute:i.getUTCMinutes(),second:i.getUTCSeconds(),dayOfWeek:i.getUTCDay()}}try{let i=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",weekday:"short",hour12:!1}).formatToParts(new Date(e)),r=e=>parseInt(i.find(t=>t.type===e)?.value||"0",10),n=r("hour");24===n&&(n=0);let s=i.find(e=>"weekday"===e.type)?.value||"Sun";return{year:r("year"),month:r("month"),day:r("day"),hour:n,minute:r("minute"),second:r("second"),dayOfWeek:({Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6})[s]??0}}catch{let t=new Date(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),dayOfWeek:t.getUTCDay()}}}let tv=[["timeframe"],["timeframe","bars_back"],["timeframe","session","bars_back"],["timeframe","session","bars_back","timeframe_bars_back"],["timeframe","session","timezone","bars_back","timeframe_bars_back"]],tw={timeframe:"string",session:"string",timezone:"string",bars_back:"number",timeframe_bars_back:"number"};class tS{constructor(e,t="openTime"){tg(this,"context"),tg(this,"dataField"),this.context=e,this.dataField=t}get __value(){return this.context.data[this.dataField]}param(e,t=0){return m.from(e).get(t)}any(...e){let t,i=e5(tx(e),tv,tw),r=i.bars_back??0,n=i.timeframe||"",s=this.context.data[this.dataField],a=m.from(s).get(r);if(isNaN(a)||null==a)return NaN;if(n&&ti(n)!==ti(this.context.timeframe)){let e=te(n);if(!e)throw new ei(`Cannot parse resolution '${n}'. - Invalid format`,"time");let i=this.context.pine?.syminfo;t=function(e,t,i,r){if("D"!==t.unit&&"W"!==t.unit&&"M"!==t.unit)return ts(e,t);let n=ty(e,t,i,r),s=`${i}|${r}|${n}`,a=tm.get(s);if(void 0!==a)return a;let{open:o,overnight:l}=tu(r);return tf(tm,s,tl(new Date(l?n-864e5:n).toISOString().slice(0,10),`${String(Math.floor(o/60)).padStart(2,"0")}:${String(o%60).padStart(2,"0")}`,i))}(a,e,i?.timezone||"UTC",i?.session)}else t=a;if(void 0!==i.session&&""!==i.session){let e=i.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._isInSession(t,i.session,e)?t:NaN}return t}_isInSession(e,t,i){let r=e8(t);if(!r)throw new ei(`Invalid session specification: "${t}"`,"time");let n=tb(e,i),s=60*n.hour+n.minute,a=n.dayOfWeek+1,o=a%7+1;for(let{start:e,end:t}of r.windows)if(e<t){if(s>=e&&s<t&&r.days.has(a))return!0}else if(s>=e&&r.days.has(o)||s<t&&r.days.has(a))return!0;return!1}}let tE=[[],["time"],["time","timezone"]],tN={time:"number",timezone:"string"};class tT{constructor(e,t){tg(this,"context"),tg(this,"extractor"),tg(this,"_cache",[]),tg(this,"_cacheTimezone",null),this.context=e,this.extractor=t}get __value(){let e=this.context.data.openTime,t=e instanceof m?e.data:Array.isArray(e)?e:[],i=this.context.pine?.syminfo?.timezone||"UTC";i!==this._cacheTimezone&&(this._cache=[],this._cacheTimezone=i);let r=this._cache;r.length>t.length&&(r.length=t.length);for(let e=r.length;e<t.length;e++){let n=t[e];r.push(null==n||isNaN(n)?NaN:this.extractor(tb(n,i)))}return new m(r,e instanceof m?e.offset:0)}param(e,t=0){return m.from(e).get(t)}any(...e){let t=tx(e);if(0===t.length)return this.__value.get(0);let i=e5(t,tE,tN),r=i.time;if(void 0===r||isNaN(r))return NaN;let n=tb(r,i.timezone||this.context.pine?.syminfo?.timezone||"UTC");return this.extractor(n)}}let tk={dayofmonth:e=>e.day,dayofweek:e=>0===e.dayOfWeek?1:e.dayOfWeek+1,hour:e=>e.hour,minute:e=>e.minute,month:e=>e.month,second:e=>e.second,weekofyear:e=>(function(e,t,i){let r=new Date(Date.UTC(e,t-1,i)),n=r.getUTCDay()||7;r.setUTCDate(r.getUTCDate()+4-n);let s=new Date(Date.UTC(r.getUTCFullYear(),0,1));return Math.ceil(((r.getTime()-s.getTime())/864e5+1)/7)})(e.year,e.month,e.day),year:e=>e.year};var tA=Object.defineProperty,tI=(e,t,i)=>((e,t,i)=>t in e?tA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class tC{constructor(e){this.context=e,tI(this,"regular","regular"),tI(this,"extended","extended")}get _timezone(){return this.context.pine?.syminfo?.timezone||"UTC"}_dayKey(e){let t=tb(e,this._timezone);return`${t.year}-${t.month}-${t.day}`}get isfirstbar(){let e=this.context.idx,t=this.context.marketData;return!!Array.isArray(t)&&!!t[e]&&(0===e||this._dayKey(t[e].openTime)!==this._dayKey(t[e-1].openTime))}get islastbar(){let e=this.context.idx,t=this.context.marketData;return!!Array.isArray(t)&&!!t[e]&&(e===t.length-1||this._dayKey(t[e].openTime)!==this._dayKey(t[e+1].openTime))}get isfirstbar_regular(){return this.isfirstbar}get islastbar_regular(){return this.islastbar}get ismarket(){return!0}get ispremarket(){return!1}get ispostmarket(){return!1}}function tM(e,t,i){let r=i.value;return"function"!=typeof r||(i.value=function(...e){return this&&this.context&&this.context.isSecondaryContext?null:r.apply(this,e)}),i}var tP=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,tR=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?tD(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&tP(t,i,s),s},tO=(e,t,i)=>((e,t,i)=>t in e?tP(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let tj=[["dateString"],["year","month","day","hour","minute","second"],["timezone","year","month","day","hour","minute","second"]],tV={dateString:"string",timezone:"string",year:"number",month:"number",day:"number",hour:"number",minute:"number",second:"number"},t$=["title","shorttitle","overlay","format","precision","scale","max_bars_back","timeframe","timeframe_gaps","explicit_plot_zorder","max_lines_count","max_labels_count","max_boxes_count","calc_bars_count","max_polylines_count","dynamic_requests","behind_chart"],tL={title:"string",shorttitle:"string",overlay:"boolean",format:"string",precision:"number",scale:"string",max_bars_back:"number",timeframe:"string",timeframe_gaps:"boolean",explicit_plot_zorder:"boolean",max_lines_count:"number",max_labels_count:"number",max_boxes_count:"number",calc_bars_count:"number",max_polylines_count:"number",dynamic_requests:"boolean",behind_chart:"boolean"},tB=["title","overlay","dynamic_requests"],tF={title:"string",overlay:"boolean",dynamic_requests:"boolean"};class tq{get __value(){return NaN}param(e,t=0){return m.from(e).get(t)}any(e){if(e instanceof tq)return!0;let t=m.from(e).get(0);return t instanceof tq||null==t||("number"==typeof t?t!=t:""===t||"object"==typeof t&&!0===t._deleted)}}let tz={freq_all:"all",freq_once_per_bar:"once_per_bar",freq_once_per_bar_close:"once_per_bar_close"},tU=["message","freq"],tW=["condition","title","message"];class tK{constructor(e){this.context=e,tO(this,"_firedKeys",new Set),tO(this,"_fallbackCounter",0),tO(this,"_fallbackLastExecTick",-1)}get freq_all(){return tz.freq_all}get freq_once_per_bar(){return tz.freq_once_per_bar}get freq_once_per_bar_close(){return tz.freq_once_per_bar_close}param(e,t,i){return m.from(e).get(0)}any(...e){let t,i=e6(e),[r,n]=eN(e,tU),s=m.from(r).get(0),a=n?m.from(n).get(0):tz.freq_once_per_bar,o="string"==typeof a&&a.startsWith("alert.freq_")?a.slice(11):a;if(i)t=i;else{let e=this.context._execTick||0;e!==this._fallbackLastExecTick&&(this._fallbackCounter=0,this._fallbackLastExecTick=e),t=`alert_${this._fallbackCounter++}`}let l=this.context.idx,h=this.context.pine?.barstate?.isrealtime??l===this.context.length-1;if("realtime"===(this.context._alertMode||"realtime")&&!h)return;let c=`${t}:${l}`;if(o===tz.freq_once_per_bar){if(this._firedKeys.has(c))return;this._firedKeys.add(c)}else if(o===tz.freq_once_per_bar_close){if(!(this.context.pine?.barstate?.isconfirmed??!0)||this._firedKeys.has(c))return;this._firedKeys.add(c)}this.context.alerts.push({type:"alert",id:t,message:s,freq:o,bar_index:l,time:this.context.data.openTime?.data?.[l]??0})}}tR([tM],tK.prototype,"any",1);class tG{constructor(e){this.context=e,tO(this,"_acCounter",0),tO(this,"_acLastExecTick",-1),tO(this,"_acFiredKeys",new Set)}extractPlotOptions(e){let t={};for(let i in e)t[i]=m.from(e[i]).get(0);return t}indicator(...e){let t=e5(e.map(e=>e instanceof m?e.get(0):e),t$,tL);return this.context.indicator={title:"",shorttitle:"",overlay:!1,format:"inherit",precision:10,scale:"points",max_bars_back:0,timeframe:"",timeframe_gaps:!0,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,calc_bars_count:0,max_polylines_count:50,dynamic_requests:!1,behind_chart:!0,...t,...this.context._propOverrides??{}},this.context.indicator}library(...e){let t=e.map(e=>e instanceof m?e.get(0):e);return this.indicator(e5(t,tB,tF))}get bar_index(){return this.context.idx}na(e){let t=m.from(e).get(0);return null==t||""===t||"number"==typeof t&&isNaN(t)||"object"==typeof t&&!0===t._deleted}nz(e,t=0){let i=m.from(e).get(0),r=m.from(t).get(0);return null==i||"number"==typeof i&&isNaN(i)?r:i}fixnan(e){let t=m.from(e);for(let e=0;e<t.length;e++){let i=t.get(e);if(null!=i&&!("number"==typeof i&&isNaN(i)))return i}return NaN}alertcondition(...e){let[t,i,r]=eN(e,tW),n=m.from(t).get(0),s=this.context.idx,a=this.context._execTick||0;a!==this._acLastExecTick&&(this._acCounter=0,this._acLastExecTick=a);let o=`alertcondition_${this._acCounter++}`;if(!n)return;let l=this.context.pine?.barstate?.isrealtime??s===this.context.length-1;if("realtime"===(this.context._alertMode||"realtime")&&!l)return;let h=`${o}:${s}`;if(this._acFiredKeys.has(h))return;this._acFiredKeys.add(h);let c=i?m.from(i).get(0):"",p=r?m.from(r).get(0):"";this.context.alerts.push({type:"alertcondition",id:o,title:c,message:p,bar_index:s,time:this.context.data.openTime?.data?.[s]??0})}error(...e){console.error("error called but is currently not implemented",e)}max_bars_back(e,t){}timestamp(...e){let t=e5(e.map(e=>e instanceof m?e.get(0):e),tj,tV);if(void 0!==t.year){let e=t.year,i=t.month,r=t.day,n=t.hour||0,s=t.minute||0,a=t.second||0,o=t.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._timestampFromComponents(o,e,i,r,n,s,a)}if(void 0!==t.dateString){let e=t.dateString.trim();if(/[Zz]$/.test(e)||/[+-]\d{2}:?\d{2}$/.test(e))return new Date(e).getTime();let i=new Date(e.includes("T")?e+"Z":e.replace(/\s+/,"T")+"Z");if(isNaN(i.getTime())&&(i=new Date(`${e} UTC`)),!isNaN(i.getTime())){let e=this.context.pine?.syminfo?.timezone||"UTC";return this._timestampFromComponents(e,i.getUTCFullYear(),i.getUTCMonth()+1,i.getUTCDate(),i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds())}return new Date(e).getTime()}return NaN}_timestampFromComponents(e,t,i,r,n,s,a){let o=new Date(Date.UTC(t,i-1,r,n,s,a));t>=0&&t<100&&o.setUTCFullYear(t);let l=e.trim();if("UTC"===l||"GMT"===l||"Etc/UTC"===l)return o.getTime();let h=l.match(/^(?:UTC|GMT)([+-])(\d{1,2})(?::(\d{2}))?$/i);if(h){let e="+"===h[1]?1:-1,t=parseInt(h[2],10),i=parseInt(h[3]||"0",10);return o.getTime()-e*(60*t+i)*6e4}try{return this._timestampFromIANA(e,t,i,r,n,s,a)}catch{return o.getTime()}}_timestampFromIANA(e,t,i,r,n,s,a){let o=new Date(Date.UTC(t,i-1,r,n,s,a));t>=0&&t<100&&o.setUTCFullYear(t);let l=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(o),h=e=>parseInt(l.find(t=>t.type===e)?.value||"0",10),c=h("year"),p=h("month"),u=h("day"),d=h("hour");24===d&&(d=0);let m=new Date(Date.UTC(c,p-1,u,d,h("minute"),h("second")));c>=0&&c<100&&m.setUTCFullYear(c);let f=m.getTime()-o.getTime();return o.getTime()-f}bool(e){let t=m.from(e).get(0);return"boolean"==typeof t?t:null!=t&&!isNaN(t)&&0!==t}int(e){let t=m.from(e).get(0);if("number"!=typeof t)throw Error(`Cannot call "int" with argument "x"="${t}". An argument of "literal string" type was used but a "simple int" is expected.`);return Math.trunc(t)}float(e){let t=m.from(e).get(0);if("number"!=typeof t)throw Error(`Cannot call "float" with argument "x"="${t}". An argument of "literal string" type was used but a "const float" is expected.`);return t}string(e){let t=m.from(e).get(0);return null==t||"number"==typeof t&&isNaN(t)?"":t.toString()}Type(e,t){let i=Object.keys(e),r={},n={},s=this.context?.pineVersion;for(let t of i){let i=e[t];i instanceof m&&(i=i.data),Array.isArray(i)?(r[t]=i[0],n[t]=i[1]):r[t]=i}let a={__name__:t,new:function(...e){let t={},o=null;if(e.length>0){let t=e[e.length-1];if(t&&"object"==typeof t&&!(t instanceof m)&&!Array.isArray(t)&&!(t instanceof p)){let r=Object.keys(t);r.length>0&&r.some(e=>i.includes(e))&&(o=t,e=e.slice(0,-1))}}for(let a=0;a<i.length;a++){let l=i[a];if(o&&l in o?t[l]=o[l]:a<e.length?t[l]=e[a]:l in n&&(t[l]=m.from(n[l]).get(0)),/(^|\s)string$/.test(r[l]??"")){let e=t[l];(null==e||"number"==typeof e&&isNaN(e))&&(t[l]="")}if(s>=6&&/(^|\s)bool$/.test(r[l]??"")){let e=t[l];(null==e||"number"==typeof e&&isNaN(e))&&(t[l]=!1)}}return new p(t,this.context,a)},copy:function(e){return new p(e._fieldValues(),this.context,a)},_fieldDefaults:n,_definitionKeys:i};return a}}tR([tM],tG.prototype,"alertcondition",1);let tH=new Set(["open","high","low","close","hl2","hlc3","ohlc4","hlcc4","volume"]);function tY(e,t){if(!tH.has(t))return;let i=e?.data?.[t];if(null!=i)return m.from(i).get(0)}let tZ=[["defval","title","tooltip","inline","group","display"],["defval","title","tooltip","group","confirm","display"],["defval","title","tooltip","inline","group","confirm","display"],["defval","title","options","tooltip","inline","group","confirm","display"],["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display"]],tJ={defval:"primitive",title:"string",tooltip:"string",inline:"string",group:"string",display:"string",confirm:"boolean",options:"array",minval:"number",maxval:"number",step:"number"},tQ=e=>!!e&&"object"==typeof e&&(Object.prototype.hasOwnProperty.call(e,"__varId")||Object.prototype.hasOwnProperty.call(e,"__inputId"));function tX(e){let t,i;for(;e.length&&tQ(e[e.length-1]);){let r=e[e.length-1];void 0!==r.__inputId?t=r.__varId??t:t??(t=r.__varId),i??(i=r.__inputId),e=e.slice(0,-1)}let r=e5(e,tZ,tJ);return void 0!==t&&(r.__varId=t),void 0!==i&&(r.__inputId=i),r}function t0(e,t){return t.__inputId&&e.inputs&&void 0!==e.inputs[t.__inputId]?e.inputs[t.__inputId]:t.__varId&&e.inputs&&void 0!==e.inputs[t.__varId]?e.inputs[t.__varId]:t.title&&e.inputs&&void 0!==e.inputs[t.title]?e.inputs[t.title]:t.defval}function t1(e,t){let i;for(let e=t.length-1;e>=0&&tQ(t[e]);e--)i??(i=t[e].__inputId);if(void 0===i)return tX(t);let r=e._inputOptionsCache??(e._inputOptionsCache=new Map),n=r.get(i);return n||(n=tX(t),r.set(i,n)),n}var t2=Object.defineProperty,t3=(e,t,i)=>((e,t,i)=>t in e?t2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let t4={any:function(e){return(...t)=>{let i=tX(t),r=t0(e,i);if("string"==typeof r&&"number"==typeof i.defval){let t=tY(e,r);if(void 0!==t)return t}return r}},bool:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},color:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},enum:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},float:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},int:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},param:function(e){return(e,t=0)=>m.from(e).get(t)},price:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},session:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},source:function(e){return(...t)=>{let i=tX(t),r=t0(e,i);if("string"==typeof r){let t=tY(e,r);return void 0!==t?t:i.defval}return r}},string:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},symbol:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},text_area:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},time:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}},timeframe:function(e){return(...t)=>{let i=t1(e,t);return t0(e,i)}}};class t6{constructor(e){this.context=e,t3(this,"any"),t3(this,"bool"),t3(this,"color"),t3(this,"enum"),t3(this,"float"),t3(this,"int"),t3(this,"param"),t3(this,"price"),t3(this,"session"),t3(this,"source"),t3(this,"string"),t3(this,"symbol"),t3(this,"text_area"),t3(this,"time"),t3(this,"timeframe"),Object.entries(t4).forEach(([t,i])=>{this[t]=i(e)})}}let t5=(1n<<48n)-1n,t9=e=>(25214903917n^BigInt(Math.trunc(e)))&t5,t8=e=>25214903917n*e+11n&t5,t7=e=>Number.isNaN(e)?NaN:Math.sign(e)*Math.round(Math.abs(e)),ie=10n**10n-2n,it=2n*10n**10n;function ii(e){let[t,i]=String(e).split("e"),[r,n=""]=t.split("."),s=n.length-Number(i??0),a=BigInt(r+n);return s>=0?[a,s]:[a*10n**BigInt(-s),0]}var ir=Object.defineProperty,is=(e,t,i)=>((e,t,i)=>t in e?ir(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ia{constructor(e=8){is(this,"buf"),is(this,"head",0),is(this,"mask"),is(this,"size",0);let t=8;for(;t<e;)t*=2;this.buf=Array(t),this.mask=t-1}static from(e){let t=new ia(e.length+1);for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t}push(e){this.size===this.buf.length&&this.grow(),this.buf[this.head+this.size&this.mask]=e,this.size++}shift(){let e=this.buf[this.head];return this.head=this.head+1&this.mask,this.size--,e}at(e){return this.buf[this.head+this.size-1-e&this.mask]}oldest(){return this.buf[this.head]}toArray(){let e=Array(this.size);for(let t=0;t<this.size;t++)e[t]=this.at(t);return e}grow(){let e=this.buf.length,t=Array(2*e);for(let e=0;e<this.size;e++)t[e]=this.buf[this.head+e&this.mask];this.buf=t,this.head=0,this.mask=2*e-1}}function io(e,t){let i=0,r=e.length;for(;i<r;){let n=i+r>>>1;e[n]<t?i=n+1:r=n}return i}function il(e,t){let i=0,r=e.length;for(;i<r;){let n=i+r>>>1;e[n]<=t?i=n+1:r=n}return i}function ih(e,t){e.splice(il(e,t),0,t)}function ic(e,t){e.splice(io(e,t),1)}class ip{constructor(){is(this,"counts",new Map),is(this,"byCount",new Map),is(this,"maxCount",0)}add(e){let t=this.counts.get(e)||0;t>0&&ic(this.byCount.get(t),e),this.counts.set(e,t+1);let i=this.byCount.get(t+1);i||this.byCount.set(t+1,i=[]),ih(i,e),t+1>this.maxCount&&(this.maxCount=t+1)}remove(e){let t=this.counts.get(e),i=this.byCount.get(t);ic(i,e),t>1?(this.counts.set(e,t-1),ih(this.byCount.get(t-1),e)):this.counts.delete(e),t===this.maxCount&&0===i.length&&this.maxCount--}mode(){return 0===this.maxCount?NaN:this.byCount.get(this.maxCount)[0]}}let iu={},id={backfill:(e,t,i,r)=>{let n=m.from(i);for(;e.length<r;)e.push(n.get(e.length))}};class im{constructor(e=!1){this.carry=e,is(this,"lastIdx",-1),is(this,"ring",new ia),is(this,"calls",0),is(this,"cap",NaN),is(this,"t",null),is(this,"agg"),is(this,"tAgg"),is(this,"tCalls",0),is(this,"fast",{rebuilt:!1,x:void 0,evict:!1,cap:NaN}),is(this,"scratch",[])}begin(e){if(e<=this.lastIdx)return;let t=this.t;if(t){if(t.rebuilt)this.ring=ia.from(t.values),this.cap=t.cap,this.rebuilt();else{this.ring.push(t.x);let e=t.evict?this.ring.shift():void 0,i=this.cap===t.cap;this.cap=t.cap,this.pushed(t.x,t.evict,e,i)}this.calls=this.tCalls;let e=this.agg;this.agg=this.tAgg,this.tAgg=e,this.t=null}if(this.carry&&this.lastIdx>=0&&this.ring.size>0){let t=Math.min(e-this.lastIdx-1,this.cap);for(let e=0;e<t;e++){let e=this.ring.at(0);this.ring.push(e);let t=this.ring.size>this.cap;this.pushed(e,t,t?this.ring.shift():void 0,!0)}}this.lastIdx=e}push(e,t,i,r=iu,n){let s=this.calls+1;this.tCalls=s;let a=this.ring.size,o=!!r.backfill&&Math.min(a+1,i)<i&&(s>=i||e>=i-1);if(a<=i&&!o){let e=a+1>i;e&&r.dropped&&r.dropped(this.ring.oldest(),this);let n=this.fast;n.x=t,n.evict=e,n.cap=i,this.t=n;return}let l=this.ring.toArray();if(l.unshift(t),r.trimOnce){if(l.length>i){let e=l.pop();r.dropped&&r.dropped(e,this)}}else for(;l.length>i;){let e=l.pop();r.dropped&&r.dropped(e,this)}o&&r.backfill(l,this,n,i),this.t={rebuilt:!0,values:l,cap:i}}set(e,t){this.tCalls=this.calls+1,this.t={rebuilt:!0,values:e,cap:t}}get size(){let e=this.t;return e?e.rebuilt?e.values.length:this.ring.size+ +!e.evict:this.ring.size}at(e){let t=this.t;return t?t.rebuilt?t.values[e]:0===e?t.x:this.ring.at(e-1):this.ring.at(e)}evicted(){return this.ring.oldest()}values(e){let t=this.t;if(t&&t.rebuilt)return t.values;let i=this.scratch;i.length=e;let r=0;t&&(i[r++]=t.x);let n=this.ring;for(let t=0;r<e;r++,t++)i[r]=n.at(t);return i}pushed(e,t,i,r){}rebuilt(){}}var iy=Object.defineProperty,i_=(e,t,i)=>((e,t,i)=>t in e?iy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let ig=e=>Number.isNaN(e);function ix(e,t,i){let r=0x8000001*e,n=r-(r-e),s=e-n,a=(r=0x8000001*t)-(r-t),o=t-a;return n*a-i+n*o+s*a+s*o}class ib{constructor(e=0){i_(this,"v",new Float64Array(64)),i_(this,"nan",new Int32Array(65)),i_(this,"ph"),i_(this,"pl"),i_(this,"qh"),i_(this,"ql"),i_(this,"off",0),i_(this,"start",0),i_(this,"end",0),i_(this,"keep",5e3),this.ph=e>=1?new Float64Array(65):null,this.pl=e>=1?new Float64Array(65):null,this.qh=e>=2?new Float64Array(65):null,this.ql=e>=2?new Float64Array(65):null}get size(){return this.end-this.start}keepFor(e){2*e>this.keep&&(this.keep=2*e)}grow(){let e=2*this.v.length,t=(e,t)=>{let i=new Float64Array(t);return i.set(e),i};this.v=t(this.v,e);let i=new Int32Array(e+1);i.set(this.nan),this.nan=i,this.ph&&(this.ph=t(this.ph,e+1),this.pl=t(this.pl,e+1)),this.qh&&(this.qh=t(this.qh,e+1),this.ql=t(this.ql,e+1))}push(e){let t=this.off+this.end-this.start;t>=this.v.length&&(this.grow(),t=this.off+this.end-this.start),this.v[t]=e;let i=ig(e);this.nan[t+1]=this.nan[t]+ +!!i;let r=i?0:e;if(this.ph){let e=this.ph[t],i=e+r,n=i-e,s=e-(i-n)+(r-n)+this.pl[t],a=i+s;this.ph[t+1]=a,this.pl[t+1]=s-(a-i)}if(this.qh){let e=this.end,i=e*r,n=ix(e,r,i),s=this.qh[t],a=s+i,o=a-s,l=s-(a-o)+(i-o)+n+this.ql[t],h=a+l;this.qh[t+1]=h,this.ql[t+1]=l-(h-a)}this.end++}truncate(e){this.end=e}compact(){let e=this.size-this.keep;if(e<=0||this.off+this.size<.75*this.v.length)return;let t=this.size-e,i=this.off+e;this.v.copyWithin(0,i,i+t),this.nan.copyWithin(0,i,i+t+1),this.ph&&(this.ph.copyWithin(0,i,i+t+1),this.pl.copyWithin(0,i,i+t+1)),this.qh&&(this.qh.copyWithin(0,i,i+t+1),this.ql.copyWithin(0,i,i+t+1)),this.off=0,this.start+=e}get(e){return this.v[this.off+e-this.start]}at(e){let t=this.end-1-e;return t>=this.start?this.v[this.off+t-this.start]:NaN}view(e){let t=this.off+this.end-this.start;return this.v.subarray(t-e,t)}nas(e){let t=this.off+this.end-this.start;return this.nan[t]-this.nan[t-e]}diff(e,t,i){let r=this.off+this.end-this.start,n=e[r],s=-e[r-i],a=n+s,o=a-n,l=n-(a-o)+(s-o)+(t[r]-t[r-i]),h=a+l;return[h,l-(h-a)]}sum(e){let[t,i]=this.diff(this.ph,this.pl,e);return t+i}wsum(e){let[t,i]=this.diff(this.qh,this.ql,e),[r,n]=this.diff(this.ph,this.pl,e),s=this.end-e-1,a=s*r,o=ix(s,r,a)+s*n,l=-a,h=t+l,c=h-t;return h+(t-(h-c)+(l-c)+(i-o))}}class iv{constructor(){i_(this,"lo",0),i_(this,"hi",0),i_(this,"savedLo",0),i_(this,"savedHi",0),i_(this,"log",[])}commit(){this.log.length=0,this.savedLo=this.lo,this.savedHi=this.hi}rollback(){for(let e=this.log.length-1;e>=0;e--){let[t,i]=this.log[e];t?this.remove(i):this.add(i)}this.log.length=0,this.lo=this.savedLo,this.hi=this.savedHi}doAdd(e){ig(e)||(this.add(e),this.log.push([!0,e]))}doRemove(e){ig(e)||(this.remove(e),this.log.push([!1,e]))}sync(e,t,i=0){let r=e.end-i,n=Math.max(e.start,r-t);if(n>=this.hi||r<=this.lo){for(;this.lo<this.hi;)this.doRemove(e.get(this.lo++));this.lo=this.hi=n}for(;this.hi>r;)this.doRemove(e.get(--this.hi));for(;this.lo<n;)this.doRemove(e.get(this.lo++));for(;this.hi<r;)this.doAdd(e.get(this.hi++));for(;this.lo>n;)this.doAdd(e.get(--this.lo))}}class iw extends iv{constructor(){super(...arguments),i_(this,"sorted",[])}add(e){this.sorted.splice(il(this.sorted,e),0,e)}remove(e){this.sorted.splice(io(this.sorted,e),1)}}class iS extends iv{constructor(){super(...arguments),i_(this,"counts",new ip)}add(e){this.counts.add(e)}remove(e){this.counts.remove(e)}}class iE{constructor(e,t=!1){this.max=e,this.newest=t,i_(this,"idx",[]),i_(this,"val",[]),i_(this,"head",0),i_(this,"lastNa",-1),i_(this,"synced",0),i_(this,"popped",[]),i_(this,"pushedCount",0),i_(this,"saved",{head:0,lastNa:-1,synced:0})}commit(e){for(;this.head<this.idx.length&&this.idx[this.head]<e.start;)this.head++;this.head>1024&&2*this.head>this.idx.length&&(this.idx.splice(0,this.head),this.val.splice(0,this.head),this.head=0),this.popped.length=0,this.pushedCount=0,this.saved={head:this.head,lastNa:this.lastNa,synced:this.synced}}rollback(){this.idx.length-=this.pushedCount,this.val.length-=this.pushedCount;for(let e=this.popped.length-1;e>=0;e--)this.idx.push(this.popped[e][0]),this.val.push(this.popped[e][1]);this.popped.length=0,this.pushedCount=0,this.head=this.saved.head,this.lastNa=this.saved.lastNa,this.synced=this.saved.synced}sync(e){for(this.synced<e.start&&(this.synced=e.start);this.synced<e.end;this.synced++){let t=this.synced,i=e.get(t);if(ig(i)){this.lastNa=t;continue}for(;this.idx.length>this.head;){let e=this.val[this.val.length-1];if(!(this.max?e<i||this.newest&&e===i:e>i||this.newest&&e===i))break;this.pushedCount>0?this.pushedCount--:this.popped.push([this.idx[this.idx.length-1],e]),this.idx.pop(),this.val.pop()}this.idx.push(t),this.val.push(i),this.pushedCount++}}find(e,t){let i=Math.max(e.end-t,this.lastNa+1,e.start),r=this.head,n=this.idx.length;for(;r<n;){let e=r+n>>1;this.idx[e]<i?r=e+1:n=e}return r<this.idx.length?this.idx[r]:-1}}class iN{constructor(e=0,t,i=!0){this.fill=t,this.backfill=i,i_(this,"h"),i_(this,"lastIdx",-1),i_(this,"savedEnd",0),i_(this,"newBar",!1),this.h=new ib(e)}write(e){let t=this.h;t.push(this.fill?this.fill(e,t.size?t.at(0):NaN):e)}push(e,t,i,r){this.visit(e,i,r),this.write(null==t?NaN:Number(t))}visit(e,t,i){let r=this.h;if(r.keepFor(t+1),e!==this.lastIdx){if(this.newBar=!0,this.lastIdx<0){if(this.backfill&&i)for(let r=Math.max(0,e-Math.max(5e3,2*(t+1)));r<e;r++){let t=i.get(e-r);this.write(null==t?NaN:Number(t))}}else{r.compact();let i=Math.min(e-this.lastIdx-1,Math.max(5e3,2*(t+1)));if(r.size)for(let e=0;e<i;e++)r.push(r.at(0))}this.savedEnd=r.end,this.lastIdx=e}else this.newBar=!1,r.truncate(this.savedEnd)}}var iT=Object.defineProperty,ik=(e,t,i)=>((e,t,i)=>t in e?iT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let iA=e=>null==e||"number"==typeof e&&Number.isNaN(e),iI=(e,t)=>"function"==typeof e?e(t):e.get(t);class iC{constructor(e){ik(this,"h",new ib(1)),ik(this,"lastIdx",-1),ik(this,"savedEnd",0),ik(this,"sorted"),ik(this,"counts"),ik(this,"hi"),ik(this,"lo"),ik(this,"bars"),ik(this,"length",0),ik(this,"sum",NaN),ik(this,"scratch",[]),this.sorted="sorted"===e?new iw:null,this.counts="counts"===e?new iS:null,this.hi="extremes"===e?new iE(!0,!0):null,this.lo="extremes"===e?new iE(!1,!0):null,this.bars="extremes"===e?new ib:null}push(e,t){this.h.push(e),this.bars?.push(t)}max(){return this.h.get(this.hi.find(this.h,this.length))}min(){return this.h.get(this.lo.find(this.h,this.length))}maxBar(){return this.bars.get(this.hi.find(this.h,this.length))}minBar(){return this.bars.get(this.lo.find(this.h,this.length))}at(e){return this.h.at(e)}values(){let e=this.length,t=this.scratch;t.length=e;let i=this.h.view(e);for(let r=0;r<e;r++)t[r]=i[e-1-r];return t}kth(e){return this.sorted.sorted[e]}mode(){return this.counts.counts.mode()}}function iM(e,t,i,r,n=!1,s,a="values"){e.taState||(e.taState={});let o=e.taState[t];o||(o=e.taState[t]=new iC(n));let l=o.h;if(!(r>=1))return;if(l.keepFor(r),o.bars?.keepFor(r),e.idx!==o.lastIdx){if(o.lastIdx<0)for(let t=Math.min(e.idx,5e3+2*r);t>=1;t--){let r=iI(i,t);iA(r)||o.push(r,e.idx-t)}else l.compact(),o.bars?.compact();o.savedEnd=l.end,o.sorted?.commit(),o.counts?.commit(),o.hi?.commit(l),o.lo?.commit(l),o.lastIdx=e.idx}else l.truncate(o.savedEnd),o.bars?.truncate(o.savedEnd),o.sorted?.rollback(),o.counts?.rollback(),o.hi?.rollback(),o.lo?.rollback();let h=void 0===s?iI(i,0):s;iA(h)||o.push(h,e.idx),o.hi?.sync(l),o.lo?.sync(l);let c=r;if("bars"===a){if(e.idx<r-1||0===l.size)return;c=Math.min(r,l.size)}else if(l.size<r)return;return o.sorted?.sync(l,c),o.counts?.sync(l,c),o.length=c,o.sum=l.sum(c),o}var iP=Object.defineProperty,iD=(e,t,i)=>((e,t,i)=>t in e?iP(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let iR={abs:function(e){return e=>Math.abs(m.from(e).get(0))},acos:function(e){return e=>Math.acos(m.from(e).get(0))},asin:function(e){return e=>Math.asin(m.from(e).get(0))},atan:function(e){return e=>Math.atan(m.from(e).get(0))},avg:function(e){return(...e)=>{let t=e.map(e=>m.from(e).get(0));return t.reduce((e,t)=>e+t,0)/t.length}},ceil:function(e){return e=>Math.ceil(m.from(e).get(0))},cos:function(e){return e=>Math.cos(m.from(e).get(0))},e:function(e){return()=>Math.E},exp:function(e){return e=>Math.exp(m.from(e).get(0))},floor:function(e){return e=>Math.floor(m.from(e).get(0))},ln:function(e){return e=>Math.log(m.from(e).get(0))},log:function(e){return e=>Math.log(m.from(e).get(0))},log10:function(e){return e=>Math.log10(m.from(e).get(0))},max:function(e){return(...e)=>Math.max(...e.map(e=>m.from(e).get(0)))},min:function(e){return(...e)=>Math.min(...e.map(e=>m.from(e).get(0)))},param:function(e){return(t,i,r)=>"string"==typeof t?t:t instanceof m?i?new m(t.data,t.offset+i):t:Array.isArray(t)||"object"!=typeof t?(e.params[r]||(e.params[r]=[]),Array.isArray(t)?new m(t,i||0):(0===e.params[r].length?e.params[r].push(t):e.params[r][e.params[r].length-1]=t,new m(e.params[r],i||0))):t},phi:function(e){return()=>1.618033988749895},pi:function(e){return()=>Math.PI},pow:function(e){return(e,t)=>Math.pow(m.from(e).get(0),m.from(t).get(0))},random:function(e){return(...t)=>{let i,r="string"==typeof t[t.length-1]?t.pop():void 0,n=void 0!==t[0]?m.from(t[0]).get(0):0,s=void 0!==t[1]?m.from(t[1]).get(0):1,a=void 0!==t[2]?m.from(t[2]).get(0):NaN;if(!a||Number.isNaN(a))i=Math.random();else{e.taState||(e.taState={});let t=r||`random_${a}`;e.taState[t]||(e.taState[t]={bar:e.idx,committed:t9(a),tentative:t9(a)});let n=e.taState[t];e.idx!==n.bar&&(n.committed=n.tentative,n.bar=e.idx),[i,n.tentative]=function(e){let t=t8(e),i=t8(t);return[(0x8000000*Number(t>>22n)+Number(i>>21n))/0x20000000000000,i]}(n.tentative)}return n+(s-n)*i}},round:function(e){return(e,t)=>{let i=m.from(e).get(0),r=null==t?0:m.from(t).get(0);if(!r)return t7(i);let n=10**r,s=Math.abs(i)*n*n;return!Number.isFinite(s)||s>=Number.MAX_SAFE_INTEGER?t7(i*n)/n:Math.sign(i)*Math.round(Math.round(s)/n)/n}},round_to_mintick:function(e){return t=>{let i=m.from(t).get(0),r=e.pine.syminfo.mintick;if(!Number.isFinite(i)||!(r>0)||0===i)return e.precision(Math.round(i/r)*r);let n=function(e,t){let i=e/t,r=Math.floor(i);if(Math.abs(i-r-.5)>1e-6+1e-12*i||!Number.isSafeInteger(r))return Math.round(i);let[n,s]=function(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let i=t.getBigUint64(0),r=Number(i>>52n&2047n),n=i&(1n<<52n)-1n;return 0===r?[n,-1074]:[n|1n<<52n,r-1075]}(e),[a,o]=ii(t),l=n*10n**BigInt(o),h=a;return s>=0?l<<=BigInt(s):h<<=BigInt(-s),it*(l-BigInt(r)*h)>=ie*h?r+1:r}(Math.abs(i),r);return e.precision(Math.sign(i)*function(e,t){let[i,r]=ii(t),n=e*Number(i);return Number.isSafeInteger(n)&&r<=22?n/10**r:e*t}(n,r))}},rphi:function(e){return()=>.6180339887498948},sign:function(e){return e=>Math.sign(m.from(e).get(0))},sin:function(e){return e=>Math.sin(m.from(e).get(0))},sqrt:function(e){return e=>Math.sqrt(m.from(e).get(0))},sum:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=m.from(t);if(r&&n>=1&&Number.isInteger(n)){let t=iM(e,r,s,n);return t?t.sum:NaN}let a=0,o=0;for(let t=0;o<n&&t<=e.idx;t++){let e=s.get(t);null==e||Number.isNaN(e)||(a+=e,o++)}return o<n?NaN:a}},tan:function(e){return e=>Math.tan(m.from(e).get(0))},todegrees:function(e){return e=>{let t=m.from(e).get(0);return null==t||Number.isNaN(t)?NaN:180/Math.PI*t}},toradians:function(e){return e=>{let t=m.from(e).get(0);return null==t||Number.isNaN(t)?NaN:Math.PI/180*t}},__and:function(e){return(e,t)=>e&&t},__eq:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:1e-10>Math.abs(i-r):i===r}},__ge:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:1e-10>Math.abs(i-r)||i>r:i>=r}},__gt:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:!(1e-10>Math.abs(i-r))&&i>r:i>r}},__idiv:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"!=typeof i||"number"!=typeof r?i/r:isNaN(i)||isNaN(r)?NaN:Math.trunc(i/r)}},__le:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:1e-10>Math.abs(i-r)||i<r:i<=r}},__lt:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:!(1e-10>Math.abs(i-r))&&i<r:i<r}},__neq:function(e){return(e,t)=>{let i=m.from(e).get(0),r=m.from(t).get(0);return"number"==typeof i&&"number"==typeof r?isNaN(i)||isNaN(r)?NaN:Math.abs(i-r)>=1e-10:i!==r}},__or:function(e){return(e,t)=>e||t}};class iO{constructor(e){this.context=e,iD(this,"_cache",{}),iD(this,"abs"),iD(this,"acos"),iD(this,"asin"),iD(this,"atan"),iD(this,"avg"),iD(this,"ceil"),iD(this,"cos"),iD(this,"e"),iD(this,"exp"),iD(this,"floor"),iD(this,"ln"),iD(this,"log"),iD(this,"log10"),iD(this,"max"),iD(this,"min"),iD(this,"param"),iD(this,"phi"),iD(this,"pi"),iD(this,"pow"),iD(this,"random"),iD(this,"round"),iD(this,"round_to_mintick"),iD(this,"rphi"),iD(this,"sign"),iD(this,"sin"),iD(this,"sqrt"),iD(this,"sum"),iD(this,"tan"),iD(this,"todegrees"),iD(this,"toradians"),iD(this,"__and"),iD(this,"__eq"),iD(this,"__ge"),iD(this,"__gt"),iD(this,"__idiv"),iD(this,"__le"),iD(this,"__lt"),iD(this,"__neq"),iD(this,"__or"),Object.entries(iR).forEach(([t,i])=>{this[t]=i(e)})}}function ij(e,t){let i=`__unsupportedRequest_${t}`;return e.cache[i]||(e.cache[i]=!0,e.warn(`request.${t}() is not supported by PineTS: it returns na`,`request.${t}`)),NaN}function iV(e){let t=Array.isArray(e)&&2===e.length&&"string"==typeof e[1]?e[0]:e;return t instanceof m?t.get(0):t}var i$=Object.defineProperty,iL=(e,t,i)=>((e,t,i)=>t in e?i$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class iB{constructor(e){iL(this,"downPrice"),iL(this,"upPrice"),iL(this,"buyVolume"),iL(this,"sellVolume"),iL(this,"totalVolume"),iL(this,"deltaVolume"),iL(this,"buyImbalance"),iL(this,"sellImbalance"),this.downPrice=e.downPrice,this.upPrice=e.upPrice,this.buyVolume=e.buyVolume,this.sellVolume=e.sellVolume,this.totalVolume=e.totalVolume,this.deltaVolume=e.delta,this.buyImbalance=e.buyImbalance,this.sellImbalance=e.sellImbalance}up_price(){return this.upPrice}down_price(){return this.downPrice}buy_volume(){return this.buyVolume}sell_volume(){return this.sellVolume}total_volume(){return this.totalVolume}delta(){return this.deltaVolume}has_buy_imbalance(){return this.buyImbalance}has_sell_imbalance(){return this.sellImbalance}}function iF(e){return e instanceof tq?NaN:e instanceof m?e.get(0):"function"==typeof e?e():e}var iq=Object.defineProperty,iz=(e,t,i)=>((e,t,i)=>t in e?iq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function iU(e,t){return Math.floor(e/t)}function iW(e,t,i){return iU(Math.round(e/t),i)}class iK{constructor(e,t,i,r,n,s,a){iz(this,"rowList"),iz(this,"buyVolume"),iz(this,"sellVolume"),iz(this,"totalVolume"),iz(this,"deltaVolume"),iz(this,"pocIndex"),iz(this,"vahIndex"),iz(this,"valIndex"),iz(this,"_rowSize"),iz(this,"_firstRowIndex"),iz(this,"_context"),this._context=e,this.rowList=t,this._rowSize=i,this._firstRowIndex=r,this.buyVolume=n.buy,this.sellVolume=n.sell,this.totalVolume=n.total,this.deltaVolume=n.delta,this.pocIndex=s,this.valIndex=a.lo,this.vahIndex=a.hi}static build(e,t,i,r){let n=t=>e.precision(t),{ticksPerRow:s,mintick:a}=i,o=s*a,l=new Map,h=new Map,c=1/0,p=-1/0;for(let e of t){if(!e||!Number.isFinite(e.price))continue;let t=Number.isFinite(e.buyVolume)?e.buyVolume:0,i=Number.isFinite(e.sellVolume)?e.sellVolume:0,r=iW(e.price,a,s);l.set(r,(l.get(r)??0)+t),h.set(r,(h.get(r)??0)+i),r<c&&(c=r),r>p&&(p=r)}if(!Number.isFinite(c))return null;r&&Number.isFinite(r.low)&&Number.isFinite(r.high)&&r.low<=r.high&&(p=Math.max(p,c=Math.min(c,iW(r.low,a,s)),iU(Math.round(r.high/a)-1,s)));let u=p-c+1;if(u>2e3)return null;let d=Array(u),m=Array(u),f=Array(u),y=0,_=0;for(let e=0;e<u;e++){let t=l.get(c+e)??0,i=h.get(c+e)??0;d[e]=t,m[e]=i,f[e]=t+i,y+=t,_+=i}let g=f[0];for(let e=1;e<u;e++)f[e]>g&&(g=f[e]);let x=(u-1)/2,b=-1;for(let e=0;e<u;e++)f[e]+1e-10<g||(b<0||Math.abs(e-x)<Math.abs(b-x)-1e-10)&&(b=e);let v=y+_,w=Number.isNaN(i.vaPercent)?0:i.vaPercent,S=v>0?v*w/100+.01:0,E=b,N=b,T=f[b];for(;E>0||N<u-1;){let e,t=N<u-1,i=E>0,r=t?f[N+1]:-1/0,n=i?f[E-1]:-1/0,s=(e=!i||!!t&&(1e-10>=Math.abs(r-n)?N+1-b<=b-(E-1):r>n))?r:n;if(T+s>S)break;T+=s,e?N++:E--}let k=Math.max(i.imbalancePercent/100,1),A=Array(u);for(let e=0;e<u;e++){let t=d[e],i=m[e],r=e>0&&t>0&&t+1e-10>=k*m[e-1],s=e<u-1&&i>0&&i+1e-10>=k*d[e+1],a=n((c+e)*o),l=n((c+e+1)*o);A[e]=new iB({downPrice:a,upPrice:l,buyVolume:n(t),sellVolume:n(i),totalVolume:n(t+i),delta:n(t-i),buyImbalance:r,sellImbalance:s})}return new iK(e,A,o,c,{buy:n(y),sell:n(_),total:n(v),delta:n(y-_)},b,{lo:E,hi:N})}buy_volume(){return this.buyVolume}sell_volume(){return this.sellVolume}total_volume(){return this.totalVolume}delta(){return this.deltaVolume}poc(){return this.rowList[this.pocIndex]}vah(){return this.rowList[this.vahIndex]}val(){return this.rowList[this.valIndex]}rows(){return new eO([...this.rowList],eR.any,this._context)}get_row_by_price(...e){let t=iF(eN(e,["price"])[0]);if("number"!=typeof t||!Number.isFinite(t))return NaN;let i=Math.floor(t/this._rowSize+1e-6)-this._firstRowIndex;return i<0||i>=this.rowList.length?NaN:this.rowList[i]}}let iG=[["ticks_per_row"],["ticks_per_row","va_percent"],["ticks_per_row","va_percent","imbalance_percent"]],iH={ticks_per_row:"series",va_percent:"series",imbalance_percent:"series"};function iY(e){return Array.isArray(e)&&2===e.length&&"string"==typeof e[1]?e[0]:e}function iZ(e){let t=iY(e);return t instanceof m?t.get(0):"number"==typeof t?t:NaN}function iJ(e,t){if(t<0)throw new ei(`Invalid value of the '${e}' argument (${t}) in the 'request.footprint' function. It must be >= 0.`,"request.footprint")}function iQ(e,t,i){t.warned||(t.warned=!0,e.warn(i,"request.footprint"))}async function iX(e,t,i){let r=e.marketData??[],n=r[0],s=r[r.length-1],a=void 0===i,o=a?n?.openTime:i,l=a?s?.closeTime??e.eDate:void 0,h=a?r.length:void 0,c=[];try{c=await e.source.getFootprintData(e.tickerId,e.timeframe,h,o,l)??[]}catch(i){iQ(e,t,`request.footprint(): footprint data could not be loaded (${i instanceof Error?i.message:String(i)})`)}for(let e of c)e&&Number.isFinite(e.openTime)&&(t.bars.set(e.openTime,e),t.built.delete(e.openTime));t.loadedVersion=e.dataVersion}let i0=new Set(["heikinashi","standard"]);function i1(e){if("string"==typeof e&&e.startsWith("={"))try{let{symbol:t,...i}=JSON.parse(e.slice(1));if("string"==typeof t)return{symbol:t,modifiers:i}}catch{}return{symbol:e,modifiers:{}}}function i2(e,t){let i=Object.keys(t).filter(e=>void 0!==t[e]);if(0===i.length)return e;let r=i.map(e=>[e,t[e]]);return r.push(["symbol",e]),r.sort(([e],[t])=>e<t?-1:+(e>t)),"="+JSON.stringify(Object.fromEntries(r))}function i3(e){if("string"!=typeof e)return{symbol:e,modifier:null};let t=e.lastIndexOf(";");if(t<=0||t===e.length-1)return{symbol:i1(e).symbol,modifier:null};let i=e.slice(t+1).toLowerCase();return i0.has(i)?{symbol:i1(e.slice(0,t)).symbol,modifier:i}:{symbol:i1(e).symbol,modifier:null}}function i4(e){if("string"!=typeof e)return e;let{symbol:t,modifier:i}=i3(e);return i?`${t};${i}`:t}function i6(e){return i3(e).symbol}function i5(e,t){let{modifier:i}=i3(e);return`${i?e.slice(0,e.lastIndexOf(";")):e};${t}`}function i9(e,t,i,r,n=!1,s=!1){for(let a=0;a<i.length;a++)if(i[a]<=e&&e<r[a])return n||s||t>=r[a]?a:a-1;return -1}function i8(e,t,i,r,n=!1,s,a=!1){for(let s=i.length-1;s>=0;s--){if(r[s]<=t&&i[s]>=e){if(n){let t=s;for(;t>0&&i[t-1]>=e;)t--;return t}return s}if(r[s]<e)break}return -1}async function i7(e,t,i){let r="string"==typeof i?i:"",n=r.match(/p\d+$/)?.[0]??r,s=e._ltfTruncatedBodies?.[n];return t.runPretranspiled(s??e.transpiledFn,e.inputs)}let re=[["symbol","timeframe","expression"],["symbol","timeframe","expression","gaps"],["symbol","timeframe","expression","gaps","lookahead"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency","calc_bars_count"]],rt={symbol:"series",timeframe:"series",expression:"any",gaps:"series",lookahead:"series",ignore_invalid_symbol:"series",currency:"series",calc_bars_count:"series"};function ri(e){return Array.isArray(e)&&2===e.length&&"string"==typeof e[1]}function rr(e){return ri(e)?e[0]:e}function rn(e){return null==e||"object"!=typeof e?e:"__value"in e?e.__value:e instanceof m?e.get(0):Array.isArray(e)?e.map(rn):e}let rs=[["symbol","timeframe","expression"],["symbol","timeframe","expression","ignore_invalid_symbol"],["symbol","timeframe","expression","ignore_invalid_symbol","currency"],["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe"],["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe","calc_bars_count"]],ra={symbol:"series",timeframe:"series",expression:"any",ignore_invalid_symbol:"series",currency:"series",ignore_invalid_timeframe:"series",calc_bars_count:"series"};function ro(e){return Array.isArray(e)&&2===e.length&&"string"==typeof e[1]}function rl(e){return ro(e)?e[0]:e}function rh(e){return"number"==typeof e?eR.float:"boolean"==typeof e?eR.bool:"string"==typeof e?eR.string:eR.any}let rc={open:e=>e.open,high:e=>e.high,low:e=>e.low,close:e=>e.close,volume:e=>e.volume,hl2:e=>(e.high+e.low)/2,hlc3:e=>(e.high+e.low+e.close)/3,ohlc4:e=>(e.high+e.low+e.open+e.close)/4,hlcc4:e=>(e.high+e.low+e.close+e.close)/4,time:e=>e.openTime,openTime:e=>e.openTime,closeTime:e=>e.closeTime};function rp(e,t){if(!(e instanceof m))return null;let i=t?.data;if(!i)return null;for(let t of Object.keys(rc))if(e===i[t])return t;return null}async function ru(e,t,i,r,n,s){let a,o=e.sDate||(e.marketData?.length>0?e.marketData[0].openTime:void 0),l=(e.marketData?.length>0?e.marketData[e.marketData.length-1].closeTime:0)||e.eDate||Date.now(),h=new u5(e.source,t,i,r,o,l);h.markAsSecondary(e),await h.ready();let c=h.openTime,u=h.closeTime,d=h.data,m=n.builtinNames.map(e=>rc[e]);if("series"===n.kind)a=d.map(e=>m[0](e));else if("tuple"===n.kind)a=d.map(e=>m.map(t=>t(e)));else{let t=n.fieldNames,i=n.udt;a=d.map(r=>{let n={};for(let e=0;e<t.length;e++)n[t[e]]=m[e](r);return new p(n,e,i)})}return{data:{openTime:{data:c},closeTime:{data:u}},params:{[s]:a}}}var rd=Object.defineProperty,rm=(e,t,i)=>((e,t,i)=>t in e?rd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let rf={currency_rate:function(e){return(...t)=>{let i=iV(t[0]),r=iV(t[1]);return"string"==typeof i&&""!==i&&i.toUpperCase()===String(r).toUpperCase()?1:ij(e,"currency_rate")}},dividends:function(e){return(...t)=>ij(e,"dividends")},earnings:function(e){return(...t)=>ij(e,"earnings")},economic:function(e){return(...t)=>ij(e,"economic")},financial:function(e){return(...t)=>ij(e,"financial")},footprint:function(e){return async(...t)=>{var i;let r=e5(t.map(iY),iG,iH),n=Math.trunc(iZ(r.ticks_per_row)),s=void 0===r.va_percent?70:iZ(r.va_percent),a=void 0===r.imbalance_percent?300:iZ(r.imbalance_percent),o=(e.cache.__footprint||(e.cache.__footprint={bars:new Map,built:new Map,requestKey:null,loadedVersion:-1,warned:!1}),e.cache.__footprint),l=`${n}|${s}|${a}`;if(null===o.requestKey)o.requestKey=l;else if(o.requestKey!==l)throw new ei("The script executes too many `request.footprint()` function calls.","request.footprint");if(iJ("ticks_per_row",n),iJ("va_percent",s),iJ("imbalance_percent",a),!(n>0))return NaN;if(!(null!=(i=e.source)&&!Array.isArray(i)&&"function"==typeof i.getFootprintData))return iQ(e,o,"request.footprint(): the market data source does not provide footprint data — returning na"),NaN;let h=e.pine?.syminfo?.mintick;if(!("number"==typeof h&&h>0))return iQ(e,o,"request.footprint(): syminfo.mintick is unavailable, so rows cannot be sized — returning na"),NaN;let c=m.from(e.data.openTime).get(0);-1===o.loadedVersion?await iX(e,o,void 0):e.dataVersion>o.loadedVersion&&await iX(e,o,c);let p=o.bars.get(c);if(!p)return NaN;if(!o.built.has(c)){let t={low:m.from(e.data.low).get(0),high:m.from(e.data.high).get(0)};o.built.set(c,iK.build(e,p.levels??[],{ticksPerRow:n,mintick:h,vaPercent:Math.min(s,100),imbalancePercent:a},t))}return o.built.get(c)??NaN}},param:function(e){return(t,i,r)=>{let n;if(e.params[r]||(e.params[r]=[]),t instanceof m)n=t.get(i||0);else if(Array.isArray(t)){let e=t.some(e=>e instanceof m),r=t.every(e=>!(e instanceof m)&&!Array.isArray(e));n=(e||r)&&t.length>=1?t.map(e=>e instanceof m?e.get(0):e):m.from(t).get(i||0)}else n=t;return 0===e.params[r].length?e.params[r].push(n):e.params[r][e.params[r].length-1]=n,e._requestParamSources||(e._requestParamSources={}),e._requestParamSources[r]=t,[n,r]}},quandl:function(e){return(...t)=>ij(e,"quandl")},security:function(e){return async(...t)=>{let i,r=[],n=e5(t.map(e=>ri(e)?(r.push(e[1]),e[0]):(r.push(void 0),e)),re,rt),s=rr(n.symbol),a=rr(n.timeframe),o=rr(n.expression),l=rr(n.gaps),h=rr(n.lookahead),c=s instanceof m?s.get(0):s,p="string"==typeof e.tickerId&&e.tickerId.includes(":")?e.tickerId.split(":")[1]:e.tickerId,u="string"==typeof p?i3(p):{symbol:p,modifier:null},d="standard"===u.modifier?null:u.modifier,f=i4(""===c?e.tickerId:c),y="string"==typeof f&&f.includes(":")?f.split(":")[1]:f,_=a instanceof m?a.get(0):a,g=""===_?e.timeframe:"string"==typeof _?_:String(_??""),x=function(e,t,i,r){let n=t[t.length-1].indexOf(e);return n>=0&&n<i.length&&void 0!==i[n]?i[n]:ri(r)?r[1]:void 0}("expression",re,r,n.expression),b=!0===l||"gaps_on"===l,v=!0===h||"lookahead_on"===h,w=!0===rr(n.ignore_invalid_symbol),S=(()=>{let e=rr(n.calc_bars_count);return"number"==typeof e&&e>0?Math.min(e,1e5):void 0})();if(e.isSecondaryContext){let e=rn(o);return Array.isArray(e)?[e]:e}let E=te(e.timeframe),N=te(g);if(!E||!N)throw Error(`Invalid value of the 'timeframe' argument ('${N?e.timeframe:g}') in the 'security' function.`);let T=tr(E),k=tr(N),A="string"==typeof y?i3(y):{symbol:y,modifier:null},I="standard"===A.modifier?null:A.modifier,C=!y||""===y||A.symbol===u.symbol&&I===d;if(tt(E)===tt(N)&&C){let e=rn(o);return Array.isArray(e)?[e]:e}let M=T>k,P=m.from(e.data.openTime).get(0),D=m.from(e.data.closeTime).get(0),R=e.idx===e.length-1&&D>Date.now(),O=`${y}_${g}_${x}`,j=`${O}_prevIdx`;if(e.cache[O]){let t=e.cache[O];if(t.failed)return NaN;e.dataVersion>t.dataVersion&&(await t.pineTS.updateTail(t.context),t.dataVersion=e.dataVersion);let i=t.context,r=M?i8(P,D,i.data.openTime.data,i.data.closeTime.data,v,e.eDate,b):i9(P,D,i.data.openTime.data,i.data.closeTime.data,v,R);if(-1==r)return NaN;let n=i.params[x][r];if(!M&&b){let t=e.cache[j];return void 0!==t&&t===r?NaN:(e.cache[j]=r,Array.isArray(n)?[n]:n)}return Array.isArray(n)?[n]:n}let V=Math.max(2592e6,2*k*1e3),$=e.sDate||(e.marketData?.length>0?e.marketData[0].openTime:void 0),L=(e.marketData?.length>0?e.marketData[e.marketData.length-1].closeTime:0)||e.eDate||Date.now();eV(e,"request.security");let B=new u5(e.source,y,g,S,S?void 0:$?$-V:void 0,L);B.markAsSecondary(e);try{i=await i7(e,B,x)}catch(t){if(!w)throw t;return e.cache[O]={failed:!0},e.warn(`request.security(${y}, ${g}) returns na: ${t?.message??t}`,"request.security"),NaN}e.cache[O]={pineTS:B,context:i,dataVersion:e.dataVersion};let F=M?i8(P,D,i.data.openTime.data,i.data.closeTime.data,v,e.eDate,b):i9(P,D,i.data.openTime.data,i.data.closeTime.data,v,R);if(-1==F)return NaN;let q=i.params[x][F];return!M&&b?(e.cache[j]=F,NaN):Array.isArray(q)?[q]:q}},security_lower_tf:function(e){return async(...t)=>{let i=[],r=e5(t.map(e=>ro(e)?(i.push(e[1]),e[0]):(i.push(void 0),e)),rs,ra),n=rl(r.symbol),s=rl(r.timeframe),a=rl(r.expression),o=n instanceof m?n.get(0):n,l=i4(""===o?e.tickerId:o),h="string"==typeof l&&l.includes(":")?l.split(":")[1]:l,c=s instanceof m?s.get(0):s,u=""===c?e.timeframe:"string"==typeof c?c:String(c??""),d=function(e,t,i,r){let n=t[t.length-1].indexOf(e);return n>=0&&n<i.length&&void 0!==i[n]?i[n]:ro(r)?r[1]:void 0}("expression",rs,i,r.expression);rl(r.ignore_invalid_symbol);let f=rl(r.ignore_invalid_timeframe),y=(()=>{let e=rl(r.calc_bars_count);return"number"==typeof e&&e>0?Math.min(e,1e5):void 0})();if(e.isSecondaryContext)return Array.isArray(a)?[a.map(t=>new eO([t],rh(t),e))]:new eO([a],rh(a),e);let _=te(e.timeframe),g=te(u);if(!_||!g){if(f)return NaN;throw Error(`Invalid value of the 'timeframe' argument ('${g?e.timeframe:u}') in the 'security_lower_tf' function.`)}let x=tr(_);if(tr(g)>x){if(f)return NaN;throw Error(`Timeframe ${u} is not lower than or equal to chart timeframe ${e.timeframe}`)}if(tt(g)===tt(_))return Array.isArray(a)?[a.map(t=>new eO([t],rh(t),e))]:new eO([a],rh(a),e);let b=`${h}_${u}_${d}_lower`,v=function(e,t){if(void 0===e)return null;if(Array.isArray(e)){let i=[];for(let r of e){let e=rp(r,t);if(null===e)return null;i.push(e)}return i.length>0?{kind:"tuple",builtinNames:i}:null}let i=rp(e,t);return null!==i?{kind:"series",builtinNames:[i]}:function(e,t){if(e instanceof m&&(e=e.get(0)),!(e instanceof p))return null;let i=e._udt;if(!i||!i._fieldDefaults||!Array.isArray(i._definitionKeys))return null;let r=i._definitionKeys;if(0===r.length)return null;let n=[];for(let e of r){if(!(e in i._fieldDefaults))return null;let r=rp(i._fieldDefaults[e],t);if(null===r)return null;n.push(r)}return{kind:"udt",builtinNames:n,fieldNames:r,udt:i}}(e,t)}(e._requestParamSources?.[d],e);if(!e.cache[b])if(eV(e,"request.security_lower_tf"),null!==v){let t=await ru(e,h,u,y,v,d);e.cache[b]={pineTS:null,context:t,dataVersion:e.dataVersion,_fastPath:!0,_fastPathArgs:{builtinExpr:v}}}else{let t=e.sDate||(e.marketData?.length>0?e.marketData[0].openTime:void 0),i=(e.marketData?.length>0?e.marketData[e.marketData.length-1].closeTime:0)||e.eDate||Date.now(),r=new u5(e.source,h,u,y,t,i);r.markAsSecondary(e);let n=await i7(e,r,d);e.cache[b]={pineTS:r,context:n,dataVersion:e.dataVersion}}let w=e.cache[b];if(e.dataVersion>w.dataVersion)if(w._fastPath){let t=await ru(e,h,u,y,w._fastPathArgs.builtinExpr,d);w.context=t,w.dataVersion=e.dataVersion}else await w.pineTS.updateTail(w.context),w.dataVersion=e.dataVersion;let S=w.context,E=m.from(e.data.openTime).get(0),N=m.from(e.data.closeTime).get(0),T=S.data.openTime.data,k=S.data.closeTime.data,A=S.params[d];if(!A)return Array.isArray(a)?[a.map(()=>new eO([],eR.float,e))]:new eO([],eR.float,e);let I=[];for(let e=0;e<T.length;e++){let t=T[e];if(!(k[e]<=E)){if(t>=N)break;t>=E&&t<N&&I.push(A[e])}}if(I.length>0&&Array.isArray(I[0])){let t=I[0].length,i=[];for(let r=0;r<t;r++){let t=I.map(e=>e[r]),n=t.length>0?rh(t[0]):eR.float;i.push(new eO(t,n,e))}return[i]}{let t=I.length>0?rh(I[0]):eR.float;return new eO(I,t,e)}}},seed:function(e){return(...t)=>ij(e,"seed")},splits:function(e){return(...t)=>ij(e,"splits")}};class ry{constructor(e){this.context=e,rm(this,"_cache",{}),rm(this,"currency_rate"),rm(this,"dividends"),rm(this,"earnings"),rm(this,"economic"),rm(this,"financial"),rm(this,"footprint"),rm(this,"param"),rm(this,"quandl"),rm(this,"security"),rm(this,"security_lower_tf"),rm(this,"seed"),rm(this,"splits"),Object.entries(rf).forEach(([t,i])=>{this[t]=i(e)})}}var r_=Object.defineProperty;class rg{constructor(e){this.up=e,((e,t,i)=>((e,t,i)=>t in e?r_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"series")}get(e){let t=this.series.get(e)-this.series.get(e+1);return this.up?t>=0?t:0:t>=0?0:-t}}function rx(e,t,i){if(!t)return;e.taState||(e.taState={});let r=e.taState[t];r||(r=e.taState[t]={lastIdx:-1,shared:!1,prev:i(),current:i(),tick:-1});let n=e._execTick??0;return e.idx>r.lastIdx?(r.lastIdx>=0&&(r.prev={...r.current}),r.lastIdx=e.idx):r.current.callIdx===e.idx&&r.tick===n&&(r.shared=!0),r.tick=n,r.shared?void 0:r}function rb(e,t,i,r,n){let s,a=(e,t)=>n?e>t:e<t,o=rx(e,t,()=>({count:0,callIdx:-1,length:NaN}));if(o&&o.prev.callIdx===e.idx-1&&o.prev.length===r){let e=i.get(0),t=i.get(1);s=iA(e)||iA(t)?o.prev.count:a(e,t)?o.prev.count+1:0}else{s=0;for(let t=0;t<e.idx&&s<r;t++){let e=i.get(t),r=i.get(t+1);if(!(iA(e)||iA(r))){if(!a(e,r))break;s++}}}return o&&(o.current={count:s,callIdx:e.idx,length:r}),s>=r}function rv(e,t,i,r){let n=i.get(0),s=r.get(0),a=rx(e,t,()=>({a:NaN,b:NaN,callIdx:-1})),o=NaN,l=NaN;if(a)a.prev.callIdx>=0&&(o=a.prev.a,l=a.prev.b);else for(let t=1;t<=e.idx;t++){let e=i.get(t),n=r.get(t);if(!iA(e)&&!iA(n)){o=e,l=n;break}}if(a){let t=!iA(n)&&!iA(s);a.current={a:t?n:o,b:t?s:l,callIdx:e.idx}}return[n,s,o,l]}let rw=e=>void 0===e||isNaN(e);function rS(e,t,i,r,n){if(!t)return function(e,t,i,r){let n=NaN,s=NaN,a=0;for(let o=0;a<t&&o<=r;o++){let t=e.get(o);rw(t)||(a++,(isNaN(s)||(i?t>n:t<n))&&(n=t,s=-o))}return r<t-1||0===a?NaN:s}(i,r,n,e.idx);let s=iM(e,t,i,r,"extremes",void 0,"bars");if(!s)return NaN;let a=n?s.maxBar():s.minBar();return a===e.idx?-0:a-e.idx}var rE=Object.defineProperty,rN=(e,t,i)=>((e,t,i)=>t in e?rE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class rT{constructor(e){this.length=e,rN(this,"size"),rN(this,"vals"),rN(this,"bars"),rN(this,"byCall"),this.size=e+1,this.vals=Array(this.size).fill(0),this.bars=Array(this.size).fill(-1),this.byCall=Array(this.size).fill(!1)}slot(e){return(e%this.size+this.size)%this.size}write(e,t){let i=this.slot(e);this.vals[i]=t,this.bars[i]=e,this.byCall[i]=!0}prefill(e,t){for(let i=Math.max(0,e-this.length);i<e;i++){let r=this.slot(i);this.vals[r]=t.get(e-i),this.bars[r]=i,this.byCall[r]=!1}}read(e){if(e<0)return NaN;let t=this.slot(e);return this.byCall[t]||this.bars[t]===e?this.vals[t]:0}readSlot(e,t){return this.byCall[e]||this.bars[e]===t?this.vals[e]:0}stalePrefill(e,t){return!this.byCall[e]&&this.bars[e]>=0&&this.bars[e]!==t}valueOf(e){return this.vals[e]}}let rk=e=>Number.isInteger(e)&&e>=1;class rA{constructor(){rN(this,"ring",null),rN(this,"lastCall",-1),rN(this,"S",0),rN(this,"N",0),rN(this,"ok",!1),rN(this,"steps",0),rN(this,"savedFor",-1),rN(this,"saved",[-1,0,0,!1,0])}step(e,t,i,r){if(!rk(i))return;this.ring&&this.ring.length===i||(this.ring=new rT(i),this.ring.prefill(e,r),this.lastCall=-1,this.ok=!1,this.savedFor=-1),e===this.savedFor?[this.lastCall,this.S,this.N,this.ok,this.steps]=this.saved:(this.savedFor=e,this.saved=[this.lastCall,this.S,this.N,this.ok,this.steps]);let n=this.ring,s=this.ok&&this.lastCall===e-1&&this.steps+1<i,a=s?n.read(e-i):NaN;if(n.write(e,t),this.lastCall=e,s&&!Number.isNaN(t)&&!Number.isNaN(a))return this.N=this.N-this.S+i*t,this.S=this.S-a+t,this.steps++,[this.S,this.N];let o=0,l=0;for(let t=0;t<i;t++){let r=n.read(e-t);l+=r*(i-t),o+=r}return this.S=o,this.N=l,this.steps=0,this.ok=!Number.isNaN(o+l),this.ok?[o,l]:void 0}}class rI{constructor(){rN(this,"slots",new rA),rN(this,"carry",new iN(2)),rN(this,"firstLength",NaN),rN(this,"seriesForm",!1),rN(this,"committedLine",null),rN(this,"line",null)}step(e,t,i,r){if(this.carry.push(e,t,rk(i)?i:1,r),this.carry.newBar&&(this.committedLine=this.line),this.line=this.committedLine,Number.isNaN(this.firstLength)?this.firstLength=i:i!==this.firstLength&&(this.seriesForm=!0),!this.seriesForm)return this.slots.step(e,t,i,r);let n=this.carry.h;if(!(!rk(i)||n.size<i||n.nas(i)>0))return[n.sum(i),n.wsum(i)]}}var rC=Object.defineProperty,rM=(e,t,i)=>((e,t,i)=>t in e?rC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class rP{constructor(e){this.up=e,rM(this,"series"),rM(this,"volume")}get(e){let t=this.series.get(e),i=t-this.series.get(e+1);return this.volume.get(e)*(this.up?i<=0?0:t:i>=0?0:t)}}var rD=Object.defineProperty,rR=(e,t,i)=>((e,t,i)=>t in e?rD(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let rO=e=>Number.isNaN(e);class rj{constructor(){rR(this,"arr",[]),rR(this,"nan",0),rR(this,"held",[]),rR(this,"head",0),rR(this,"carry",new iN),rR(this,"undoLog",[]),rR(this,"lastTick")}step(e,t,i,r,n){let s=null==t?NaN:Number(t);for(this.carry.push(e,s,i,r),this.carry.newBar?this.commit():(void 0===n||n!==this.lastTick)&&this.rollback(),this.lastTick=n,this.insert(s),this.held.push(s),this.undoLog.push(()=>this.held.pop());this.held.length-this.head>i;){let e=this.held[this.head++];this.undoLog.push(()=>this.head--),this.removeValue(e)}let a=this.carry.h;for(;this.held.length-this.head<i&&a.size>this.held.length-this.head;){let e=a.at(this.held.length-this.head);if(this.head>0){let t=this.held[--this.head];this.held[this.head]=e,this.undoLog.push(()=>{this.held[this.head]=t,this.head++})}else this.held.unshift(e),this.undoLog.push(()=>this.held.shift());this.insert(e)}return this.held.length-this.head<i?void 0:this.arr}commit(){this.undoLog.length=0,this.head>1024&&2*this.head>this.held.length&&(this.held=this.held.slice(this.head),this.head=0)}rollback(){for(let e=this.undoLog.length-1;e>=0;e--)this.undoLog[e]();this.undoLog.length=0}insert(e){let t=this.insertAt(e);this.arr.splice(t,0,e),rO(e)&&this.nan++,this.undoLog.push(()=>{this.arr.splice(t,1),rO(e)&&this.nan--})}removeValue(e){let t=this.indexOf(e);t<0||(this.arr.splice(t,1),rO(e)&&this.nan--,this.undoLog.push(()=>{this.arr.splice(t,0,e),rO(e)&&this.nan++}))}insertAt(e){let t=this.arr;if(0===this.nan&&!rO(e))return il(t,e);let i=0;for(;i<t.length&&!(e<t[i]);)i++;return i}indexOf(e){let t=this.arr;if(0===this.nan&&!rO(e)){let i=io(t,e);return t[i]===e?i:-1}if(rO(e)){for(let e=0;e<t.length;e++)if(rO(t[e]))return e;return -1}return t.indexOf(e)}}function rV(e,t,i,r,n,s){if(!t)return function(e,t,i,r,n){let s=t-r,a=e[s];if(!(s>=0)||null==a||isNaN(a)||t<i+r)return NaN;let o=0;for(let l=t;l>=0&&o<i+r+1;l--){let t=e[l];if(!(null==t||isNaN(t))&&(o++,l!==s&&(n?t>a||l>s&&t===a:t<a||l>s&&t===a)))return NaN}return a}(m.from(i).toArray(),e.idx,r,n,s);let a=iM(e,t,m.from(i),r+n+1,"extremes",void 0,"bars");return a&&n>=0&&(s?a.maxBar():a.minBar())===e.idx-n?s?a.max():a.min():NaN}let r$=["Traditional","Fibonacci","Woodie","Classic","DM","Camarilla"];function rL(e,{high:t,low:i,close:r},n){let s=t-i,a=(t+i+r)/3;switch(e){case"Traditional":return[a,2*a-i,2*a-t,a+s,a-s,2*a+(t-2*i),2*a-(2*t-i),3*a+(t-3*i),3*a-(3*t-i),4*a+(t-4*i),4*a-(4*t-i)];case"Fibonacci":return[a,a+.382*s,a-.382*s,a+.618*s,a-.618*s,a+s,a-s,NaN,NaN,NaN,NaN];case"Woodie":{let e=(t+i+2*n)/4,r=t+2*(e-i),a=i-2*(t-e);return[e,2*e-i,2*e-t,e+s,e-s,r,a,r+s,a-s,NaN,NaN]}case"Classic":return[a,2*a-i,2*a-t,a+s,a-s,a+2*s,a-2*s,a+3*s,a-3*s,NaN,NaN];case"DM":{let e=r<n?t+2*i+r:r>n?2*t+i+r:t+i+2*r;return[e/4,e/2-i,e/2-t,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]}case"Camarilla":{let e=t/i*r;return[a,r+1.1*s/12,r-1.1*s/12,r+1.1*s/6,r-1.1*s/6,r+1.1*s/4,r-1.1*s/4,r+1.1*s/2,r-1.1*s/2,e,r-(e-r)]}}return Array(11).fill(NaN)}var rB=Object.defineProperty,rF=(e,t,i)=>((e,t,i)=>t in e?rB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class rq{constructor(e,t,i){this.length=e,rF(this,"ring"),rF(this,"vals",[]),rF(this,"slots",[]),this.ring=new rT(e),this.ring.prefill(t,i);for(let e=0;e<this.ring.size;e++)this.insert(this.ring.valueOf(e),e)}write(e,t){let i=this.ring.slot(e);this.remove(this.ring.valueOf(i),i),this.ring.write(e,t),this.insert(t,i)}insert(e,t){if(Number.isNaN(e))return;let i=il(this.vals,e);this.vals.splice(i,0,e),this.slots.splice(i,0,t)}remove(e,t){if(Number.isNaN(e))return;let i=io(this.vals,e);for(;this.slots[i]!==t;)i++;this.vals.splice(i,1),this.slots.splice(i,1)}}var rz=Object.defineProperty,rU=(e,t,i)=>((e,t,i)=>t in e?rz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class rW{constructor(){rU(this,"lastIdx",-1),rU(this,"prev",NaN),rU(this,"cur",NaN)}}function rK(e,t,i){return Number.isNaN(i)?(t.cur=t.prev,t.prev):(t.cur=i,e.precision(i))}var rG=Object.defineProperty,rH=(e,t,i)=>((e,t,i)=>t in e?rG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let rY=(e,t)=>Number.isNaN(e)?t:e,rZ=e=>null==e||Number.isNaN(e);class rJ{constructor(){rH(this,"carry",new iN(2,rY)),rH(this,"savedSeen",0),rH(this,"seen",0),rH(this,"started",!1)}}var rQ=Object.defineProperty,rX=(e,t,i)=>((e,t,i)=>t in e?rQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let r0={accdist:function(e){return t=>{e.taState||(e.taState={});let i=t||"accdist";e.taState[i]||(e.taState[i]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=e.taState[i];e.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=e.idx);let n=e.get(e.data.close,0),s=e.get(e.data.high,0),a=e.get(e.data.low,0),o=e.get(e.data.volume,0);if(isNaN(n)||isNaN(s)||isNaN(a)||isNaN(o))return r.currentCumulativeSum=r.prevCumulativeSum,e.precision(r.prevCumulativeSum);let l=s-a,h=0;0!==l&&(h=(n-a-(s-n))/l*o);let c=r.prevCumulativeSum+h;return r.currentCumulativeSum=c,e.precision(c)}},alma:function(e){return(t,i,r,n,...s)=>{let a="string"==typeof s[s.length-1]?s.pop():void 0,o=m.from(i).get(0),l=m.from(r).get(0),h=m.from(n).get(0),c=s.length>0&&!!m.from(s[0]).get(0);e.taState||(e.taState={});let p=a||`alma_${o}_${l}_${h}_${c}`;e.taState[p]||(e.taState[p]={carry:new iN,weightsKey:"",weights:[]});let u=e.taState[p],d=u.carry,f=`${o}_${l}_${h}_${c}`;if(u.weightsKey!==f){let e=c?Math.floor(l*(o-1)):l*(o-1),t=o/h,i=[],r=0;for(let n=0;n<o;n++){let s=Math.exp(-Math.pow(n-e,2)/(2*t*t));i.push(s),r+=s}for(let e=0;e<i.length;e++)i[e]/=r;u.weights=i,u.weightsKey=f}let y=m.from(t);d.push(e.idx,y.get(0),o,y);let _=d.h;if(!(o>=1)||_.size<o)return NaN;let g=u.weights,x=0,b=_.view(o);for(let e=0;e<o;e++)x+=g[e]*b[e];return e.precision(x)}},atr:function(e){return(t,i)=>{let r,n=m.from(t).get(0);e.taState||(e.taState={});let s=i||`atr_${n}`;e.taState[s]||(e.taState[s]={lastIdx:-1,prevAtr:null,prevInitSum:0,prevInitCount:0,currentAtr:null,currentInitSum:0,currentInitCount:0});let a=e.taState[s];e.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevAtr=a.currentAtr,a.prevInitSum=a.currentInitSum,a.prevInitCount=a.currentInitCount),a.lastIdx=e.idx);let o=e.get(e.data.high,0),l=e.get(e.data.low,0),h=e.get(e.data.close,0);if(isNaN(o)||isNaN(l)||isNaN(h))return NaN;let c=e.idx>0?e.get(e.data.close,1):null;if(null===c||isNaN(c))r=o-l;else{let e=Math.abs(o-c),t=Math.abs(l-c);r=Math.max(o-l,e,t)}let p=a.prevInitCount,u=a.prevInitSum,d=a.prevAtr;if(p<n){if(u+=r,p++,a.currentInitSum=u,a.currentInitCount=p,p===n){let t=u/n;return a.currentAtr=t,e.precision(t)}return NaN}let f=(d*(n-1)+r)/n;return a.currentAtr=f,e.precision(f)}},barssince:function(e){return(t,i)=>{e.taState||(e.taState={});let r=i||"barssince";e.taState[r]||(e.taState[r]={lastIdx:-1,prevLastTrueIndex:null,currentLastTrueIndex:null});let n=e.taState[r];e.idx>n.lastIdx&&(n.lastIdx>=0&&(n.prevLastTrueIndex=n.currentLastTrueIndex),n.lastIdx=e.idx);let s=m.from(t).get(0),a=n.prevLastTrueIndex;return s&&(a=e.idx),n.currentLastTrueIndex=a,null===a?NaN:e.idx-a}},bb:function(e){return(t,i,r,n)=>{let s=m.from(i).get(0),a=m.from(r).get(0);e.taState||(e.taState={});let o=iM(e,n||`bb_${s}_${a}`,m.from(t),s);if(!o)return[[NaN,NaN,NaN]];let l=o.sum/s,h=o.values(),c=0;for(let e=0;e<s;e++)c+=Math.pow(h[e]-l,2);let p=Math.sqrt(c/s);return[[e.precision(l),e.precision(l+a*p),e.precision(l-a*p)]]}},bbw:function(e){return(t,i,r,n)=>{let s=m.from(i).get(0),a=m.from(r).get(0);e.taState||(e.taState={});let o=iM(e,n||`bbw_${s}_${a}`,m.from(t),s);if(!o)return NaN;let l=o.sum/s,h=o.values(),c=0;for(let e=0;e<s;e++){let t=h[e]-l;c+=t*t}let p=Math.sqrt(c/s);return 0===l?e.precision(0):e.precision(a*p*2/l*100)}},cci:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0),a=m.from(t);e.taState||(e.taState={});let o=r||`cci_${s}`,l=(n=e.taState)[o]??(n[o]=new iN),h=a.get(0);l.push(e.idx,h,s,a);let c=iM(e,`${o}_mean`,a,s);if(!c||l.h.size<s)return NaN;let p=c.sum/s,u=l.h.view(s),d=0;for(let e=0;e<s;e++)d+=Math.abs(u[s-1-e]-p);let f=d/s;return 0===f?0:e.precision((h-p)/(.015*f))}},change:function(e){return(t,i=1,r)=>{var n;"string"==typeof i&&(r=i,i=1);let s=m.from(i).get(0);e.taState||(e.taState={});let a=r||`change_${s}`,o=(n=e.taState)[a]??(n[a]=new iN),l=m.from(t),h=l.get(0);if(o.push(e.idx,h,s,l),!(s>=0)||o.h.size<=s)return NaN;let c=h-o.h.at(s);return e.precision(c)}},cmo:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=m.from(t);e.taState||(e.taState={});let a=r||`cmo_${n}`;e.taState[a]||(e.taState[a]={prev:new im,up:new rg(!0),down:new rg(!1)});let o=e.taState[a],l=o.prev;l.begin(e.idx),o.up.series=o.down.series=s;let h=s.get(0),c=l.ring.size?l.ring.at(0):s.get(1);l.push(e.idx,h,1);let p=h-c,u=iM(e,`${a}_up`,o.up,n,!1,p>=0?p:0),d=iM(e,`${a}_down`,o.down,n,!1,p>=0?0:-p);if(!u||!d)return NaN;let f=u.sum+d.sum;if(0===f)return e.precision(0);let y=100*(u.sum-d.sum)/f;return e.precision(y)}},cog:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0),a=m.from(t),o=0,l=0;if(r&&s>=1){e.taState||(e.taState={});let t=(n=e.taState)[r]??(n[r]=new iN(2));t.push(e.idx,a.get(0),s,a);let i=iM(e,`${r}_sum`,a,s),h=t.h;if(!i||h.size<s||h.nas(s)>0)return NaN;o=i.sum,l=(s+1)*h.sum(s)-h.wsum(s)}else for(let e=0;e<s;e++){let t=a.get(e);if(isNaN(t))return NaN;o+=t,l+=t*(e+1)}if(0===o)return NaN;let h=-l/o;return e.precision(h)}},correlation:function(e){return(t,i,r,n)=>{let s=m.from(r).get(0),a=m.from(t),o=m.from(i),l=n||`correlation_${s}`,h=(t,i)=>{let r=iM(e,`${l}_${t}`,i,s);if(!r)return NaN;let n=r.values(),a=0;for(let e=0;e<s;e++)a+=n[e];return a/s},c=h("x",e=>a.get(e)),p=h("y",e=>o.get(e)),u=h("xy",e=>a.get(e)*o.get(e)),d=h("xx",e=>a.get(e)*a.get(e)),f=h("yy",e=>o.get(e)*o.get(e));if([c,p,u,d,f].some(e=>Number.isNaN(e)))return NaN;let y=d-c*c,_=f-p*p;return y<=0||_<=0?e.precision(0):e.precision((u-c*p)/Math.sqrt(y*_))}},cross:function(e){return(t,i,r)=>{let[n,s,a,o]=rv(e,r,m.from(t),m.from(i));return!(isNaN(n)||isNaN(s)||isNaN(a)||isNaN(o))&&(n>s&&a<=o||n<s&&a>=o)}},crossover:function(e){return(t,i,r)=>{let[n,s,a,o]=rv(e,r,m.from(t),m.from(i));return a<=o&&n>s}},crossunder:function(e){return(t,i,r)=>{let[n,s,a,o]=rv(e,r,m.from(t),m.from(i));return a>=o&&n<s}},cum:function(e){return(t,i)=>{e.taState||(e.taState={});let r=i||"cum";e.taState[r]||(e.taState[r]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let n=e.taState[r];e.idx>n.lastIdx&&(n.lastIdx>=0&&(n.prevCumulativeSum=n.currentCumulativeSum),n.lastIdx=e.idx);let s=m.from(t).get(0);if(isNaN(s))return n.currentCumulativeSum=n.prevCumulativeSum,NaN;let a=n.prevCumulativeSum+s;return n.currentCumulativeSum=a,e.precision(a)}},dev:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0),a=m.from(t);e.taState||(e.taState={});let o=r||`dev_${s}`,l=(n=e.taState)[o]??(n[o]=new iN);l.push(e.idx,a.get(0),s,a);let h=iM(e,`${o}_mean`,a,s);if(!h||l.h.size<s)return NaN;let c=h.sum/s,p=l.h.view(s),u=0;for(let e=0;e<s;e++)u+=Math.abs(p[s-1-e]-c);let d=u/s;return e.precision(d)}},dmi:function(e){return(t,i,r)=>{let n=m.from(t).get(0),s=m.from(i).get(0);e.taState||(e.taState={});let a=r||`dmi_${n}_${s}`;e.taState[a]||(e.taState[a]={lastIdx:-1,prevTrInitSum:0,prevPlusInitSum:0,prevMinusInitSum:0,prevInitCount:0,prevSmoothedTR:NaN,prevSmoothedPlus:NaN,prevSmoothedMinus:NaN,prevDxInitSum:0,prevAdxInitCount:0,prevADX:NaN,currentTrInitSum:0,currentPlusInitSum:0,currentMinusInitSum:0,currentInitCount:0,currentSmoothedTR:NaN,currentSmoothedPlus:NaN,currentSmoothedMinus:NaN,currentDxInitSum:0,currentAdxInitCount:0,currentADX:NaN});let o=e.taState[a];e.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevTrInitSum=o.currentTrInitSum,o.prevPlusInitSum=o.currentPlusInitSum,o.prevMinusInitSum=o.currentMinusInitSum,o.prevInitCount=o.currentInitCount,o.prevSmoothedTR=o.currentSmoothedTR,o.prevSmoothedPlus=o.currentSmoothedPlus,o.prevSmoothedMinus=o.currentSmoothedMinus,o.prevDxInitSum=o.currentDxInitSum,o.prevAdxInitCount=o.currentAdxInitCount,o.prevADX=o.currentADX),o.lastIdx=e.idx);let l=e.get(e.data.high,0),h=e.get(e.data.low,0),c=e.get(e.data.close,0);if(isNaN(l)||isNaN(h)||isNaN(c))return[[NaN,NaN,NaN]];let p=e.idx>0?e.get(e.data.high,1):NaN,u=e.idx>0?e.get(e.data.low,1):NaN,d=e.idx>0?e.get(e.data.close,1):NaN;if(isNaN(p))return[[NaN,NaN,NaN]];let f=Math.max(l-h,Math.abs(l-d),Math.abs(h-d)),y=l-p,_=u-h,g=y>_&&y>0?y:0,x=_>y&&_>0?_:0,b=o.prevInitCount,v=o.prevTrInitSum,w=o.prevPlusInitSum,S=o.prevMinusInitSum,E=o.prevSmoothedTR,N=o.prevSmoothedPlus,T=o.prevSmoothedMinus;if(++b<=n)v+=f,w+=g,S+=x,b===n&&(E=v/n,N=w/n,T=S/n);else{let e=1/n;E=e*f+(1-e)*E,N=e*g+(1-e)*N,T=e*x+(1-e)*T}if(o.currentInitCount=b,o.currentTrInitSum=v,o.currentPlusInitSum=w,o.currentMinusInitSum=S,o.currentSmoothedTR=E,o.currentSmoothedPlus=N,o.currentSmoothedMinus=T,b<n)return[[NaN,NaN,NaN]];let k=0===E?0:100*N/E,A=0===E?0:100*T/E,I=k+A,C=0===I?0:100*Math.abs(k-A)/I,M=o.prevAdxInitCount,P=o.prevDxInitSum,D=o.prevADX,R=NaN;if(++M<=s)P+=C,M===s&&(R=D=P/s);else{let e=1/s;R=D=e*C+(1-e)*D}return o.currentAdxInitCount=M,o.currentDxInitSum=P,o.currentADX=D,[[e.precision(k),e.precision(A),e.precision(R)]]}},ema:function(e){return(t,i,r)=>{let n=m.from(i).get(0);e.taState||(e.taState={});let s=r||`ema_${n}`;e.taState[s]||(e.taState[s]={lastIdx:-1,prevEma:null,prevInitSum:0,prevInitCount:0,currentEma:null,currentInitSum:0,currentInitCount:0});let a=e.taState[s];e.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevEma=a.currentEma,a.prevInitSum=a.currentInitSum,a.prevInitCount=a.currentInitCount),a.lastIdx=e.idx);let o=m.from(t).get(0);if(null==o||isNaN(o))return NaN;let l=a.prevInitCount,h=a.prevInitSum,c=a.prevEma;if(l<n){if(h+=o,l++,a.currentInitSum=h,a.currentInitCount=l,l===n){let t=h/n;return a.currentEma=t,e.precision(t)}return NaN}let p=2/(n+1),u=o*p+c*(1-p);return a.currentEma=u,e.precision(u)}},falling:function(e){return(t,i,r)=>{let n=m.from(i).get(0);return rb(e,r,m.from(t),n,!1)}},highest:function(e){return(t,i,r)=>{"string"==typeof i&&void 0===r&&(r=i,i=t,t=e.data.high);let n=m.from(i).get(0),s=iM(e,r||`highest_${n}`,m.from(t),n,"extremes",void 0,"bars");return s?e.precision(s.max()):NaN}},highestbars:function(e){return(t,i,r)=>{"string"==typeof i&&void 0===r&&(r=i,i=t,t=e.data.high);let n=m.from(i).get(0),s=rS(e,r,m.from(t),n,!0);return e.idx<n-1?NaN:s}},hma:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=Math.floor(n/2),a=Math.floor(Math.sqrt(n)),o=e.pine.ta.wma,l=o(t,s,r?`${r}_wma1`:void 0),h=o(t,n,r?`${r}_wma2`:void 0),c=isNaN(l)||isNaN(h);e.taState||(e.taState={});let p=r?`${r}_hma_final`:`hma_final_${n}`;e.taState[p]||(e.taState[p]=new im(!0));let u=e.taState[p];if(u.begin(e.idx),c)return u.ring.size&&u.push(e.idx,u.ring.at(0),a),NaN;if(u.push(e.idx,2*l-h,a),u.size<a)return NaN;let d=0,f=0;for(let e=0;e<a;e++){let t=a-e;d+=u.at(e)*t,f+=t}let y=d/f;return e.precision(y)}},iii:function(e){return t=>{let i=e.get(e.data.close,0),r=e.get(e.data.high,0),n=e.get(e.data.low,0),s=e.get(e.data.volume,0);if(isNaN(i)||isNaN(r)||isNaN(n)||isNaN(s))return NaN;let a=r-n;return 0===a?e.precision(0):e.precision((2*i-r-n)/a*s)}},kc:function(e){return(t,i,r,n,s)=>{let a,o=m.from(i).get(0),l=m.from(r).get(0),h=!0;"string"==typeof n?s=n:void 0!==n&&(h=m.from(n).get(0));let c=e.get(e.data.high,0),p=e.get(e.data.low,0);if(h){let t=e.get(e.data.close,1);a=isNaN(t)?NaN:Math.max(c-p,Math.abs(c-t),Math.abs(p-t))}else a=c-p;let u=m.from(t).get(0);e.taState||(e.taState={});let d=s||`kc_${o}_${l}_${h}`;e.taState[d]||(e.taState[d]={lastIdx:-1,basisState:{prevEma:null,initSum:0,initCount:0},rangeState:{prevEma:null,initSum:0,initCount:0},currentBasisState:{prevEma:null,initSum:0,initCount:0},currentRangeState:{prevEma:null,initSum:0,initCount:0}});let f=e.taState[d];e.idx>f.lastIdx&&(f.lastIdx>=0&&(f.basisState={...f.currentBasisState},f.rangeState={...f.currentRangeState}),f.lastIdx=e.idx);let y=(e,t,i,r)=>{if(isNaN(i))return Object.assign(t,e),NaN;let n=e.initCount,s=e.initSum,a=e.prevEma;if(n<r){if(s+=i,n++,t.initSum=s,t.initCount=n,t.prevEma=a,n===r){let e=s/r;return t.prevEma=e,e}return NaN}let o=2/(r+1),l=i*o+a*(1-o);return t.prevEma=l,t.initSum=s,t.initCount=n,l},_=y(f.basisState,f.currentBasisState,u,o),g=y(f.rangeState,f.currentRangeState,a,o);return isNaN(_)||isNaN(g)?[[NaN,NaN,NaN]]:[[e.precision(_),e.precision(_+g*l),e.precision(_-g*l)]]}},kcw:function(e){return(t,i,r,n,s)=>{let a,o=m.from(i).get(0),l=m.from(r).get(0),h=!0;"string"==typeof n?s=n:void 0!==n&&(h=m.from(n).get(0)),e.taState||(e.taState={});let c=s||`kcw_${o}_${l}_${h}`;e.taState[c]||(e.taState[c]={lastIdx:-1,basisState:{prevEma:null,initSum:0,initCount:0},rangeState:{prevEma:null,initSum:0,initCount:0},currentBasisState:{prevEma:null,initSum:0,initCount:0},currentRangeState:{prevEma:null,initSum:0,initCount:0}});let p=e.taState[c];e.idx>p.lastIdx&&(p.lastIdx>=0&&(p.basisState={...p.currentBasisState},p.rangeState={...p.currentRangeState}),p.lastIdx=e.idx);let u=(e,t,i,r)=>{if(isNaN(i))return Object.assign(t,e),NaN;let n=e.initCount,s=e.initSum,a=e.prevEma;if(n<r){if(s+=i,n++,t.initSum=s,t.initCount=n,t.prevEma=a,n===r){let e=s/r;return t.prevEma=e,e}return NaN}let o=2/(r+1),l=i*o+a*(1-o);return t.prevEma=l,t.initSum=s,t.initCount=n,l},d=e.get(e.data.high,0),f=e.get(e.data.low,0);if(h){let t=e.get(e.data.close,1);a=isNaN(t)?NaN:Math.max(d-f,Math.abs(d-t),Math.abs(f-t))}else a=d-f;let y=m.from(t).get(0),_=u(p.basisState,p.currentBasisState,y,o),g=u(p.rangeState,p.currentRangeState,a,o);return isNaN(_)||isNaN(g)?NaN:0===_?e.precision(0):e.precision(2*g*l/_)}},linreg:function(e){return(t,i,r,n)=>{let s=m.from(i).get(0),a=m.from(r).get(0);e.taState||(e.taState={});let o=n||`linreg_${s}_${a}`;e.taState[o]||(e.taState[o]=new rI);let l=e.taState[o],h=m.from(t),c=l.step(e.idx,h.get(0),s,h);if(!c)return NaN;let p=s*(s-1)/2,u=(s-1)*s*(2*s-1)/6,d=c[0],f=c[1]-c[0],y=s*u-p*p;if(0===y)return l.line?e.precision(l.line[1]+l.line[0]*(s-1-a)):NaN;let _=(s*f-p*d)/y,g=(d-_*p)/s;return l.line=[_,g],e.precision(g+_*(s-1-a))}},lowest:function(e){return(t,i,r)=>{"string"==typeof i&&void 0===r&&(r=i,i=t,t=e.data.low);let n=m.from(i).get(0),s=iM(e,r||`lowest_${n}`,m.from(t),n,"extremes",void 0,"bars");return s?e.precision(s.min()):NaN}},lowestbars:function(e){return(t,i,r)=>{"string"==typeof i&&void 0===r&&(r=i,i=t,t=e.data.low);let n=m.from(i).get(0),s=rS(e,r,m.from(t),n,!1);return e.idx<n-1?NaN:s}},macd:function(e){return(t,i,r,n,s)=>{let a=m.from(i).get(0),o=m.from(r).get(0),l=m.from(n).get(0),h=s||`macd_${a}_${o}_${l}`,c=`${h}_fast`,p=`${h}_slow`,u=`${h}_signal`,d=e.pine.ta.ema(t,a,c),f=e.pine.ta.ema(t,o,p),y=NaN;isNaN(d)||isNaN(f)||(y=d-f);let _=NaN;isNaN(y)||(_=e.pine.ta.ema(y,l,u));let g=NaN;return isNaN(y)||isNaN(_)||(g=y-_),[[e.precision(y),e.precision(_),e.precision(g)]]}},max:function(e){return(t,i)=>{let r;e.taState||(e.taState={});let n=i||"max";e.taState[n]||(e.taState[n]={lastIdx:-1,prevMax:NaN,currentMax:NaN});let s=e.taState[n];e.idx>s.lastIdx&&(s.lastIdx>=0&&(s.prevMax=s.currentMax),s.lastIdx=e.idx);let a=m.from(t).get(0);return r=isNaN(a)?s.prevMax:isNaN(s.prevMax)?a:Math.max(s.prevMax,a),s.currentMax=r,e.precision(r)}},median:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=iM(e,r||`median_${n}`,m.from(t),n,"sorted");if(!s)return NaN;let a=Math.floor(n/2),o=n%2==0?(s.kth(a-1)+s.kth(a))/2:s.kth(a);return e.precision(o)}},mfi:function(e){return(t,i,r)=>{let n=m.from(i).get(0);e.taState||(e.taState={});let s=r||`mfi_${n}`;e.taState[s]||(e.taState[s]={prev:new im,up:new rP(!0),down:new rP(!1)});let a=e.taState[s],o=a.prev;o.begin(e.idx);let l=m.from(t),h=m.from(e.data.volume),c=l.get(0),p=o.ring.size?o.ring.at(0):l.get(1);o.push(e.idx,c,1);let u=c-p,d=h.get(0);a.up.series=a.down.series=l,a.up.volume=a.down.volume=h;let f=iM(e,`${s}_up`,a.up,n,!1,d*(u<=0?0:c)),y=iM(e,`${s}_down`,a.down,n,!1,d*(u>=0?0:c));if(!f||!y)return NaN;let _=f.sum,g=y.sum;return 0===g?e.precision(100):0===_?e.precision(0):e.precision(100-100/(1+_/g))}},min:function(e){return(t,i)=>{let r;e.taState||(e.taState={});let n=i||"min";e.taState[n]||(e.taState[n]={lastIdx:-1,prevMin:NaN,currentMin:NaN});let s=e.taState[n];e.idx>s.lastIdx&&(s.lastIdx>=0&&(s.prevMin=s.currentMin),s.lastIdx=e.idx);let a=m.from(t).get(0);return r=isNaN(a)?s.prevMin:isNaN(s.prevMin)?a:Math.min(s.prevMin,a),s.currentMin=r,e.precision(r)}},mode:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=iM(e,r||`mode_${n}`,m.from(t),n,"counts");return s&&e.idx>=n-1?s.mode():NaN}},mom:function(e){return(t,i,r)=>{let n=m.from(i).get(0);return e.pine.ta.change(t,n,r)}},nvi:function(e){return t=>{e.taState||(e.taState={});let i=t||"nvi";e.taState[i]||(e.taState[i]={lastIdx:-1,committedNVI:1,tentativeNVI:1});let r=e.taState[i];e.idx>r.lastIdx&&(r.lastIdx>=0&&(r.committedNVI=r.tentativeNVI),r.lastIdx=e.idx);let n=e.get(e.data.close,0),s=e.get(e.data.close,1),a=e.get(e.data.volume,0),o=e.get(e.data.volume,1),l=isNaN(n)?0:n,h=isNaN(s)?0:s,c=isNaN(a)?0:a,p=isNaN(o)?0:o,u=r.committedNVI;return 0!==l&&0!==h&&c<p&&(u+=(l-h)/h*u),r.tentativeNVI=u,e.precision(u)}},obv:function(e){return()=>{e.taState||(e.taState={}),e.taState.obv||(e.taState.obv={lastIdx:-1,committedOBV:0,tentativeOBV:0});let t=e.taState.obv;e.idx>t.lastIdx&&(t.lastIdx>=0&&(t.committedOBV=t.tentativeOBV),t.lastIdx=e.idx);let i=e.get(e.data.close,0),r=e.get(e.data.volume,0),n=e.get(e.data.close,1);if(isNaN(n))return t.tentativeOBV=0,e.precision(0);let s=t.committedOBV;return i>n?s+=r:i<n&&(s-=r),t.tentativeOBV=s,e.precision(s)}},param:function(e){return(t,i,r)=>t instanceof m?i?new m(t.data,t.offset+i):t:(e.params[r]||(e.params[r]=[]),Array.isArray(t)?new m(t,i||0):(0===e.params[r].length?e.params[r].push(t):e.params[r][e.params[r].length-1]=t,new m(e.params[r],i||0)))},percentile_linear_interpolation:function(e){return(t,i,r,n)=>{var s;let a=m.from(i).get(0),o=m.from(r).get(0),l=m.from(t);if(!rk(a))return NaN;e.taState||(e.taState={});let h=n||`pli_${a}_${o}`,c=((s=e.taState)[h]??(s[h]=new rj)).step(e.idx,l.get(0),a,l,e._execTick);return!c||e.idx<a-1?NaN:e.precision(function(e,t){let i=e.length,r=Math.min(Math.max(t/100*i-.5,0),i-1),n=Math.floor(r);return n>=i-1?e[i-1]:e[n]+(r-n)*(e[n+1]-e[n])}(c,o))}},percentile_nearest_rank:function(e){return(t,i,r,n)=>{var s;let a=m.from(i).get(0),o=m.from(r).get(0),l=m.from(t);if(!rk(a))return NaN;e.taState||(e.taState={});let h=n||`pnr_${a}_${o}`,c=((s=e.taState)[h]??(s[h]=new rj)).step(e.idx,l.get(0),a,l,e._execTick);return!c||e.idx<a-1?NaN:e.precision(function(e,t){let i=e.length;return e[Math.min(Math.max(Math.ceil(t/100*i)-1,0),i-1)]}(c,o))}},percentrank:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0),a=m.from(t),o=a.get(0),l=0;if(r){e.taState||(e.taState={});let t=(n=e.taState)[r]??(n[r]={carry:new iN,prev:new iw}),i=t.carry,h=t.prev;if(i.push(e.idx,o,s,a),i.newBar?h.commit():h.rollback(),h.sync(i.h,s,1),e.idx<s)return NaN;null==o||Number.isNaN(o)||(l=il(h.sorted,o))}else{if(e.idx<s)return NaN;if(null!=o)for(let e=1;e<=s;e++){let t=a.get(e);null!=t&&t<=o&&l++}}return e.precision(l/s*100)}},pivothigh:function(e){return(t,i,r,n)=>{"string"==typeof r&&(n=r,r=i,i=t,t=e.data.high);let s=m.from(i).get(0),a=m.from(r).get(0);return e.precision(rV(e,n,t,s,a,!0))}},pivotlow:function(e){return(t,i,r,n)=>{"string"==typeof r&&(n=r,r=i,i=t,t=e.data.low);let s=m.from(i).get(0),a=m.from(r).get(0);return e.precision(rV(e,n,t,s,a,!1))}},pivot_point_levels:function(e){return(t,i,...r)=>{let n="string"==typeof r[r.length-1]?r.pop():void 0,s=m.from(t).get(0),a=!0===m.from(i).get(0),o=r.length>0&&!0===m.from(r[0]).get(0);if(!r$.includes(s))throw new ei(`Invalid argument '${s}' for 'type' in the 'ta.pivot_point_levels' function. Possible values: ['Camarilla', 'Traditional', 'DM', 'Classic', 'Fibonacci', 'Woodie']`,"ta.pivot_point_levels");if(o&&"Woodie"===s)throw new ei('The `developing` parameter of the `ta.pivot_point_levels()` cannot be `true` when `type` is "Woodie".',"ta.pivot_point_levels");e.taState||(e.taState={});let l=n||`pivot_point_levels_${s}_${o}`;e.taState[l]||(e.taState[l]={lastIdx:-1,prev:{period:null,levels:null},current:{period:null,levels:null}});let h=e.taState[l];e.idx>h.lastIdx&&(h.lastIdx>=0&&(h.prev=h.current),h.lastIdx=e.idx);let c={open:m.from(e.data.open).get(0),high:m.from(e.data.high).get(0),low:m.from(e.data.low).get(0),close:m.from(e.data.close).get(0)},p=h.prev.period,u=h.prev.levels;return a||!p?(a&&p&&(u=rL(s,p,"Woodie"===s?c.open:p.open)),p={...c}):p={open:p.open,high:Math.max(p.high,c.high),low:Math.min(p.low,c.low),close:c.close},h.current={period:p,levels:u},new eO((o?rL(s,p,p.open):u??Array(11).fill(NaN)).map(t=>e.precision(t)),eR.float,e)}},pvi:function(e){return t=>{e.taState||(e.taState={});let i=t||"pvi";e.taState[i]||(e.taState[i]={lastIdx:-1,committedPVI:1,tentativePVI:1});let r=e.taState[i];e.idx>r.lastIdx&&(r.lastIdx>=0&&(r.committedPVI=r.tentativePVI),r.lastIdx=e.idx);let n=e.get(e.data.close,0),s=e.get(e.data.close,1),a=e.get(e.data.volume,0),o=e.get(e.data.volume,1),l=isNaN(n)?0:n,h=isNaN(s)?0:s,c=isNaN(a)?0:a,p=isNaN(o)?0:o,u=r.committedPVI;return 0!==l&&0!==h&&c>p&&(u+=(l-h)/h*u),r.tentativePVI=u,e.precision(u)}},pvt:function(e){return t=>{e.taState||(e.taState={});let i=t||"pvt";e.taState[i]||(e.taState[i]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=e.taState[i];e.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=e.idx);let n=e.get(e.data.close,0),s=e.get(e.data.close,1),a=e.get(e.data.volume,0),o=r.prevCumulativeSum;return isNaN(n)||isNaN(s)||isNaN(a)||0===s||(o+=(n-s)/s*a),r.currentCumulativeSum=o,e.precision(o)}},range:function(e){return(t,i,r)=>{let n=m.from(i).get(0);if(!(n>=1))return NaN;let s=iM(e,r||`range_${n}`,m.from(t),n,"extremes");if(!s)return NaN;let a=s.max();return e.precision((a>5e-324?a:5e-324)-s.min())}},rci:function(e){return(t,i,r)=>{let n=m.from(i).get(0);if(!rk(n))return NaN;e.taState||(e.taState={});let s=r||`rci_${n}`,a=m.from(t),o=e.taState[s];o&&o.length===n||(o=e.taState[s]=new rq(n,e.idx,a));let l=e.idx,h=a.get(0);if(o.write(l,h??NaN),n<2||l<n)return NaN;let c=o.ring,p=c.size,u=c.slot(l),d=!1;for(let e=0;e<n;e++){let t=(u-e+p)%p;if(Number.isNaN(c.readSlot(t,l-e))||l-e<0)return NaN;c.stalePrefill(t,l-e)&&(d=!0)}if(d){let t=[];for(let e=n-1;e>=0;e--)t.push(c.read(l-e));let i=function(e,t){let i=e.map((e,t)=>t).sort((t,i)=>e[t]-e[i]),r=Array(t);for(let n=0;n<t;){let s=n;for(;s+1<t&&e[i[s+1]]===e[i[n]];)s++;let a=(n+s)/2+1;for(let e=n;e<=s;e++)r[i[e]]=a;n=s+1}let n=(t+1)/2,s=0,a=0,o=0;for(let e=0;e<t;e++){let t=e+1-n,i=r[e]-n;s+=t*i,a+=t*t,o+=i*i}return 0===o?NaN:s/Math.sqrt(a*o)*100}(t,n);return Number.isNaN(i)?NaN:e.precision(i)}let f=(u+1)%p,y=(n+1)/2,_=0,g=0,x=0;for(let e=0;e<n;e++){let t=e+1-y;g+=t*t}let b=o.vals,v=o.slots;for(let e=0,t=0;e<b.length;){let i=e,r=+(v[e]!==f);for(;i+1<b.length&&b[i+1]===b[e];)v[++i]!==f&&r++;let s=t+(r-1)/2+1-y;for(let t=e;t<=i;t++)v[t]!==f&&(_+=(n-(u-v[t]+p)%p-y)*s,x+=s*s);t+=r,e=i+1}return 0===x?NaN:e.precision(_/Math.sqrt(g*x)*100)}},rising:function(e){return(t,i,r)=>{let n=m.from(i).get(0);return rb(e,r,m.from(t),n,!0)}},rma:function(e){return(t,i,r)=>{let n=m.from(i).get(0);e.taState||(e.taState={});let s=r||`rma_${n}`;e.taState[s]||(e.taState[s]={lastIdx:-1,prevRma:null,prevInitSum:0,prevInitCount:0,currentRma:null,currentInitSum:0,currentInitCount:0});let a=e.taState[s];e.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevRma=a.currentRma,a.prevInitSum=a.currentInitSum,a.prevInitCount=a.currentInitCount),a.lastIdx=e.idx);let o=m.from(t).get(0);if(null==o||Number.isNaN(o))return a.currentRma=a.prevRma,a.currentInitSum=a.prevInitSum,a.currentInitCount=a.prevInitCount,NaN;let l=a.prevInitCount,h=a.prevInitSum,c=a.prevRma;if(l<n){if(h+=o,l++,a.currentInitSum=h,a.currentInitCount=l,l===n){let t=h/n;return a.currentRma=t,e.precision(t)}return NaN}let p=1/n,u=o*p+c*(1-p);return a.currentRma=u,e.precision(u)}},roc:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0);e.taState||(e.taState={});let a=r||`roc_${s}`,o=(n=e.taState)[a]??(n[a]=new iN),l=m.from(t),h=l.get(0);if(o.push(e.idx,h,s,l),!(s>=0)||o.h.size<=s)return NaN;let c=o.h.at(s);return e.precision((h-c)/c*100)}},rsi:function(e){return(t,i,r)=>{let n=m.from(i).get(0);e.taState||(e.taState={});let s=r||`rsi_${n}`;e.taState[s]||(e.taState[s]={lastIdx:-1,prevPrevValue:null,prevAvgGain:0,prevAvgLoss:0,initGains:[],initLosses:[],currentPrevValue:null,currentAvgGain:0,currentAvgLoss:0,currentInit:null});let a=e.taState[s];e.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevPrevValue=a.currentPrevValue,a.prevAvgGain=a.currentAvgGain,a.prevAvgLoss=a.currentAvgLoss,a.currentInit&&(a.initGains.push(a.currentInit[0]),a.initLosses.push(a.currentInit[1]))),a.currentInit=null,a.lastIdx=e.idx);let o=m.from(t).get(0);if(null==o||isNaN(o))return a.currentPrevValue=NaN,a.currentInit=null,a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let l=a.prevPrevValue;if(null===l||isNaN(l))return a.currentPrevValue=o,a.currentInit=null,a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let h=a.prevAvgGain,c=a.prevAvgLoss,p=o-l,u=p>0?p:0,d=p<0?-p:0;if(a.initGains.length<n){if(a.currentInit=[u,d],a.currentPrevValue=o,a.initGains.length+1===n){h=(a.initGains.reduce((e,t)=>e+t,0)+u)/n,c=(a.initLosses.reduce((e,t)=>e+t,0)+d)/n,a.currentAvgGain=h,a.currentAvgLoss=c;let t=0===c?100:100-100/(1+h/c);return e.precision(t)}return NaN}a.currentInit=null,h=(h*(n-1)+u)/n,c=(c*(n-1)+d)/n,a.currentAvgGain=h,a.currentAvgLoss=c,a.currentPrevValue=o;let f=0===c?100:100-100/(1+h/c);return e.precision(f)}},sar:function(e){return(t,i,r,n)=>{let s=m.from(t).get(0),a=m.from(i).get(0),o=m.from(r).get(0);e.taState||(e.taState={});let l=n||`sar_${s}_${a}_${o}`;e.taState[l]||(e.taState[l]={lastIdx:-1,prevResult:NaN,prevMaxMin:NaN,prevAcceleration:NaN,prevIsBelow:!1,prevBarIndex:0,currentResult:NaN,currentMaxMin:NaN,currentAcceleration:NaN,currentIsBelow:!1,currentBarIndex:0});let h=e.taState[l];e.idx>h.lastIdx&&(h.lastIdx>=0&&(h.prevResult=h.currentResult,h.prevMaxMin=h.currentMaxMin,h.prevAcceleration=h.currentAcceleration,h.prevIsBelow=h.currentIsBelow,h.prevBarIndex=h.currentBarIndex),h.lastIdx=e.idx);let c=h.prevResult,p=h.prevMaxMin,u=h.prevAcceleration,d=h.prevIsBelow,f=h.prevBarIndex,y=e.get(e.data.high,0),_=e.get(e.data.low,0),g=e.get(e.data.close,0),x=e.get(e.data.close,1),b=e.get(e.data.high,1),v=e.get(e.data.low,1),w=e.get(e.data.high,2),S=e.get(e.data.low,2);if(isNaN(y)||isNaN(_)||isNaN(g))return h.currentResult=c,h.currentMaxMin=p,h.currentAcceleration=u,h.currentIsBelow=d,h.currentBarIndex=f,NaN;let E=!1;return 1===f&&(g>x?(d=!0,p=y,c=v):(d=!1,p=_,c=b),E=!0,u=s),f>=1&&(c+=u*(p-c),d?c>_&&(E=!0,d=!1,c=Math.max(y,p),p=_,u=s):c<y&&(E=!0,d=!0,c=Math.min(_,p),p=y,u=s),E||(d?y>p&&(p=y,u=Math.min(u+a,o)):_<p&&(p=_,u=Math.min(u+a,o))),d?(c=Math.min(c,v),f>1&&(c=Math.min(c,S))):(c=Math.max(c,b),f>1&&(c=Math.max(c,w)))),f++,h.currentResult=c,h.currentMaxMin=p,h.currentAcceleration=u,h.currentIsBelow=d,h.currentBarIndex=f,f<=1?NaN:e.precision(c)}},sma:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=iM(e,r||`sma_${n}`,m.from(t),n);return s?e.precision(s.sum/n):NaN}},stdev:function(e){return(t,i,...r)=>{let n="string"==typeof r[r.length-1]?r.pop():void 0,s=m.from(i).get(0),a=0===r.length||!!m.from(r[0]).get(0),o=iM(e,n||`stdev_${s}_${a}`,m.from(t),s);if(!o)return NaN;let l=o.sum/s,h=0,c=o.values();for(let e=0;e<s;e++)h+=Math.pow(c[e]-l,2);let p=Math.sqrt(h/(a?s:s-1));return e.precision(p)}},stoch:function(e){return(t,i,r,n,s)=>{var a;let o=m.from(n).get(0);e.taState||(e.taState={});let l=s||`stoch_${o}`,h=(a=e.taState)[l]??(a[l]=new rW),c=m.from(t).get(0),p=m.from(i).get(0),u=m.from(r).get(0);e.idx!==h.lastIdx&&(h.prev=h.cur,h.lastIdx=e.idx);let d=iM(e,`${l}_h`,m.from(i),o,"extremes",p,"bars"),f=iM(e,`${l}_l`,m.from(r),o,"extremes",u,"bars");if(!d||!f)return rK(e,h,NaN);let y=d.max(),_=f.min(),g=y-_;return 0===g?c===_?rK(e,h,NaN):(h.cur=NaN,NaN):rK(e,h,100*(c-_)/g)}},supertrend:function(e){return(t,i,r)=>{let n,s,a,o=m.from(i).get(0);e.taState||(e.taState={});let l=r||`supertrend_${m.from(t).get(0)}_${o}`;e.taState[l]||(e.taState[l]={factor:m.from(t).get(0),lastIdx:-1,prevTrSum:0,prevAtrValue:NaN,prevAtrCount:0,prevLowerBand:NaN,prevUpperBand:NaN,prevSuperTrend:NaN,prevDirection:NaN,currentTrSum:0,currentAtrValue:NaN,currentAtrCount:0,currentLowerBand:NaN,currentUpperBand:NaN,currentSuperTrend:NaN,currentDirection:NaN});let h=e.taState[l],c=h.factor;e.idx>h.lastIdx&&(h.lastIdx>=0&&(h.prevTrSum=h.currentTrSum,h.prevAtrValue=h.currentAtrValue,h.prevAtrCount=h.currentAtrCount,h.prevLowerBand=h.currentLowerBand,h.prevUpperBand=h.currentUpperBand,h.prevSuperTrend=h.currentSuperTrend,h.prevDirection=h.currentDirection),h.lastIdx=e.idx);let p=e.get(e.data.high,0),u=e.get(e.data.low,0),d=e.get(e.data.close,0);if(isNaN(p)||isNaN(u)||isNaN(d))return[[NaN,NaN]];let f=(p+u)/2,y=e.idx>0?e.get(e.data.close,1):NaN;n=isNaN(y)?p-u:Math.max(p-u,Math.abs(p-y),Math.abs(u-y));let _=h.prevAtrCount,g=h.prevTrSum,x=h.prevAtrValue;++_<=o?(g+=n,_===o&&(x=g/o)):x=(x*(o-1)+n)/o;let b=x;if(h.currentAtrCount=_,h.currentTrSum=g,h.currentAtrValue=x,isNaN(b))return[[NaN,NaN]];let v=f+c*b,w=f-c*b,S=isNaN(h.prevLowerBand)?0:h.prevLowerBand,E=isNaN(h.prevUpperBand)?0:h.prevUpperBand;isNaN(h.prevLowerBand)||w>S||y<S||(w=S),isNaN(h.prevUpperBand)||v<E||y>E||(v=E);let N=h.prevSuperTrend;return a=-1==(s=_===o?1:N===h.prevUpperBand?d>v?-1:1:d<w?1:-1)?w:v,h.currentLowerBand=w,h.currentUpperBand=v,h.currentSuperTrend=a,h.currentDirection=s,[[e.precision(a),s]]}},swma:function(e){return(t,i)=>{let r=[1,2,2,1];e.taState||(e.taState={});let n=i||"swma";e.taState[n]||(e.taState[n]=new im(!0));let s=e.taState[n];s.begin(e.idx),s.push(e.idx,m.from(t).get(0),4,id,t);let a=s.values(s.size);if(a.length<4)return NaN;let o=0;for(let e=0;e<4;e++)o+=r[e]*a[3-e];return o/=6,e.precision(o)}},tr:function(e){return(t,i)=>{let r=!0;"string"==typeof t||void 0!==t&&(r=m.from(t).get(0));let n=e.get(e.data.high,0),s=e.get(e.data.low,0),a=e.get(e.data.close,1);if(isNaN(a))return r?e.precision(n-s):NaN;let o=Math.max(n-s,Math.abs(n-a),Math.abs(s-a));return e.precision(o)}},tsi:function(e){return(t,i,r,n)=>{let s=m.from(i).get(0),a=m.from(r).get(0);e.taState||(e.taState={});let o=n||`tsi_${s}_${a}`;e.taState[o]||(e.taState[o]={lastIdx:-1,prevSource:NaN,prevEma1PcValue:NaN,prevEma1PcCount:0,prevEma1PcSum:0,prevEma2PcValue:NaN,prevEma2PcCount:0,prevEma2PcSum:0,prevEma1AbsValue:NaN,prevEma1AbsCount:0,prevEma1AbsSum:0,prevEma2AbsValue:NaN,prevEma2AbsCount:0,prevEma2AbsSum:0,currentSource:NaN,currentEma1PcValue:NaN,currentEma1PcCount:0,currentEma1PcSum:0,currentEma2PcValue:NaN,currentEma2PcCount:0,currentEma2PcSum:0,currentEma1AbsValue:NaN,currentEma1AbsCount:0,currentEma1AbsSum:0,currentEma2AbsValue:NaN,currentEma2AbsCount:0,currentEma2AbsSum:0});let l=e.taState[o];e.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevSource=l.currentSource,l.prevEma1PcValue=l.currentEma1PcValue,l.prevEma1PcCount=l.currentEma1PcCount,l.prevEma1PcSum=l.currentEma1PcSum,l.prevEma2PcValue=l.currentEma2PcValue,l.prevEma2PcCount=l.currentEma2PcCount,l.prevEma2PcSum=l.currentEma2PcSum,l.prevEma1AbsValue=l.currentEma1AbsValue,l.prevEma1AbsCount=l.currentEma1AbsCount,l.prevEma1AbsSum=l.currentEma1AbsSum,l.prevEma2AbsValue=l.currentEma2AbsValue,l.prevEma2AbsCount=l.currentEma2AbsCount,l.prevEma2AbsSum=l.currentEma2AbsSum),l.lastIdx=e.idx);let h=m.from(t).get(0);if(isNaN(h))return l.currentSource=NaN,NaN;let c=isNaN(l.prevSource)?NaN:h-l.prevSource;if(l.currentSource=h,isNaN(c))return NaN;let p=Math.abs(c),u=2/(a+1),d=2/(s+1),f=2/(a+1),y=2/(s+1),_=l.prevEma1PcCount,g=l.prevEma1PcSum,x=l.prevEma1PcValue;++_<=a?(g+=c,_===a&&(x=g/a)):x=c*u+x*(1-u);let b=l.prevEma1AbsCount,v=l.prevEma1AbsSum,w=l.prevEma1AbsValue;if(++b<=a?(v+=p,b===a&&(w=v/a)):w=p*f+w*(1-f),isNaN(x)||isNaN(w))return l.currentEma1PcCount=_,l.currentEma1PcSum=g,l.currentEma1PcValue=x,l.currentEma1AbsCount=b,l.currentEma1AbsSum=v,l.currentEma1AbsValue=w,NaN;let S=l.prevEma2PcCount,E=l.prevEma2PcSum,N=l.prevEma2PcValue;++S<=s?(E+=x,S===s&&(N=E/s)):N=x*d+N*(1-d);let T=l.prevEma2AbsCount,k=l.prevEma2AbsSum,A=l.prevEma2AbsValue;if(++T<=s?(k+=w,T===s&&(A=k/s)):A=w*y+A*(1-y),l.currentEma1PcCount=_,l.currentEma1PcSum=g,l.currentEma1PcValue=x,l.currentEma1AbsCount=b,l.currentEma1AbsSum=v,l.currentEma1AbsValue=w,l.currentEma2PcCount=S,l.currentEma2PcSum=E,l.currentEma2PcValue=N,l.currentEma2AbsCount=T,l.currentEma2AbsSum=k,l.currentEma2AbsValue=A,isNaN(N)||isNaN(A))return NaN;if(0===A)return e.precision(0);let I=N/A;return e.precision(I)}},valuewhen:function(e){return(t,i,r,n)=>{let s;e.taState||(e.taState={});let a=n||"valuewhen";e.taState[a]||(e.taState[a]={lastIdx:-1,values:[],pending:!1,pendingValue:void 0});let o=e.taState[a];e.idx>o.lastIdx&&(o.pending&&o.values.push(o.pendingValue),o.pending=!1,o.lastIdx=e.idx);let l=m.from(t).get(0),h=m.from(i).get(0),c=m.from(r).get(0);if(o.pending=!!l,o.pendingValue=h,isNaN(c)||c<0)return NaN;let p=o.values;if(o.pending)if(0===c)s=h;else{let e=p.length-c;if(e<0)return NaN;s=p[e]}else{let e=p.length-1-c;if(e<0)return NaN;s=p[e]}return"number"==typeof s?e.precision(s):s}},variance:function(e){return(t,i,...r)=>{let n="string"==typeof r[r.length-1]?r.pop():void 0,s=m.from(i).get(0),a=0===r.length||!!m.from(r[0]).get(0),o=iM(e,n||`variance_${s}_${a}`,m.from(t),s);if(!o)return NaN;let l=0,h=0,c=o.values();for(let e=0;e<s;e++){let t=c[e];l+=t,h+=t*t}let p=l/s,u=h/s-p*p;return e.precision(a?u:u*s/(s-1))}},vwap:function(e){return(...t)=>{let i="string"==typeof t[t.length-1]?t.pop():void 0,r=t.length>0?t[0]:e.data.hlc3,n=t.length>=2,s=t.length>=3;e.taState||(e.taState={});let a=i||`vwap_${t.length}`;e.taState[a]||(e.taState[a]={lastIdx:-1,prevCumulativePV:0,prevCumulativeVolume:0,prevCumulativePPV:0,prevStarted:!1,prevLastSessionDate:null,currentCumulativePV:0,currentCumulativeVolume:0,currentCumulativePPV:0,currentStarted:!1,currentLastSessionDate:null});let o=e.taState[a];e.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevCumulativePV=o.currentCumulativePV,o.prevCumulativeVolume=o.currentCumulativeVolume,o.prevCumulativePPV=o.currentCumulativePPV,o.prevStarted=o.currentStarted,o.prevLastSessionDate=o.currentLastSessionDate),o.lastIdx=e.idx);let l=m.from(r).get(0),h=m.from(e.data.volume).get(0),c=o.prevCumulativePV,p=o.prevCumulativeVolume,u=o.prevCumulativePPV,d=o.prevStarted,f=o.prevLastSessionDate,y;if(n)y=!!m.from(t[1]).get(0);else{let t=tb(m.from(e.data.openTime).get(0),e.pine?.syminfo?.timezone||"UTC"),i=`${t.year}-${String(t.month).padStart(2,"0")}-${String(t.day).padStart(2,"0")}`;y=f!==i,f=i}y&&(c=0,p=0,u=0,d=!0),d&&(c+=l*h,p+=h,u+=l*l*h),o.currentCumulativePV=c,o.currentCumulativeVolume=p,o.currentCumulativePPV=u,o.currentStarted=d,o.currentLastSessionDate=f;let _=d&&0!==p?c/p:NaN;if(!s)return isNaN(_)?NaN:e.precision(_);let g=m.from(t[2]).get(0),x=Math.sqrt(Math.max(u/p-_*_,0));return[[e.precision(_),e.precision(_+g*x),e.precision(_-g*x)]]}},vwma:function(e){return(t,i,r)=>{let n=m.from(i).get(0),s=m.from(t),a=m.from(e.data.volume),o=r||`vwma_${n}`,l=iM(e,`${o}_sv`,e=>s.get(e)*a.get(e),n),h=iM(e,`${o}_v`,a,n);return l&&h?e.precision(l.sum/h.sum):NaN}},wad:function(e){return t=>{e.taState||(e.taState={});let i=t||"wad";e.taState[i]||(e.taState[i]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=e.taState[i];e.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=e.idx);let n=e.get(e.data.close,0),s=e.get(e.data.high,0),a=e.get(e.data.low,0),o=e.get(e.data.close,1);if(isNaN(n)||isNaN(s)||isNaN(a))return r.currentCumulativeSum=r.prevCumulativeSum,e.precision(r.prevCumulativeSum);let l=0;if(!isNaN(o)){let e=Math.max(s,o),t=Math.min(a,o),i=n-o;i>0?l=n-t:i<0&&(l=n-e)}let h=r.prevCumulativeSum+l;return r.currentCumulativeSum=h,e.precision(h)}},wma:function(e){return(t,i,r)=>{var n;let s=m.from(i).get(0);if(!(s>=1))return NaN;e.taState||(e.taState={});let a=r||`wma_${s}`,o=(n=e.taState)[a]??(n[a]=new rJ),l=o.carry,h=m.from(t),c=h.get(0);if(l.push(e.idx,c,s,h),o.started)l.newBar?o.savedSeen=o.seen:o.seen=o.savedSeen;else{o.started=!0;for(let t=1;t<=e.idx&&o.seen<s;t++)rZ(h.get(t))||o.seen++;o.savedSeen=o.seen}if(rZ(c)||o.seen++,rZ(c))return NaN;let p=l.h;return o.seen<s||p.size<s||p.nas(s)>0?NaN:e.precision(p.wsum(s)/(s*(s+1)/2))}},wpr:function(e){return(t,i)=>{let r=m.from(t).get(0);e.taState||(e.taState={});let n=i||`wpr_${r}`,s=e.get(e.data.high,0),a=e.get(e.data.low,0),o=e.get(e.data.close,0),l=isNaN(s)||isNaN(a)||isNaN(o),h=iM(e,`${n}_h`,e.data.high,r,"extremes",l?NaN:s,"bars"),c=iM(e,`${n}_l`,e.data.low,r,"extremes",l?NaN:a,"bars");if(l||!h||!c)return NaN;let p=h.max(),u=p-c.min();return 0===u?e.precision(0):e.precision(-((p-o)/u*100))}},wvad:function(e){return t=>{let i=e.get(e.data.close,0),r=e.get(e.data.open,0),n=e.get(e.data.high,0),s=e.get(e.data.low,0),a=e.get(e.data.volume,0);if(isNaN(i)||isNaN(r)||isNaN(n)||isNaN(s)||isNaN(a))return NaN;let o=n-s;return 0===o?e.precision(0):e.precision((i-r)/o*a)}}};class r1{constructor(e){this.context=e,rX(this,"accdist"),rX(this,"alma"),rX(this,"atr"),rX(this,"barssince"),rX(this,"bb"),rX(this,"bbw"),rX(this,"cci"),rX(this,"change"),rX(this,"cmo"),rX(this,"cog"),rX(this,"correlation"),rX(this,"cross"),rX(this,"crossover"),rX(this,"crossunder"),rX(this,"cum"),rX(this,"dev"),rX(this,"dmi"),rX(this,"ema"),rX(this,"falling"),rX(this,"highest"),rX(this,"highestbars"),rX(this,"hma"),rX(this,"iii"),rX(this,"kc"),rX(this,"kcw"),rX(this,"linreg"),rX(this,"lowest"),rX(this,"lowestbars"),rX(this,"macd"),rX(this,"max"),rX(this,"median"),rX(this,"mfi"),rX(this,"min"),rX(this,"mode"),rX(this,"mom"),rX(this,"nvi"),rX(this,"obv"),rX(this,"param"),rX(this,"percentile_linear_interpolation"),rX(this,"percentile_nearest_rank"),rX(this,"percentrank"),rX(this,"pivothigh"),rX(this,"pivotlow"),rX(this,"pivot_point_levels"),rX(this,"pvi"),rX(this,"pvt"),rX(this,"range"),rX(this,"rci"),rX(this,"rising"),rX(this,"rma"),rX(this,"roc"),rX(this,"rsi"),rX(this,"sar"),rX(this,"sma"),rX(this,"stdev"),rX(this,"stoch"),rX(this,"supertrend"),rX(this,"swma"),rX(this,"tr"),rX(this,"tsi"),rX(this,"valuewhen"),rX(this,"variance"),rX(this,"vwap"),rX(this,"vwma"),rX(this,"wad"),rX(this,"wma"),rX(this,"wpr"),rX(this,"wvad"),Object.entries(r0).forEach(([t,i])=>{this[t]=i(e)})}}let r2=["title","shorttitle","overlay","format","precision","scale","pyramiding","calc_on_order_fills","calc_on_every_tick","max_bars_back","backtest_fill_limits_assumption","default_qty_type","default_qty_value","initial_capital","currency","slippage","commission_type","commission_value","process_orders_on_close","close_entries_rule","margin_long","margin_short","explicit_plot_zorder","max_lines_count","max_labels_count","max_boxes_count","calc_bars_count","risk_free_rate","use_bar_magnifier","fill_orders_on_standard_ohlc","max_polylines_count","dynamic_requests","behind_chart","calc_on_every_history_tick"];function r3(e,t,i){let r=e+t*i;if(!i||i<=0)return r;let n=e/i+t,s=Math.round(n);return Math.abs(n-s)>1e-6?r:r4(s,i)}function r4(e,t){let i=String(t),r=i.includes("e-")?Number(i.split("e-")[1])+(i.split("e-")[0].split(".")[1]?.length??0):i.split(".")[1]?.length??0;return Number((e*t).toFixed(r))}function r6(e,t){return t&&!(t<=0)&&Number.isFinite(e)?r4(Math.round(e/t),t):e}function r5(e,t){return e._fillsOnTickGrid?r6(t,e.pine?.syminfo?.mintick):t}function r9(e){let t=e.pine?.syminfo?.mintick;if(!e._fillsOnTickGrid||!t)return;let i=e._rawBar;if(!i)return{peakAt:e=>e};let r=r6(i.high,t),n=r6(i.low,t),s=r6(i.open,t);return{peakAt:e=>e===r?i.high:e===n?i.low:e===s?i.open:e}}function r8(e,t,i){if(!i||i<=0||!Number.isFinite(e)||e===t)return e;let r=e/i;return r4(e>t?Math.ceil(r-1e-4):Math.floor(r+1e-4),i)}function r7(e,t,i,r){if(!r||r<=0||!Number.isFinite(e))return e;let n=e/r;return r4("stop"===i==(1===t)?Math.ceil(n-1e-4):Math.floor(n+1e-4),r)}function ne(e,t){let i=e._entry_commission??("open"===e.status?e.commission??0:(e.commission??0)/2);return Math.abs(e.size)*e.entry_price*t+i}function nt(e,t,i,r){return Math.abs(e)*t*r*i/100}function ni(e,t){let i=e.strategy,r=e.pine?.syminfo?.pointvalue??1,n=0;for(let e of nz(i))n+=(1===e.dir?t-e.entry_price:e.entry_price-t)*e.qty*r;return i.initial_capital+i.netprofit+n}function nr(e,t,i,r,n=!0,s=!1){let a,o=e.strategy,l=o.config.default_qty_type||"fixed",h=o.config.default_qty_value??1;if("function"==typeof l&&(l=l()),"function"==typeof h&&(h=h()),null!=t&&!Number.isNaN(t))return nc(e,Math.abs(t));let c=e.pine?.syminfo?.pointvalue??1;switch(n&&(r=nk(e,i,r)),l){case"fixed":default:a=h;break;case"cash":a=h/(r*c);break;case"percent_of_equity":{let e=0===Number(-1===i?o.config.margin_short:o.config.margin_long)?Math.min(h,100):h,t=o.equity*e/100,n=r*c,s=o.config.commission_type??"percent",l=Number(o.config.commission_value??0)||0;a="cash_per_contract"===s?t/(n+l):"cash_per_order"===s?(t-l)/n:t/(n*(1+l/100))}}return s&&a<0?-nc(e,-a):nc(e,a)}function nn(e,t,i,r){let n=e=>"number"==typeof e&&Number.isFinite(e);return n(e)?(1===r?i>=e:i<=e)?i:e:n(t)?(1===r?i<=t:i>=t)?i:t:i}function ns(e){let t=Number(e.strategy?.config?.backtest_fill_limits_assumption??0);return!Number.isFinite(t)||t<=0?0:t*(e.pine?.syminfo?.mintick??.01)}function na(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:"function"==typeof e?e():e instanceof m?e.get(0):Array.isArray(e)?e[e.length-1]:"object"==typeof e&&void 0!==e.get?e.get(0):e}function no(e){return"number"==typeof e&&Number.isNaN(e)||"object"==typeof e&&null!==e&&"__value"in e}function nl(e){if(void 0===e.when)return!1;let t=na(e.when);return!t||no(t)}function nh(e){let t=e.pine?.syminfo?.mincontract;return"number"==typeof t&&t>0?t:1e-6}function nc(e,t){if(!Number.isFinite(t)||t<=0)return 0;let i=nh(e),r=Math.floor(t/i*(1+1e-10)),n=Math.min(10,Math.max(0,Math.ceil(-Math.log10(i))));return Number((r*i).toFixed(n))}function np(e,t,i){return Math.min(t,Math.max(nh(e),nc(e,t*i/100)))}function nu(e,t,i,r){return Math.abs(t-e)<=Math.abs(e-i)?[e,t,i,r]:[e,i,t,r]}function nd(e,t,i){if(i?e[0]>=t:e[0]<=t)return 0;for(let r=0;r<3;r++){let n=e[r],s=e[r+1];if(i?n<=t&&s>=t:n>=t&&s<=t)return r+(s===n?0:(t-n)/(s-n))}}function nm(e,t,i){let{dir:r,mintick:n}=i,s=e=>r*e,a=e=>{let t=r3(e,-r*i.offset,n);if(!i.offGrid||!n)return t;let s=t/n;return r4(1===r?Math.floor(s+1e-6):Math.ceil(s-1e-6),n)},o=i.offGrid?.peakAt??(e=>e),l=i.armed,h=i.peak,c=[t];for(let i=Math.floor(t.at)+1;i<e.length;i++)c.push({at:i,price:e[i]});if(l&&s(t.price)<=s(a(h))||l&&s(o(t.price))>s(h)&&(h=o(t.price),s(t.price)<=s(a(h))))return{fill:{price:t.price,at:t.at,level:a(h)},armed:l,peak:h};if(!l&&void 0!==i.armPrice&&s(t.price)>=s(i.armPrice)&&(l=!0,h=o(t.price),i.offset<=0&&t.at>0))return{fill:{price:t.price,at:t.at,level:t.price},armed:l,peak:h};for(let e=0;e+1<c.length;e++){let t=c[e],r=c[e+1],n=e=>t.price===r.price?t.at:t.at+(e-t.price)/(r.price-t.price)*(r.at-t.at);if(s(r.price)>s(t.price)){if(!l&&void 0!==i.armPrice&&s(r.price)>=s(i.armPrice)&&(l=!0,h=i.armPrice,i.offset<=0))return{fill:{price:i.armPrice,at:n(i.armPrice),level:i.armPrice},armed:l,peak:h};l&&s(o(r.price))>s(h)&&(h=o(r.price))}else if(l&&s(r.price)<s(t.price)){let e=a(h);if(s(r.price)<=s(e))return{fill:{price:e,at:n(e),level:e},armed:l,peak:h}}}return{armed:l,peak:h}}function nf(e,t,i,r){let n=void 0!==e.profit?r3(t,i*e.profit,r):void 0,s=void 0!==e.loss?r3(t,-i*e.loss,r):void 0,a=(t,i,r)=>void 0===t?i:void 0===i||e._priceLegsWin?t:r(t,i);return{tp:a(e.limit,n,1===i?Math.min:Math.max),sl:a(e.stop,s,1===i?Math.max:Math.min)}}function ny(e,t,i,r){let n=void 0!==e.trail_points?r3(t,i*e.trail_points,r):void 0;return void 0===e.trail_price?n:void 0===n||e._priceLegsWin?e.trail_price:1===i?Math.min(e.trail_price,n):Math.max(e.trail_price,n)}function n_(e,t,i){let r=t._intrabarEntry?.bar===e.idx?t._intrabarEntry:void 0;if(r){let e="limit"===r.type!=(1===r.dir),t=nd(i,r.level,e);if(void 0!==t)return{at:t,price:r.level}}return{at:0,price:i[0]}}function ng(e,t,i){let r=e.strategy,n=Math.sign(r.position_size),s=[];if(0===n)return s;let a=e.pine?.syminfo?.mintick??.01,o=ns(e);for(let l of r.pending_orders)if(!("pending"!==l.status||(l.category??"entry")!=="exit"||l.bar>=e.idx))for(let h of r.opentrades){if(l.from_entry&&h.entry_id!==l.from_entry||h._exits_filled?.has(l.id))continue;let r=(e,t)=>{void 0!==e&&s.push({at:e,level:t,order:l,trade:h})},c=h._bracket_entry??h.entry_price,{tp:p,sl:u}=nf(l,c,n,a);if(void 0!==p&&r(nd(t,p+n*o,1===n),p),void 0!==u&&r(nd(t,u,1!==n),u),i&&void 0!==l.trail_offset&&(void 0!==l.trail_price||void 0!==l.trail_points)){let i=ny(l,c,n,a),s=l._trailByTrade?.[h.id]??{armed:!1,peak:NaN},o=nm(t,n_(e,h,t),{...s,armPrice:i,offset:l.trail_offset,dir:n,mintick:a,offGrid:r9(e)}).fill;o&&r(o.at,o.level)}}return s}function nx(e,t){t._placed=e._placeCount=(e._placeCount??0)+1,e.pending_orders.push(t)}function nb(e){return!!e.oca_name&&("cancel"===e.oca_type||"reduce"===e.oca_type)}function nv(e,t,i){let r=nN(e.direction);if("market"===e.type)return 0;let n="limit"===e.type?e.limit:e.stop;if(void 0!==n)return nd(i,t??n,"limit"===e.type?-1===r:1===r)}function nw(e,t,i,r){let n=i??Math.abs(t._base_qty??t.qty);for(let i of e.pending_orders)i===t||"pending"!==i.status||i.oca_name!==t.oca_name||i.oca_type!==t.oca_type||("cancel"===t.oca_type?i.status="cancelled":r?.(i)||(i.category??"entry")==="exit"&&!(i.qty>0)||(i.qty=Math.max(0,i.qty-n),void 0!==i._base_qty&&(i._base_qty=Math.max(0,i._base_qty-n)),i.qty<=1e-9&&(i.status="cancelled")))}function nS(e,t=!1){if(!e.strategy)return;let i=e.strategy,{pending_orders:r}=i,n=m.from(e.data.open).get(0),s=m.from(e.data.high).get(0),a=m.from(e.data.low).get(0),o=m.from(e.data.close).get(0),l=m.from(e.data.openTime).get(0);nU(e,n);let h=ns(e),c=nu(n,s,a,o),p=(e,t)=>0===t&&"market"===e.type&&(e.category??"entry")!=="exit"?+(1!==nN(e.direction)):0,u=e=>(e.category??"entry")==="exit"||"market"===e.type?0:"limit"===e.type?2:1,d=(e,t)=>{if(0!==t||"market"===e.type||(e.category??"entry")==="exit")return 0;let i="limit"===e.type?e.limit:e.stop;return void 0===i?0:Math.abs(i-n)},f=r.map((t,i)=>({o:t,i:i,at:(t=>{if((t.category??"entry")==="exit"||"pending"!==t.status||t.bar>=e.idx||"market"===t.type)return 0;let i=nN(t.direction),r="limit"===t.type?t.limit:t.stop;return void 0===r?0:nd(c,r,"limit"===t.type?-1===i:1===i)??1/0})(t)})).sort((e,t)=>e.at-t.at||u(e.o)-u(t.o)||d(e.o,e.at)-d(t.o,t.at)||p(e.o,e.at)-p(t.o,t.at)||e.i-t.i).map(e=>e.o);for(let p of(t||(i._preFillSize={idx:e.idx,size:i.position_size}),f)){if("pending"!==p.status||(p.category??"entry")==="exit"||t&&p._deferredPastExits!==e.idx||p.bar>=e.idx)continue;let u=!1,d=n;switch(p.type){case"market":u=!0,d=n;break;case"limit":if(void 0!==p.limit){let e=nN(p.direction);1===e&&a<=p.limit-h?(u=!0,d=n<=p.limit-h?n:p.limit):-1===e&&s>=p.limit+h&&(u=!0,d=n>=p.limit+h?n:p.limit)}break;case"stop":if(void 0!==p.stop){let e=nN(p.direction);1===e&&s>=p.stop?(u=!0,d=Math.max(n,p.stop)):-1===e&&a<=p.stop&&(u=!0,d=Math.min(n,p.stop))}break;case"stop-limit":if(void 0!==p.stop&&void 0!==p.limit){let e,t=nN(p.direction);p._stopTriggered?e=n:(1===t?s>=p.stop:a<=p.stop)&&(p._stopTriggered=!0,e=1===t?Math.max(n,p.stop):Math.min(n,p.stop)),void 0!==e&&((1===t?e<=p.limit:e>=p.limit)?(u=!0,d=e):(1===t?a<=p.limit-h:s>=p.limit+h)&&(u=!0,d=p.limit))}}t&&void 0!==p._deferredFillPrice&&(u=!0,d=p._deferredFillPrice,p._deferredFillPrice=void 0);let m=[];if(u&&!t&&("limit"===p.type||"stop"===p.type||"stop-limit"===p.type)){let t=nN(p.direction),r=Math.sign(i.position_size);if(0!==r&&r!==t){let i=nu(n,s,a,o),r=nd(i,d,"limit"===p.type?-1===t:1===t),l=void 0===r?[]:ng(e,i,!0),h="limit"===p.type?p.limit:p.stop,c=t=>1e-9>=Math.abs(t.at-r)&&t.trade.entry_bar_index<e.idx,u=new Map;for(let e of l){if(!c(e))continue;let t=`${e.order._placed}:${e.trade.id}`;u.set(t,Math.max(u.get(t)??0,Math.abs(e.level-n)))}let f=Math.abs(h-n);if(l.some(e=>{if(e.at<r-1e-9)return!0;if(!c(e))return!1;let t=u.get(`${e.order._placed}:${e.trade.id}`);return 0===r&&Math.abs(t-f)>1e-9?t<f:(e.order._placed??0)<(p._placed??0)})){p._deferredPastExits=e.idx,p._deferredFillPrice=d;continue}let y=new Set;for(let e of l){let t=`${e.order._placed}:${e.trade.id}`;c(e)&&!y.has(t)&&(y.add(t),m.push({order:e.order,trade:e.trade}))}}}if(u&&nb(p)){let t=nu(n,s,a,o),i=nv(p,d,t);if(r.some(r=>r!==p&&"pending"===r.status&&r.oca_name===p.oca_name&&r.oca_type===p.oca_type&&nb(r)&&(r.category??"entry")!=="exit"&&r.bar<e.idx&&(nv(r,void 0,t)??1/0)<(i??1/0)))continue}if(u){let t=m.map(({trade:e})=>Math.abs(e.size));if(nW(e,"market"===p.type?0:nv(p,d,c)??0),e._fillOnVertex="market"===p.type||d===n,nE(e,p,d,l,n),e._fillOnVertex=void 0,"filled"===p.status&&m.forEach(({order:r,trade:s},a)=>{if(i.opentrades.includes(s)||!(t[a]>1e-9))return;let o={id:r.id,comment:r.comment,direction:-Math.sign(s.size),qty:t[a],type:void 0!==r.stop||void 0!==r.loss?"stop":"limit",bar:e.idx,time:l,status:"pending"};nE(e,o,d,l,n)}),"filled"===p.status&&nb(p)){let t=t=>"stop"===t.type&&void 0!==t.stop&&t.bar<e.idx&&(t.category??"entry")!=="exit"&&(1===nN(t.direction)?n>=t.stop:n<=t.stop);nw(i,p,void 0,t(p)?t:void 0)}if("filled"===p.status&&"market"!==p.type&&d!==n){let t="limit"===p.type||"stop-limit"===p.type&&d===p.limit?"limit":"stop";for(let r of i.opentrades)r.entry_id!==p.id||r.entry_bar_index!==e.idx||r._intrabarEntry||(r._intrabarEntry={bar:e.idx,level:d,type:t,dir:nN(p.direction)})}}}i.pending_orders=r.filter(e=>"pending"===e.status),nU(e,o),e.strategy}function nE(e,t,i,r,n){let s=e.strategy;if(function(e,t){let i=e.strategy._risk;return!!i&&(void 0!==i.haltedFrom&&t.bar>=i.haltedFrom||void 0!==i.blockFrom&&t.bar>=i.blockFrom&&t.bar<=(i.blockTo??1/0))}(e,t)||"entry"===t.category&&Math.sign(s.position_size)===nN(t.direction)&&nC(s,nN(t.direction))){t.status="cancelled";return}let a=nN(t.direction);("market"===t.type||"stop"===t.type)&&(i=nk(e,a,i));let o=s.risk_rules??{};if("entry"===t.category){let n=s.position_size,l="long"===o.allow_entry_in?1:"short"===o.allow_entry_in?-1:0;if(0!==l&&a!==l){if(Math.sign(n)===l){nq(e,Math.abs(n),i,r,{exitId:t.id,exitComment:t.comment}),t.status="filled",t.fill_price=i,t.fill_bar=e.idx,t.fill_time=r,nj(e,i);return}let s=t._isReversalEntry&&void 0!==t._base_qty?t.qty-t._base_qty:0;if(0!==n||!(s>1e-9)){t.status="cancelled";return}t.qty=s,t._base_qty=s}if(void 0!==o.max_position_size){let i=Number(o.max_position_size),r=0!==n&&Math.sign(n)!==a,s=r?Math.abs(n):0,l=r?0:Math.abs(n),h=Math.max(0,t.qty-s),c=nc(e,Math.max(0,i-l));if(h>c+1e-9){if(c<=0&&0===s){t.status="cancelled";return}t.qty=s+c,void 0!==t._base_qty&&(t._base_qty=c)}}}let l=1===a?s.config.margin_long??100:s.config.margin_short??100;{let o=s.position_size,h=Math.sign(o),c=0!==h&&h!==a,p=s._preFillSize,u=p&&p.idx===e.idx?p.size:o,d=c&&Math.sign(u)===h,m=d?Math.max(0,t.qty-Math.abs(o)):t.qty;if(m>0&&l>0&&!t._risk){let c=e.pine?.syminfo?.pointvalue??1,p=(e._pathAt??0)>0&&(e._pathAt??0)<3,u=s._placement,f="market"===t.type&&0===e._pathAt&&u?.idx===e.idx?u:void 0,y=0;h===a&&(y=function(e,t){let i=e.strategy,r=e.pine?.syminfo?.pointvalue??1,n=0;for(let e of i.opentrades){let s=1===Math.sign(e.size)?i.config.margin_long??100:i.config.margin_short??100;n+=nt(e.size,t,s,r)}return n}(e,p?i:f?f.price:n));let _=(f?f.equity:p&&0!==o?ni(e,i):s.equity)-y,g=0===o&&t._isReversalEntry&&!t._reversesPending&&"market"!==t.type&&void 0!==t._base_qty,x=nt(g?Math.min(t._base_qty,m):m,i,l,c),b=t._base_qty,v=Math.min(b,t.qty-b),w=e=>nt(e,i,l,c)<=_,S=x>_&&t._reversesPending&&0===o&&v>0&&!w(t.qty-v)&&w(v);if(S&&(t.qty=v),x>_&&g&&t.qty-b>1e-9)t.qty-=b;else if(x>_&&!S){let n=Math.min(Math.abs(o),t.qty),s=f&&nt(m,f.price,l,c)<=_;d&&n>0&&!s?(nq(e,n,i,r,{exitId:t.id,exitComment:t.comment}),t.status="filled",t.fill_price=i,t.fill_bar=e.idx,t.fill_time=r,nj(e,i)):t.status="cancelled";return}}}(function(e,t,i,r){let n=e.strategy,s=nN(t.direction),a=n.position_size,o=Math.sign(a);if(1===o&&-1===s||-1===o&&1===s){let l=Math.min(Math.abs(a),t.qty),h=t.qty-l;if(nq(e,l,i,r,{exitId:t.id,exitComment:t.comment,isImplicitReversal:h>0,reversalShare:l/t.qty}),h>0){for(let e of n.pending_orders)"pending"===e.status&&(e.category??"entry")==="exit"&&!e.from_entry&&e._placedWithPosition&&e._placedDir===o&&(e.status="cancelled");let a=t._base_qty;void 0!==a&&h>a+1e-9?(nB(e,t.id,s,a,i,r,t.comment,a/t.qty),nB(e,t.id,s,h-a,i,r,t.comment,(h-a)/t.qty)):nB(e,t.id,s,h,i,r,t.comment,h/t.qty)}}else nB(e,t.id,s,t.qty,i,r,t.comment)})(e,t,i,r),t.status="filled",t.fill_price=i,t.fill_bar=e.idx,t.fill_time=r,nj(e,i)}function nN(e){return"number"==typeof e?e:"long"===e?1:"short"===e?-1:0}function nT(e,t,i,r){let n=t.config.commission_type??"percent",s=t.config.commission_value??0;if(!s||0===s)return 0;let a=e.pine?.syminfo?.pointvalue??1;switch(n){case"percent":return Math.abs(i)*r*a*(s/100);case"cash_per_contract":return Math.abs(i)*s;case"cash_per_order":return s;default:return 0}}function nk(e,t,i){let r=e.strategy.config.slippage??0;if(!r||0===r)return i;let n=r*(e.pine?.syminfo?.mintick??.01);return 1===t?i+n:i-n}function nA(e,t,i=0,r=NaN,n=!0){let s=e._openFills;if(s&&n&&t&&s.idx===t.idx&&0===t._pathAt&&(()=>{let i=m.from(t.data.open).get(0);return Math.abs(r-i)<=(e.config.slippage??0)*(t.pine?.syminfo?.mintick??.01)+1e-9*Math.abs(i)})()){i>0?s.buys+=i:s.sells+=i,s.real.push(e.position_size);return}nI(e,e.position_size)}function nI(e,t){let i=Math.abs(t);i>e.max_contracts_held_all&&(e.max_contracts_held_all=i),t>e.max_contracts_held_long&&(e.max_contracts_held_long=t),-t>e.max_contracts_held_short&&(e.max_contracts_held_short=-t)}function nC(e,t){let i=e.config.pyramiding??1,r=0;for(let i of e.opentrades)Math.sign(i.size)===t&&r++;return r>=i}let nM={orders:"Close Position (Max number of filled orders in one day)",drawdown:"Close Position (Max Drawdown)",intraday:"Close Position (Max intraday Loss)",consDays:"Close Position (Max consecutive loss days)"};function nP(e){let t=e.strategy;return t._risk??(t._risk={dayStartEquity:t.initial_capital,dayMaxEquity:t.initial_capital,dayFills:0,prevDayEndEquity:t.initial_capital,consLossDays:0,realizedPeak:t.initial_capital})}let nD=new Map;function nR(e,t,i,r){let n=e.strategy,s=nP(e),a=m.from(e.data.openTime).get(0);for(let r of(0!==e._pathAt||s._closingOut||(s._closingOut=!0,n1(e,"market"),s._closingOut=!1,nW(e,0)),n.opentrades.length>0&&0!==n.position_size&&nq(e,Math.abs(n.position_size),i,a,{exitId:t,exitComment:t,forced:!0}),n.pending_orders))"pending"===r.status&&(r.status="cancelled");"day"===r?(s.blockedDay=s.day,s.blockFrom=e.idx,s.blockTo=void 0):s.haltedFrom=e.idx}function nO(e){let t=e.strategy._risk;if(!t||t.dayStartBar!==e.idx||void 0!==e._pathAt&&0!==e._pathAt)return!1;let i=e._excSeg;return(!i||!(i.scale>0))&&(t.dayStartEquity=t.dayMaxEquity=ni(e,m.from(e.data.open).get(0)),!0)}function nj(e,t){let i=e.strategy;i&&(i._fillCount=(i._fillCount??0)+1);let r=i?._fillPnl??0;i&&(i._fillPnl=0);let n=i?.risk_rules;if(!n||0===Object.keys(n).length)return;let s=nP(e);if(void 0!==s.haltedFrom||s._closingOut)return;s.dayFills++;let a=i.initial_capital+i.netprofit;if(s.realizedPeak=Math.max(s.realizedPeak,a),n.max_drawdown&&void 0===s.haltedFrom){let i=s.realizedPeak-a,r=Number(n.max_drawdown.value);if("percent_of_equity"===n.max_drawdown.type?100*i/s.realizedPeak>=r-1e-12:i>=r-1e-9)return nR(e,nM.drawdown,t,"forever")}if(n.max_intraday_filled_orders&&s.dayFills>=Number(n.max_intraday_filled_orders.count))return nR(e,nM.orders,t,"day");n.max_intraday_loss&&!nO(e)&&nV(e,t,r)}function nV(e,t,i=0){let r=e.strategy,n=r.risk_rules.max_intraday_loss;if(!n)return!1;let s=nP(e);if(s.blockedDay===s.day)return!1;let a=0!==r.position_size?ni(e,t):r.initial_capital+r.netprofit;s.dayMaxEquity=Math.max(s.dayMaxEquity,a);let o=s.dayStartEquity-(a-i),l=Number(n.value);return o>=("percent_of_equity"===n.type?l/100*s.dayMaxEquity:l)-1e-9&&(nR(e,nM.intraday,t,"day"),!0)}function n$(e){let t=e.strategy?._risk;t&&t._drawdownAtClose===e.idx&&(t._drawdownAtClose=void 0,nW(e,3),nR(e,nM.drawdown,m.from(e.data.close).get(0),"forever"))}function nL(e){let t=e.strategy;if(!t?.risk_rules?.max_intraday_loss||0===t.position_size)return;let i=nP(e);if(void 0!==i.haltedFrom&&i.haltedFrom<=e.idx)return;let r=Math.sign(t.position_size),n=m.from(e.data[1===r?"high":"low"]).get(0);i.dayMaxEquity=Math.max(i.dayMaxEquity,ni(e,n));let s=m.from(e.data[1===r?"low":"high"]).get(0),a=nu(m.from(e.data.open).get(0),m.from(e.data.high).get(0),m.from(e.data.low).get(0),m.from(e.data.close).get(0));nW(e,a[1]===s?1:2),nV(e,s)}function nB(e,t,i,r,n,s,a,o){let l=e.strategy,h=l.opentrades.length+l.closedtrades.length,c=l.config.commission_type??"percent",p=nT(e,l,r,n),u=void 0!==o&&"cash_per_order"===c?p*o:p,d={id:`trade_${h}`,entry_id:t,entry_comment:a??t,entry_price:n,_bracket_entry:n,entry_bar_index:e.idx,entry_time:s,size:i*r,commission:u,max_drawdown:0,max_runup:0,status:"open"};d._entry_qty=Math.abs(d.size),l.opentrades.push(d),void 0===l._first_entry_price&&(l._first_entry_price=n);let m={entry_id:t,entry_price:n,entry_time:s,entry_bar_index:e.idx,entry_comment:d.entry_comment,qty:r,commission:u};(l._ledger_entries??(l._ledger_entries=[])).push(m),u>0&&(l.netprofit-=u,l.grossloss+=u);let f=e._pathAt??0,y=l._marginFrom;f>0&&!(y?.idx===e.idx&&y.at>=f)&&(l._marginFrom={idx:e.idx,at:f}),m._dir=i,nJ(e,d,i),nJ(e,m,i);let _=e.pine?.syminfo?.pointvalue??1,g=nH(d._fav,d._adv,r,_,u);d.max_runup=g.runup,d.max_drawdown=g.drawdown,nY(e,{price:n,np:-u,add:{ref:m,dir:i,qty:r,entry:n,comm:u}});let x=l.position_size,b=x+d.size;if(0===x)l.position_size=b,l.position_avg_price=n,l.position_entry_name=t;else if(Math.sign(x)===Math.sign(b)){let e=Math.abs(x)*l.position_avg_price+r*n;l.position_avg_price=e/Math.abs(b),l.position_size=b}nA(l,e,d.size,n)}function nF(e,t,i){let r=t.profit??0;r>0?(e.grossprofit+=i*r,e.wintrades+=i,e.wintrades_total_profit+=i*r):r<0?(e.grossloss+=i*Math.abs(r),e.losstrades+=i,e.losstrades_total_loss+=i*Math.abs(r)):e.eventrades+=i}function nq(e,t,i,r,n){let s=e.strategy,a=e.pine?.syminfo?.pointvalue??1,o=t,l=s.netprofit,h=[...s.opentrades];s.opentrades=[];let c=null;for(let l of h){if(o<=0){s.opentrades.push(l);continue}let p=Math.abs(l.size),u=Math.min(p,o),d=Math.sign(l.size),m=o=>{let p=(s.config.commission_type??"percent")==="cash_per_order",u=n?.isImplicitReversal&&p,m=p?nT(e,s,t,i)*(t>0?o/t:1):nT(e,s,o,i),f=u?m*(n?.reversalShare??.5):m;for(let t of function(e,t,i){let r=[],n=i,s=e._ledger_entries??[],a="ANY"===String(e.config.close_entries_rule??"FIFO").toUpperCase();for(let e of s){if(n<=1e-9)break;if(a&&e.entry_id!==t.entry_id||e.qty<=1e-9)continue;let i=Math.min(e.qty,n),s=e.qty>0?e.commission*(i/e.qty):0;r.push({rec:e,entry_id:e.entry_id,qty:i,entry_price:e.entry_price,entry_time:e.entry_time,entry_bar_index:e.entry_bar_index,entry_comment:e.entry_comment,commission:s}),e.qty-=i,e.commission-=s,n-=i}if(e._ledger_entries=s.filter(e=>e.qty>1e-9),n>1e-9){let e=Math.abs(t.size);r.push({entry_id:t.entry_id,qty:n,entry_price:t.entry_price,entry_time:t.entry_time,entry_bar_index:t.entry_bar_index,entry_comment:t.entry_comment,commission:e>0?(t.commission??0)*(n/e):0})}return r}(s,l,o)){let p=f*(t.qty/o),u=(1===d?i-t.entry_price:t.entry_price-i)*t.qty*a,m=function(e,t,i,r,n){let s=e._pathAt??3;t._openBar===e.idx&&Number.isFinite(t._openAt)&&(s=Math.max(s,t._openAt));let a={entry_price:t.entry_price,_fav:t._fav,_adv:t._adv};return t._openBar===e.idx&&1e-9>Math.abs((t._openAt??NaN)-s)&&n!==n2?{}:(e._exc?.bar===e.idx&&nG(e,a,i,t._obsFrom??-.5,s,!1),nK(a,i,r),{fav:a._fav,adv:a._adv})}(e,t.rec??l,d,i,n?.exitId),y=nH(m.fav,m.adv,t.qty,a,t.commission);nY(e,{price:i,np:u-p,remove:{ref:t.rec??l,qty:t.qty,comm:t.commission}});let _={id:`trade_${s.opentrades.length+s.closedtrades.length+h.length}`,entry_id:t.entry_id,entry_comment:t.entry_comment,entry_price:t.entry_price,_bracket_entry:l._bracket_entry,entry_bar_index:t.entry_bar_index,entry_time:t.entry_time,size:d*t.qty,commission:t.commission+p,_entry_commission:t.commission,max_drawdown:y.drawdown,max_runup:y.runup,status:"closed",exit_price:i,exit_bar_index:e.idx,exit_time:r,exit_id:n?.exitId??l.exit_id,exit_comment:n?.exitComment??l.exit_comment,profit:u-t.commission-p};if(s.netprofit+=u-p,s.grossloss-=t.commission,t.rec&&c?.rec===t.rec){let e=c.row;nF(s,e,-1),e.size=e.size+_.size,e.commission=(e.commission??0)+(_.commission??0),e.profit=(e.profit??0)+(_.profit??0),e._entry_commission=(e._entry_commission??0)+t.commission;let i=nH(m.fav,m.adv,Math.abs(e.size),a,e._entry_commission??0);e.max_runup=i.runup,e.max_drawdown=i.drawdown,nF(s,e,1);continue}nF(s,_,1),s.closedtrades.push(_),c={rec:t.rec,row:_}}};if(u>=p-1e-9)l.status="closed",l.exit_price=i,l.exit_bar_index=e.idx,l.exit_time=r,m(p),o-=u;else{m(u);let e=(l.commission??0)*(u/p);l.size=d*(p-u),l.commission=(l.commission??0)-e,s.opentrades.push(l),o=0}}let p=s.position_size,u=Math.sign(p)*t,d=p-u;if(1e-9>Math.abs(d)&&(d=0),s.position_size=d,nA(s,e,d-p,i,!n?.forced),n?.isImplicitReversal&&(s._fillPnl=(s._fillPnl??0)+(s.netprofit-l)),0===d)s.position_avg_price=NaN,s.position_entry_name="";else if(s.opentrades.length>0){let e=0,t=0;for(let i of nz(s))e+=i.qty*i.entry_price,t+=i.qty;s.position_avg_price=e/t,s.position_entry_name=s._ledger_entries?.[0]?.entry_id??s.opentrades[0].entry_id}}function nz(e){let t=e._ledger_entries??[],i=Math.sign(e.position_size)||1;return t.length>0?t.map(e=>({qty:e.qty,entry_price:e.entry_price,commission:e.commission,dir:i})):e.opentrades.map(e=>({qty:Math.abs(e.size),entry_price:e.entry_price,commission:e.commission??0,dir:Math.sign(e.size)}))}function nU(e,t){let i=e.strategy,r=e.pine?.syminfo?.pointvalue??1,n=0;for(let e of nz(i))n+=(1===e.dir?t-e.entry_price:e.entry_price-t)*e.qty*r;i.openprofit=n,i.equity=i.initial_capital+i.netprofit+n}function nW(e,t){let i=e._excSeg;e._pathAt=i?i.offset+t*i.scale:t}function nK(e,t,i){let r=t*(i-e.entry_price);r<=e._fav||(e._fav=r),-r<=e._adv||(e._adv=-r)}function nG(e,t,i,r,n,s){let a=e._exc?.path;if(a)for(let e=0;e<a.length;e++)e>r+1e-9&&(s?e<=n+1e-9:e<n-1e-9)&&nK(t,i,a[e])}function nH(e,t,i,r,n){return i>0?{runup:void 0===e?0:Math.max(0,e*i*r-n),drawdown:void 0===t?0:Math.max(0,t*i*r+n)}:{runup:0,drawdown:0}}function nY(e,t){var i;let r=e._exc;if(!r||r.bar!==e.idx)return;if(r.finalized)return void((i=e.strategy)._excPreTicks??(i._excPreTicks=[])).push(t.price);let n=e._pathAt??0,s=t.remove?.ref;s?._openBar===e.idx&&Number.isFinite(s._openAt)&&(n=Math.max(n,s._openAt)),r.events.push({at:n,seq:r.events.length,...t})}function nZ(e){let t=e.strategy;if(!t)return;let i=nu(m.from(e.data.open).get(0),m.from(e.data.high).get(0),m.from(e.data.low).get(0),m.from(e.data.close).get(0));for(let r of(e._exc={bar:e.idx,path:i,events:[],start:{netprofit:t.netprofit,lots:function(e){let t=e._ledger_entries??[],i=Math.sign(e.position_size)||1;return t.length>0?t.map(e=>({ref:e,dir:e._dir??i,qty:e.qty,entry:e.entry_price,comm:e.commission})):e.opentrades.map(e=>({ref:e,dir:Math.sign(e.size),qty:Math.abs(e.size),entry:e.entry_price,comm:e.commission??0}))}(t)},pre:t._excPreTicks??[]},t._excPreTicks=[],e._pathAt=void 0,e._excSeg=void 0,t.opentrades))r._obsFrom=-.5;for(let e of t._ledger_entries??[])e._obsFrom=-.5}function nJ(e,t,i){let r=e._pathAt??0;t._fav=void 0,t._adv=void 0,t._openBar=e.idx,t._openAt=r,t._obsFrom=r;let n=e._exc?.bar===e.idx?e._exc.path:void 0,s=e._fillOnVertex??(0===r||3===r);n&&s&&Number.isInteger(r)&&r>=0&&r<n.length&&nK(t,i,n[r])}function nQ(e,t,i,r,n,s,a){let o=e.strategy,l=new Map(o.opentrades.map((e,t)=>[e,t])),h=()=>o.opentrades.sort((e,t)=>(l.get(e)??1/0)-(l.get(t)??1/0));if(void 0!==a){let t=[],l=[];for(let e of o.opentrades)e.id===a?t.push(e):l.push(e);if(0===t.length)return;let c=Math.abs(t[0].size);o.opentrades=[...t,...l],nq(e,Math.min(i,c),r,n,s),h();return}if(!t||""===t)return void nq(e,i,r,n,s);let c=[],p=[];for(let e of o.opentrades)e.entry_id===t?c.push(e):p.push(e);let u=c.reduce((e,t)=>e+Math.abs(t.size),0);if(0===u)return;let d=Math.min(i,u);o.opentrades=[...c,...p],nq(e,d,r,n,s),h()}function nX(e,t,i){let r=e.strategy,n=(t,i)=>{let r=new Map,n=t.qty&&t.qty>0?t.qty:1/0;for(let s of i){let i=Math.min(t.qty_percent&&t.qty_percent>0&&!(t.qty&&t.qty>0)?np(e,s._entry_qty??Math.abs(s.size),t.qty_percent):n,Math.abs(s.size));r.set(s,i),t.qty&&t.qty>0&&(n-=i)}return r},s=new Map(i.map(e=>[e,Math.abs(e.size)]));for(let e of r.pending_orders.filter(e=>e!==t&&"pending"===e.status&&(e.category??"entry")==="exit"&&!n0(e)&&(e._seq??1/0)<(t._seq??1/0)).sort((e,t)=>(e._seq??0)-(t._seq??0))){let t=i.filter(t=>(!e.from_entry||t.entry_id===e.from_entry)&&!t._exits_filled?.has(e.id));for(let[i,r]of n(e,t))s.set(i,Math.max(0,(s.get(i)??0)-r))}let a=new Map,o=0;for(let[e,r]of n(t,i)){let t=Math.min(r,s.get(e)??0);a.set(e,t),o+=t}return{total:o,perTrade:a}}function n0(e){return(e.category??"entry")==="exit"&&"market"===e.type&&void 0===e.profit&&void 0===e.loss&&void 0===e.limit&&void 0===e.stop&&void 0===e.trail_price&&void 0===e.trail_points}function n1(e,t="intrabar",i){if(!e.strategy)return;let r=e.strategy;if(0===r.pending_orders.length)return;let n=m.from(e.data.open).get(0),s=m.from(e.data.high).get(0),a=m.from(e.data.low).get(0),o=m.from(e.data.close).get(0),l=m.from(e.data.openTime).get(0),h=e.pine?.syminfo?.mintick??.01,c=!1,p=ns(e),u=nu(m.from(e.data.open).get(0),m.from(e.data.high).get(0),m.from(e.data.low).get(0),m.from(e.data.close).get(0)),d=r.pending_orders.map((i,r)=>({o:i,i:r,at:"intrabar"===t&&(i.category??"entry")==="exit"?function(e,t,i){if(n0(t))return 0;let r=e.strategy,n=e.pine?.syminfo?.mintick??.01,s=ns(e),a=1/0;for(let o of r.opentrades){if(t.from_entry&&o.entry_id!==t.from_entry)continue;let r=Math.sign(o.size),l=o._bracket_entry??o.entry_price,{tp:h,sl:c}=nf(t,l,r,n);if(void 0!==h&&(a=Math.min(a,nd(i,h+r*s,1===r)??1/0)),void 0!==c&&(a=Math.min(a,nd(i,c,1!==r)??1/0)),void 0!==t.trail_offset&&(void 0!==t.trail_price||void 0!==t.trail_points)){let s=ny(t,l,r,n),h=t._trailByTrade?.[o.id]??{armed:!1,peak:NaN},c=nm(i,{at:0,price:i[0]},{...h,armPrice:s,offset:t.trail_offset,dir:r,mintick:n,offGrid:r9(e)});c.fill&&(a=Math.min(a,c.fill.at))}}return a}(e,i,u):0})).sort((e,t)=>e.at-t.at||e.i-t.i),f=d.map((t,i)=>({x:t,slot:i,d:0===t.at&&(t.o.category??"entry")==="exit"?function(e,t,i){let r;if(n0(t))return;let n=e.pine?.syminfo?.mintick??.01;for(let s of e.strategy.opentrades){if(t.from_entry&&s.entry_id!==t.from_entry)continue;let e=Math.sign(s.size),{tp:a,sl:o}=nf(t,s._bracket_entry??s.entry_price,e,n);void 0!==a&&e*(i-a)>=0&&(r=Math.min(r??1/0,Math.abs(i-a))),void 0!==o&&e*(o-i)>=0&&(r=Math.min(r??1/0,Math.abs(i-o)))}return r}(e,t.o,n):void 0})).filter(e=>void 0!==e.d),y=f.map(e=>e.slot);for(let u of(f.sort((e,t)=>e.d-t.d||e.slot-t.slot).forEach((e,t)=>d[y[t]]=e.x),d.map(e=>e.o))){if("pending"!==u.status||(u.category??"entry")!=="exit"||"market"===t&&!n0(u))continue;let d=r.opentrades.filter(e=>!u.from_entry||e.entry_id===u.from_entry);if(u._intended_trade_ids){let e=new Set(u._intended_trade_ids);d=d.filter(t=>e.has(t.id))}if(0===d.length){"intrabar"===t&&(u.from_entry&&r.pending_orders.some(e=>"pending"===e.status&&(e.category??"entry")==="entry"&&e.id===u.from_entry)||(u.status="cancelled"));continue}if(i&&(n0(u)||0===(d=d.filter(e=>i.has(e.id))).length))continue;let m=d.reduce((e,t)=>e+Math.abs(t.size),0),f=Math.sign(d[0].size);if(n0(u)){if("open"===t||u.bar>=e.idx)continue;if("market"===t){if(u.immediately)continue;let t=r.pending_orders.indexOf(u);if(r.pending_orders.slice(0,t).some(t=>"pending"===t.status&&(t.category??"entry")==="entry"&&"market"===t.type&&t.bar<e.idx))continue}let i=u.immediately?o:n;i=nk(e,-f,i),nW(e,3*!!u.immediately);let s=m;u.qty&&u.qty>0?s=Math.min(u.qty,m):u.qty_percent&&u.qty_percent>0&&(s=np(e,m,u.qty_percent)),nQ(e,u.from_entry,s,i,l,{exitId:u.id,exitComment:u.comment}),u.status="filled",u.fill_price=i,u.fill_bar=e.idx,u.fill_time=l,nj(e,i);continue}if(0===(d=d.filter(e=>!e._exits_filled?.has(u.id))).length){"intrabar"===t&&(u.status="cancelled");continue}m=d.reduce((e,t)=>e+Math.abs(t.size),0);let y=new Map(d.map(e=>[e,Math.abs(e.size)]));for(let e of d)e.size,e.entry_price;let _=1===f,g=Math.abs(s-n)<=Math.abs(n-a),x=_?g:!g,b=[],v=[],w=r._mc_exit_lock,S=w&&w.bar===e.idx,E=nX(e,u,d);for(let i of d){if(S&&i.id!==w.tradeId)continue;let l=i._bracket_entry??i.entry_price,c=E.perTrade.get(i)??0;if(!(c>1e-9))continue;let{tp:d,sl:m}=nf(u,l,_?1:-1,h),f="intrabar"===t&&i._intrabarEntry?.bar===e.idx?i._intrabarEntry:void 0;if(f&&!S){let e=function(e,t,i,r,n,s){let{open:a,high:o,low:l,close:h}=n,c=Math.abs(o-a)<=Math.abs(a-l)?[a,o,l,h]:[a,l,o,h],p="limit"===e.type==(1===e.dir),u=e.level,d=-1;for(let e=0;e<3;e++){let t=c[e],i=c[e+1];if(p?t>=u&&i<=u:t<=u&&i>=u){d=e;break}}if(d<0)return;if(void 0!==t&&(r?u>=t:u<=t))return{kind:"profit",price:u};if(void 0!==i&&(r?u<=i:u>=i))return{kind:"loss",price:u};let m=[u,...c.slice(d+1)];for(let e=0;e+1<m.length;e++){let n=m[e],a=m[e+1];if(a>n){if(r&&void 0!==t&&a>=t+s)return{kind:"profit",price:t};if(!r&&void 0!==i&&a>=i)return{kind:"loss",price:i}}else if(a<n){if(r&&void 0!==i&&a<=i)return{kind:"loss",price:i};if(!r&&void 0!==t&&a<=t-s)return{kind:"profit",price:t}}}return null}(f,d,m,_,{open:n,high:s,low:a,close:o},p);if(void 0!==e){e&&("profit"===e.kind?b:v).push({qty:c,price:e.price,kind:e.kind,tradeId:i.id});continue}}let y=void 0!==d&&("open"===t?_?n>=d:n<=d:_?s>=d+p:a<=d-p),g=void 0!==m&&("open"===t?_?n<=m:n>=m:_?a<=m:s>=m),N=void 0!==m&&(_?n<=m:n>=m),T=void 0!==d&&(_?n>=d+p:n<=d-p);if(g&&N&&!_&&i.entry_bar_index===e.idx){let t=r._preFillSize;if((t?.idx===e.idx?t.size:0)<0){(i._exits_filled??(i._exits_filled=new Set)).add(u.id);continue}}let k=null;y&&g?k=N?"loss":T||x?"profit":"loss":y?k="profit":g&&(k="loss"),"loss"===k&&v.push({qty:c,price:N?n:m,kind:"loss",tradeId:i.id}),"profit"===k&&b.push({qty:c,price:T?n:d,kind:"profit",tradeId:i.id})}b.sort((e,t)=>_?e.price-t.price:t.price-e.price),v.sort((e,t)=>_?t.price-e.price:e.price-t.price);let N=nu(n,s,a,o),T=[];if("intrabar"===t&&!S&&void 0!==u.trail_offset&&(void 0!==u.trail_price||void 0!==u.trail_points)){let t=u._trailByTrade??(u._trailByTrade={});for(let i of d){let r=n_(e,i,N),n=t[i.id]??{armed:!1,peak:NaN},s=ny(u,i._bracket_entry??i.entry_price,_?1:-1,h),a=nm(N,r,{...n,armPrice:s,offset:u.trail_offset,dir:_?1:-1,mintick:h,offGrid:r9(e)});t[i.id]={armed:a.armed,peak:a.peak};let o=E.perTrade.get(i)??0;a.fill&&o>1e-9&&T.push({qty:o,price:a.fill.price,kind:"trailing",at:a.fill.at,tradeId:i.id})}}for(let e of b)e.at??(e.at=nd(N,e.price+(_?p:-p),_)??0);for(let e of v)e.at??(e.at=nd(N,e.price,!_)??0);let k=(x?[...b,...v,...T]:[...v,...T,...b]).sort((e,t)=>(e.at??0)-(t.at??0));if(k.length>0){let i=E.total,n=()=>r.opentrades.filter(e=>!u.from_entry||e.entry_id===u.from_entry).reduce((e,t)=>e+Math.abs(t.size),0),s=NaN,a=!1;for(let o of k){if(i<=1e-9)break;let h=n();if(h<=1e-9)break;let c=Math.min(o.qty===1/0?h:o.qty,i,h),p="profit"===o.kind?o.price:nk(e,-f,o.price),d="profit"===o.kind?u.comment_profit??u.comment:"loss"===o.kind?u.comment_loss??u.comment:u.comment_trailing??u.comment;nW(e,"intrabar"===t?o.at??0:0),nQ(e,u.from_entry,c,p,l,{triggerKind:o.kind,exitId:u.id,exitComment:d},o.tradeId),u.oca_name&&"reduce"===u.oca_type&&nw(r,u,c),i-=c,s=p,a=!0}for(let[t,r]of(a&&(c=!0,nj(e,s)),a&&(1e-9>=n()||i<=1e-9)&&(u.status="filled",u.fill_price=s,u.fill_bar=e.idx,u.fill_time=l),y))Math.abs(t.size)<r&&(t._exits_filled??(t._exits_filled=new Set)).add(u.id)}}if(c&&0===r.opentrades.length){let t=new Set(r.closedtrades.filter(t=>t.exit_bar_index===e.idx).map(e=>e.entry_id));for(let e of r.pending_orders)"pending"===e.status&&(e.category??"entry")==="exit"&&e._placedWithPosition&&(!e.from_entry||t.has(e.from_entry))&&(e.status="cancelled")}r.pending_orders=r.pending_orders.filter(e=>"pending"===e.status),nU(e,o)}let n2="Close position order";function n3(e,t="extreme"){let i=e.strategy;if(!i||0===i.opentrades.length)return!1;let r=Math.sign(i.position_size);if(0===r)return!1;let n=1===r?i.config.margin_long??100:i.config.margin_short??100;if(!(n>0)||i._risk?.haltedFrom!==void 0)return!1;let s=m.from(e.data.open).get(0),a=m.from(e.data.high).get(0),o=m.from(e.data.low).get(0),l=m.from(e.data.close).get(0),h=m.from(e.data.openTime).get(0),c=e.pine?.syminfo?.pointvalue??1,p="open"===t?s:"close"===t?l:"favorable"===t==(1===r)?a:o,u="open"===t?0:"close"===t?3:nu(s,a,o,l)[1]===p?1:2,d=e._excSeg,f=i._marginFrom;if(f?.idx===e.idx&&(d?d.offset+u*d.scale:u)<f.at-1e-9)return!1;let y=Math.abs(i.position_size),_=ni(e,p),g=nt(y,p,n,c);if(_<g){let s=g-_,a=n/100,o=nc(e,s/(p*c*a)),l=o>0?Math.min(y,Number((4*o).toFixed(10))):Math.min(y,1),d=[...i.opentrades],f=d[0],x=Math.abs(f.size),b=f.entry_price;if(nW(e,u),nq(e,l,nk(e,-r,p),h,{exitId:n2,exitComment:"Margin call",forced:!0}),function(e,t){let i=e.strategy.risk_rules?.max_drawdown;if(!i)return;let r=nP(e);if(void 0!==r.haltedFrom)return;let n=r.realizedPeak-ni(e,t),s=Number(i.value);("percent_of_equity"===i.type?100*n/r.realizedPeak>=s-1e-12:n>=s-1e-9)&&(r._drawdownAtClose=e.idx)}(e,p),"extreme"===t&&l>=x-1e-9&&Math.abs(i.position_size)>1e-9){let t=s-nt(x,p,n,c)+x*(p-b)*r*c;if(t>0){let n=m.from(e.data.close).get(0),s=Math.trunc(t/(p*c*a)*1e6)/1e6,o=Math.min(Math.abs(i.position_size),4*s);o>1e-9&&(i._pending_close_mc={qty:o,price:n,time:h,dir:r})}}let v=d.find(e=>"open"===e.status);return i._mc_exit_lock={bar:e.idx,tradeId:v?.id??null},!0}return!1}function n4(e){if(e.strategy&&(e.strategy._openFills={idx:e.idx,start:e.strategy.position_size,buys:0,sells:0,real:[]}),e.strategy?.risk_rules?.max_intraday_loss&&nO(e),e.strategy){let t=e._excSeg,i=t&&t.scale>0?m.from(e.data.open).get(0):m.from(e.data.close).get(1);Number.isFinite(i)&&(e.strategy._placement={idx:e.idx,price:i,equity:ni(e,i)})}n1(e,"market"),nS(e),n3(e,"open");let t=function(e){let t=e.strategy,i=Math.sign(t?.position_size??0);if(0===i)return!1;let r=m.from(e.data.open).get(0),n=Math.abs(m.from(e.data.high).get(0)-r)<=Math.abs(r-m.from(e.data.low).get(0));return 1===i?!n:n}(e)&&!function(e){if(!e.strategy||0===e.strategy.position_size)return!1;let t=m.from(e.data.open).get(0),i=m.from(e.data.high).get(0),r=m.from(e.data.low).get(0),n=m.from(e.data.close).get(0),s=function(e,t,i=!1){let r;for(let n of ng(e,t,i))(void 0===r||n.at<r)&&(r=n.at);return r}(e,nu(t,i,r,n));return void 0!==s&&s<1}(e);t&&(nL(e),n3(e,"extreme")),n1(e,"intrabar"),function(e){let t=e.strategy;if(!t||!t.pending_orders.some(t=>t._deferredPastExits===e.idx))return;let i=new Set(t.opentrades.map(e=>e.id));nS(e,!0);let r=new Set(t.opentrades.filter(e=>!i.has(e.id)).map(e=>e.id));r.size>0&&n1(e,"intrabar",r)}(e),n3(e,"favorable"),t||(nL(e),n3(e,"extreme")),e.strategy&&function(e){let t=e._openFills;if(e._openFills=void 0,!t||0===t.real.length)return;let i=t.start+t.buys,r=t.start+t.buys+t.sells,n=Math.sign(1e-9>Math.abs(i)?0:i);if(0===n||n===Math.sign(t.start)||n===Math.sign(1e-9>Math.abs(r)?0:r))nI(e,i),nI(e,1e-9>Math.abs(r)?0:r);else for(let i of t.real)nI(e,i)}(e.strategy)}function n6(e){if(Array.isArray(e))return e.map(n6);if(e instanceof Map){let t=new Map;return e.forEach((e,i)=>t.set(i,n6(e))),t}if(null!==e&&"object"==typeof e){let t={};for(let i of Object.keys(e))t[i]=n6(e[i]);return t}return e}function n5(e,t){if("number"==typeof t&&t<0)throw new ei(`Invalid \`qty\` value (${t}) in the \`${e}()\` call. Use a positive number less or equal to 1000000000000.`,e)}function n9(e,t){if(!("number"!=typeof t||Number.isNaN(t))&&(t>100||t<0||0===t&&"strategy.exit"===e))throw new ei(`Invalid \`qty_percent\` value (${t}) in the \`strategy.exit()\` call. Use a positive value less than or equal to 100 for this parameter.`,e)}function n8(e,t,i,r){let n=t.pending_orders.find(e=>("entry"===e.category||void 0===e.category)&&!e._risk&&e.id===i&&"pending"===e.status&&nN(e.direction)!==r);if(!n)return;let s="entry"===n.category?"strategy.entry":"strategy.order",a=e=>1===e?"long":"short",o=a(nN(n.direction)),l=a(r);throw new ei(`The '${s}' call already generated an order with the '${i}' ID in the '${o}' direction, which cannot be changed to '${l}'. Cancel the existing '${i}' order and create a new order in the desired direction, or specify a different 'id' for the '${l}' order.`,e)}let n7=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],se={id:"string",direction:"series",qty:"series",limit:"series",stop:"series",oca_name:"string",oca_type:"string",comment:"string",alert_message:"string",disable_alert:"boolean"},st=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],si={id:"string",direction:"series",qty:"series",limit:"series",stop:"series",oca_name:"string",oca_type:"string",comment:"string",alert_message:"string",disable_alert:"boolean"},sr=[["id","from_entry","qty","qty_percent","profit","limit","loss","stop","trail_price","trail_points","trail_offset","oca_name","comment","comment_profit","comment_loss","comment_trailing","alert_message","alert_profit","alert_loss","alert_trailing","disable_alert"]],sn={id:"string",from_entry:"string",qty:"series",qty_percent:"series",profit:"series",limit:"series",loss:"series",stop:"series",trail_price:"series",trail_points:"series",trail_offset:"series",oca_name:"string",comment:"string",comment_profit:"string",comment_loss:"string",comment_trailing:"string",alert_message:"string",alert_profit:"string",alert_loss:"string",alert_trailing:"string",disable_alert:"boolean"},ss=[["id","comment","qty","qty_percent","alert_message","immediately","disable_alert"]],sa={id:"string",comment:"string",qty:"series",qty_percent:"series",alert_message:"string",immediately:"boolean",disable_alert:"boolean"},so=[["comment","alert_message","immediately","disable_alert"]],sl={comment:"string",alert_message:"string",immediately:"boolean",disable_alert:"boolean"},sh=[["id","immediately"]],sc={id:"string",immediately:"boolean"},sp={any:function(e){return(...t)=>{let i=function(e){let t=e=>e instanceof m?e.get(0):e,i={};return e.forEach((e,r)=>{if(e4(e))for(let r of Object.keys(e))i[r]=t(e[r]);else r<r2.length&&void 0!==e&&(i[r2[r]]=t(e))}),i}(t);return e.strategy?e.strategy.config={...e.strategy.config,...i,...e._propOverrides??{}}:function(e,t){let i={...t,...e._propOverrides??{}},r={title:"",shorttitle:"",overlay:!1,format:"inherit",precision:10,scale:"right",pyramiding:1,calc_on_order_fills:!1,calc_on_every_tick:!1,max_bars_back:0,backtest_fill_limits_assumption:0,default_qty_type:"fixed",default_qty_value:1,initial_capital:1e6,currency:"USD",slippage:0,commission_type:"percent",commission_value:0,margin_long:100,margin_short:100,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,max_polylines_count:50,risk_free_rate:2,use_bar_magnifier:!1,fill_orders_on_standard_ohlc:!1,...5===e.pineVersion?{margin_long:0,margin_short:0}:{},...i},n=r.initial_capital,s=i.currency||e.pine?.syminfo?.currency||r.currency||"USD";e.strategy={config:r,opentrades:[],closedtrades:[],pending_orders:[],position_size:0,position_avg_price:NaN,position_entry_name:"",initial_capital:n,account_currency:s,equity:n,netprofit:0,grossprofit:0,grossloss:0,openprofit:0,max_drawdown:0,max_runup:0,equity_peak:n,equity_trough:n,equity_at_runup_peak:n,equity_at_drawdown_peak:n,max_drawdown_percent_value:0,max_runup_percent_value:0,sharpe_ratio:0,sortino_ratio:0,cagr:NaN,buy_and_hold_pnl:NaN,buy_and_hold_per_gain:NaN,strategy_outperformance:NaN,_first_entry_price:void 0,_monthly_equity:[],_last_month_key:-1,wintrades:0,losstrades:0,eventrades:0,wintrades_total_profit:0,losstrades_total_loss:0,max_contracts_held_all:0,max_contracts_held_long:0,max_contracts_held_short:0,risk_rules:{},risk_halted:!1}}(e,i),e.strategy.config}},order:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.order() called before strategy() declaration");let i=e5(t,n7,se);if(nl(i))return;let r=e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:"function"==typeof e?e():e instanceof m?e.get(0):Array.isArray(e)?e[e.length-1]:"object"==typeof e&&void 0!==e.get?e.get(0):e,n=e=>"number"==typeof e&&Number.isNaN(e)||"object"==typeof e&&null!==e&&"__value"in e?void 0:e,s=r(i.id),a=r(i.direction),o=n(r(i.qty)),l=n(r(i.limit)),h=n(r(i.stop)),c=r(i.oca_name),p=r(i.oca_type),u=r(i.comment),d=nN(a);n5("strategy.order",o),n8("strategy.order",e.strategy,s,d);let f=r5(e,m.from(e.data.close).get(0)),y=e.pine?.syminfo?.mintick??0;void 0!==l&&(l=r7(l,d,"limit",y)),void 0!==h&&(h=r7(h,d,"stop",y));let _=nr(e,o,d,nn(h,l,f,d),void 0===l);if(_<=0)return;let g="market";void 0!==l&&void 0!==h?g="stop-limit":void 0!==l?g="limit":void 0!==h&&(g="stop");let x=m.from(e.data.openTime).get(0),b={id:s,direction:d,qty:_,type:g,limit:l,stop:h,bar:e.idx,time:x,status:"pending",oca_name:c,oca_type:p,comment:u};return e.strategy.pending_orders=e.strategy.pending_orders.filter(e=>void 0!==e.category&&"entry"!==e.category||e.id!==s||"pending"!==e.status),nx(e.strategy,b),b}},param:function(e){return(e,t)=>m.from(e).get(t||0)},opentrades:function(e){return()=>{let t=function(e){let t=e.strategy;if(!t)return[];let i=t._ledger_entries??[];if(0===i.length)return t.opentrades.slice();let r=e.pine?.syminfo?.pointvalue??1,n=Math.sign(t.position_size)||1;return i.map((e,t)=>{let i=nH(e._fav,e._adv,e.qty,r,e.commission);return{id:`open_${t}`,entry_id:e.entry_id,entry_comment:e.entry_comment,entry_price:e.entry_price,entry_bar_index:e.entry_bar_index,entry_time:e.entry_time,size:(e._dir??n)*e.qty,commission:e.commission,max_runup:i.runup,max_drawdown:i.drawdown,status:"open"}})}(e),i=e=>{let i=Number(e);return t[Number.isNaN(i)?0:i]},r={__value:t.length,valueOf:()=>t.length,toString:()=>String(t.length),[Symbol.toPrimitive]:()=>t.length},n=e.pine?.syminfo?.pointvalue??1,s=e=>Math.abs(e.size)*e.entry_price*n+(e.commission??0);r.profit=t=>{let r=i(t);if(!r)return 0;let s=(()=>{let t=e.marketData;return Array.isArray(t)&&e.idx>=0&&e.idx<t.length?r5(e,t[e.idx]?.close??NaN):NaN})();return Number.isFinite(s)?(1===Math.sign(r.size)?s-r.entry_price:r.entry_price-s)*Math.abs(r.size)*n-(r.commission??0)-((t,i)=>{let r=e.strategy?.config,s=r?.commission_type??"percent",a=r?.commission_value??0;if(!a)return 0;let o=Math.abs(t.size);switch(s){case"percent":return o*i*n*(a/100);case"cash_per_contract":return o*a;case"cash_per_order":return a;default:return 0}})(r,s):NaN},r.profit_percent=e=>{let t=i(e);if(!t)return 0;let n=r.profit(e);if(!Number.isFinite(n))return NaN;let a=s(t);return 0!==a?100*n/a:NaN},r.size=e=>i(e)?.size??0,r.commission=e=>i(e)?.commission??0,r.entry_price=e=>i(e)?.entry_price??NaN,r.entry_bar_index=e=>i(e)?.entry_bar_index??NaN,r.entry_id=e=>i(e)?.entry_id??"",r.entry_comment=e=>i(e)?.entry_comment??i(e)?.entry_id??"",r.entry_time=e=>i(e)?.entry_time??NaN,r.max_drawdown=e=>i(e)?.max_drawdown??0,r.max_drawdown_percent=e=>{let t=i(e);if(!t||!t.max_drawdown)return 0;let r=s(t);return r>0?100*t.max_drawdown/r:0},r.max_runup=e=>i(e)?.max_runup??0,r.max_runup_percent=e=>{let t=i(e);if(!t||!t.max_runup)return 0;let r=s(t);return r>0?100*t.max_runup/r:0};let a=e.strategy,o=a?.config?.margin_long??100,l=a?.config?.margin_short??100,h=Math.sign(a?.position_size??0);if(a&&(h>0?o>0:!(h<0)&&o>0||l>0)){let e=0;for(let i of t)e+=Math.abs(i.size)*i.entry_price*n;r.capital_held=e}else r.capital_held=NaN;return r}},closedtrades:function(e){return()=>{let t=e.strategy?.closedtrades??[],i=t.length,r=Math.max(0,i-9e3),n=e=>{let n=Number(e);return Number.isNaN(n)&&(n=0),n>=r&&n<i?t[n]:void 0},s={__value:i,valueOf:()=>i,toString:()=>String(i),[Symbol.toPrimitive]:()=>i},a=e.pine?.syminfo?.pointvalue??1,o=e=>ne(e,a);return s.profit=e=>n(e)?.profit??0,s.profit_percent=e=>{let t=n(e);if(!t)return 0;if(void 0===t.profit)return NaN;let i=o(t);return 0!==i?100*t.profit/i:NaN},s.size=e=>n(e)?.size??0,s.commission=e=>n(e)?.commission??0,s.entry_price=e=>n(e)?.entry_price??NaN,s.entry_bar_index=e=>n(e)?.entry_bar_index??NaN,s.entry_id=e=>n(e)?.entry_id??"",s.entry_comment=e=>n(e)?.entry_comment??n(e)?.entry_id??"",s.entry_time=e=>n(e)?.entry_time??NaN,s.exit_price=e=>n(e)?.exit_price??NaN,s.exit_bar_index=e=>n(e)?.exit_bar_index??NaN,s.exit_id=e=>n(e)?.exit_id??"",s.exit_comment=e=>n(e)?.exit_comment??n(e)?.exit_id??"",s.exit_time=e=>n(e)?.exit_time??NaN,s.max_drawdown=e=>n(e)?.max_drawdown??0,s.max_drawdown_percent=e=>{let t=n(e);if(!t||!t.max_drawdown)return 0;let i=o(t);return i>0?100*t.max_drawdown/i:0},s.max_runup=e=>n(e)?.max_runup??0,s.max_runup_percent=e=>{let t=n(e);if(!t||!t.max_runup)return 0;let i=o(t);return i>0?100*t.max_runup/i:0},s.first_index=r,s}},netprofit:function(e){return()=>e.strategy?.netprofit??0},position_size:function(e){return()=>e.strategy?.position_size??0},position_avg_price:function(e){return()=>{let t=e.strategy;return t&&0!==t.position_size?t.position_avg_price:NaN}},equity:function(e){return()=>e.strategy?.equity??e.strategy?.config?.initial_capital??1e4},long:function(e){return()=>"long"},short:function(e){return()=>"short"},cash:function(e){return()=>"cash"},percent_of_equity:function(e){return()=>"percent_of_equity"},fixed:function(e){return()=>"fixed"},openprofit:function(e){return()=>e.strategy?.openprofit??0},openprofit_percent:function(e){return()=>{let t=e.strategy;if(!t)return 0;let i=(t.initial_capital??0)+(t.netprofit??0);return i?100*t.openprofit/i:0}},netprofit_percent:function(e){return()=>{let t=e.strategy;return t&&t.initial_capital?100*t.netprofit/t.initial_capital:0}},grossprofit:function(e){return()=>e.strategy?.grossprofit??0},grossprofit_percent:function(e){return()=>{let t=e.strategy;return t&&t.initial_capital?100*t.grossprofit/t.initial_capital:0}},grossloss:function(e){return()=>e.strategy?.grossloss??0},grossloss_percent:function(e){return()=>{let t=e.strategy;return t&&t.initial_capital?100*t.grossloss/t.initial_capital:0}},wintrades:function(e){return()=>e.strategy?.wintrades??0},losstrades:function(e){return()=>e.strategy?.losstrades??0},eventrades:function(e){return()=>e.strategy?.eventrades??0},avg_trade:function(e){return()=>{let t=e.strategy;return t&&t.closedtrades&&0!==t.closedtrades.length?t.netprofit/t.closedtrades.length:NaN}},avg_trade_percent:function(e){return()=>{let t=e.strategy;if(!t||!t.closedtrades||0===t.closedtrades.length)return NaN;let i=e.pine?.syminfo?.pointvalue??1,r=0;for(let e of t.closedtrades){let t=ne(e,i);0!==t&&(r+=100*(e.profit??0)/t)}return r/t.closedtrades.length}},avg_winning_trade:function(e){return()=>{let t=e.strategy;return t&&0!==t.wintrades?t.wintrades_total_profit/t.wintrades:NaN}},avg_winning_trade_percent:function(e){return()=>{let t=e.strategy;if(!t||0===t.wintrades)return NaN;let i=e.pine?.syminfo?.pointvalue??1,r=0;for(let e of t.closedtrades)if((e.profit??0)>0){let t=ne(e,i);0!==t&&(r+=100*(e.profit??0)/t)}return r/t.wintrades}},avg_losing_trade:function(e){return()=>{let t=e.strategy;return t&&0!==t.losstrades?t.grossloss/t.losstrades:NaN}},avg_losing_trade_percent:function(e){return()=>{let t=e.strategy;if(!t||0===t.losstrades)return NaN;let i=e.pine?.syminfo?.pointvalue??1,r=0;for(let e of t.closedtrades)if((e.profit??0)<0){let t=ne(e,i);0!==t&&(r+=100*(e.profit??0)/t)}return r/t.losstrades}},max_drawdown:function(e){return()=>e.strategy?.max_drawdown??0},max_drawdown_percent:function(e){return()=>{let t=e.strategy;return t?t.max_drawdown_percent_value??0:0}},max_runup:function(e){return()=>e.strategy?.max_runup??0},max_runup_percent:function(e){return()=>{let t=e.strategy;return t?t.max_runup_percent_value??0:0}},max_contracts_held_all:function(e){return()=>e.strategy?.max_contracts_held_all??0},max_contracts_held_long:function(e){return()=>e.strategy?.max_contracts_held_long??0},max_contracts_held_short:function(e){return()=>e.strategy?.max_contracts_held_short??0},position_entry_name:function(e){return()=>e.strategy?.position_entry_name??""},initial_capital:function(e){return()=>e.strategy?.initial_capital??0},account_currency:function(e){return()=>e.strategy?.account_currency??"USD"},margin_liquidation_price:function(e){return()=>{let t=e.strategy;if(!t||0===t.position_size)return NaN;let i=t.position_avg_price;if(!Number.isFinite(i))return NaN;let r=Math.sign(t.position_size),n=1===r?t.config.margin_long??100:t.config.margin_short??100;if(!(n>0)||1===r&&100===n)return NaN;let s=Math.abs(t.position_size),a=e.pine?.syminfo?.pointvalue??1,o=((t.initial_capital??0)+(t.netprofit??0))/(a*s)-r*i,l=e.pine?.syminfo?.mintick??.01,h=o/(n/100-r)/l;return 1===r?Math.floor(h+1e-6)*l:Math.ceil(h-1e-6)*l}},entry:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.entry() called before strategy() declaration");let i=e5(t,st,si);if(nl(i))return;let r=e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:"function"==typeof e?e():e instanceof m?e.get(0):Array.isArray(e)?e[e.length-1]:"object"==typeof e&&void 0!==e.get?e.get(0):e,n=e=>"number"==typeof e&&Number.isNaN(e)||"object"==typeof e&&null!==e&&"__value"in e?void 0:e,s=r(i.id),a=r(i.direction),o=n(r(i.qty)),l=n(r(i.limit)),h=n(r(i.stop)),c=r(i.oca_name),p=r(i.oca_type),u=r(i.comment),d=nN(a),f=e.strategy;n5("strategy.entry",o),n8("strategy.entry",f,s,d);let y=f.position_size;for(let t of f.pending_orders)if(t.bar===e.idx&&"pending"===t.status){if(("entry"===t.category||void 0===t.category)&&"market"===t.type)y+=nN(t.direction)*t.qty;else if(n0(t)&&0!==y){let i=f.opentrades.filter(e=>!t.from_entry||e.entry_id===t.from_entry);if(t._intended_trade_ids){let e=new Set(t._intended_trade_ids);i=i.filter(t=>e.has(t.id))}let r=i.reduce((e,t)=>e+Math.abs(t.size),0),n=r;t.qty&&t.qty>0?n=Math.min(t.qty,r):t.qty_percent&&t.qty_percent>0&&(n=np(e,r,t.qty_percent)),y-=Math.sign(y)*Math.min(n,Math.abs(y))}}if(Math.sign(y)===d&&0!==y&&nC(f,d))return;let _=r5(e,m.from(e.data.close).get(0)),g="market";void 0!==l&&void 0!==h?g="stop-limit":void 0!==l?g="limit":void 0!==h&&(g="stop");let x=e.pine?.syminfo?.mintick??0,b=void 0!==l?r7(l,d,"limit",x):void 0,v=void 0!==h?r7(h,d,"stop",x):void 0,w=nr(e,o,d,nn(v,b,_,d),void 0===b),S=0!==y&&Math.sign(y)!==d;if(w<=0&&!S)return;let E=S?Math.abs(y)+w:w,N=m.from(e.data.openTime).get(0),T={id:s,direction:d,qty:E,type:g,limit:b,stop:v,bar:e.idx,time:N,status:"pending",category:"entry",oca_name:c,oca_type:p,comment:u,_isReversalEntry:S,_base_qty:w,_reversesPending:S&&Math.sign(f.position_size)!==Math.sign(y)};f.pending_orders=f.pending_orders.filter(e=>"entry"!==e.category&&void 0!==e.category||e.id!==s||"pending"!==e.status),nx(f,T)}},exit:function(e){return(...t)=>{let i;if(!e.strategy)throw Error("strategy.exit() called before strategy() declaration");e6(t);let r=e5(t,sr,sn);if(nl(r))return;let n=e=>void 0!==r[e];if(!(["profit","limit","loss","stop"].some(n)||n("trail_offset")&&(n("trail_price")||n("trail_points"))))throw new ei('strategy.exit must have at least one of the following parameters: "profit", "limit", "loss", "stop" or one of the following pairs: "trail_offset" and "trail_price" / "trail_points". To close the position at market price, use "strategy.close"',"strategy.exit");let s=e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:"function"==typeof e?e():e instanceof m?e.get(0):Array.isArray(e)?e[e.length-1]:"object"==typeof e&&void 0!==e.get?e.get(0):e,a=s(r.id),o=s(r.from_entry),l=s(r.qty),h=s(r.qty_percent),c=e=>"number"==typeof e&&Number.isNaN(e)||"object"==typeof e&&null!==e&&"__value"in e,p=e=>c(e)?void 0:e,u=e=>"number"==typeof e?Math.ceil(e-1e-9):e,d=u(p(s(r.profit))),f=p(s(r.limit)),y=u(p(s(r.loss))),_=p(s(r.stop)),g=p(s(r.trail_price)),x=p(s(r.trail_points)),b="number"==typeof(i=p(s(r.trail_offset)))?Math.trunc(i+1e-9*Math.sign(i)):i,v=o??"",w=v?e.strategy.pending_orders.find(e=>"entry"===e.category&&e.id===v&&"pending"===e.status):e.strategy.pending_orders.find(e=>"entry"===e.category&&"pending"===e.status),S=!!w?._isReversalEntry;if(v&&!w&&!e.strategy.opentrades.some(e=>e.entry_id===v))return;(null==l||c(l))&&n9("strategy.exit",h);let E=e.pine?.syminfo?.mintick??0,N=e._fillPointPrice??m.from(e.data.close).get(0),T=e.strategy.opentrades.find(e=>!v||e.entry_id===v),k=T?Math.sign(T.size):w?nN(w.direction):0,A=(e,t)=>void 0===e?void 0:k?r7(e,-k,t,E):r8(e,N,E),I=A(f,"limit"),C=A(_,"stop"),M=void 0!==g?r8(g,N,E):void 0,P=a??"exit",D=e.strategy.pending_orders,R=[];for(let e=D.length-1;e>=0;e--){let t=D[e];"exit"===t.category&&t.id===P&&(t.from_entry??"")===v&&"pending"===t.status&&(R.push(t),D.splice(e,1))}if([d,I,y,C,M,x].every(e=>void 0===e))return;let O={id:P,direction:0,qty:null==l||c(l)?0:nc(e,Math.abs(Number(l))),qty_percent:c(h)?void 0:h,type:"market",bar:e.idx,time:m.from(e.data.openTime).get(0),status:"pending",category:"exit",from_entry:v,profit:d,loss:y,limit:I,stop:C,trail_price:M,_trailPriceRaw:g,trail_points:x,trail_offset:b,oca_name:s(r.oca_name),_priceLegsWin:5===e.pineVersion,oca_type:s(r.oca_name)?"reduce":void 0,comment:s(r.comment),comment_profit:s(r.comment_profit),comment_loss:s(r.comment_loss),comment_trailing:s(r.comment_trailing),alert_message:s(r.alert_message),alert_profit:s(r.alert_profit),alert_loss:s(r.alert_loss),alert_trailing:s(r.alert_trailing),disable_alert:s(r.disable_alert),_attachedAtReversal:S,_placedWithPosition:e.strategy.opentrades.length>0,_placedDir:Math.sign(e.strategy.position_size)},j=R.find(e=>e._trailByTrade&&e._trailPriceRaw===g&&e.trail_points===x);if(j&&(O._trailByTrade={...j._trailByTrade}),void 0!==O.trail_offset&&(void 0!==M||void 0!==x)){let t=e._fillPointPrice??m.from(e.data.close).get(0);for(let i of e.strategy.opentrades){if(v&&i.entry_id!==v||O._trailByTrade?.[i.id]?.armed)continue;let e=Math.sign(i.size),r=ny(O,i._bracket_entry??i.entry_price,e,E);Number.isFinite(t)&&e*(t-r)>=0&&((O._trailByTrade??(O._trailByTrade={}))[i.id]={armed:!0,peak:t})}}let V=e.strategy,$=V._exit_seqs??(V._exit_seqs=new Map),L=`${P}\0${v}`;$.has(L)||$.set(L,$.size+1),O._seq=$.get(L),nx(e.strategy,O)}},close:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.close() called before strategy() declaration");let i=e5(t,ss,sa);if(nl(i))return;let r=na(i.id),n=na(i.qty),s=na(i.qty_percent),a=no(n)||null==n?void 0:nc(e,Math.abs(Number(n))),o=no(s)?void 0:s;if(null==r||!e.strategy.opentrades.some(e=>e.entry_id===r))return;void 0===a&&n9("strategy.close",o);let l=e=>(e.category??"entry")==="exit"&&(void 0!==e.profit||void 0!==e.loss||void 0!==e.limit||void 0!==e.stop||void 0!==e.trail_price||void 0!==e.trail_points),h=e.strategy.pending_orders,c=void 0!==a&&Number(a)>0||void 0!==o&&Number(o)>0&&100>Number(o);for(let e of h)!c&&l(e)&&(e.from_entry??"")===r&&"pending"===e.status&&(e.status="cancelled");e.strategy.pending_orders=h.filter(e=>"pending"===e.status);let p={id:`Close entry(s) order ${r}`,direction:0,qty:0,type:"market",bar:e.idx,time:m.from(e.data.openTime).get(0),status:"pending",category:"exit",from_entry:r,qty_percent:o,comment:na(i.comment),alert_message:na(i.alert_message),immediately:!0===na(i.immediately),disable_alert:na(i.disable_alert),_intended_trade_ids:e.strategy.opentrades.filter(e=>e.entry_id===r).map(e=>e.id)};void 0!==a&&(p.qty=a),e.strategy.pending_orders.push(p)}},close_all:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.close_all() called before strategy() declaration");let i=e5(t,so,sl);if(nl(i)||0===e.strategy.opentrades.length)return;let r=e=>(e.category??"entry")==="exit"&&(void 0!==e.profit||void 0!==e.loss||void 0!==e.limit||void 0!==e.stop||void 0!==e.trail_price||void 0!==e.trail_points),n=e.strategy.pending_orders;for(let e of n)r(e)&&"pending"===e.status&&(e.status="cancelled");e.strategy.pending_orders=n.filter(e=>"pending"===e.status);let s={id:"Close position order",direction:0,qty:0,type:"market",bar:e.idx,time:m.from(e.data.openTime).get(0),status:"pending",category:"exit",from_entry:"",comment:na(i.comment),alert_message:na(i.alert_message),immediately:!0===na(i.immediately),disable_alert:na(i.disable_alert),_intended_trade_ids:e.strategy.opentrades.map(e=>e.id)};e.strategy.pending_orders.push(s)}},cancel:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.cancel() called before strategy() declaration");let i=e5(t,sh,sc);if(nl(i))return;let r=na(i.id);null!=r&&(e.strategy.pending_orders=e.strategy.pending_orders.filter(e=>"pending"!==e.status||e.id!==r))}},cancel_all:function(e){return(...t)=>{if(!e.strategy)throw Error("strategy.cancel_all() called before strategy() declaration");nl(e5(t,[[]],{}))||(e.strategy.pending_orders=e.strategy.pending_orders.filter(e=>"pending"!==e.status))}},convert_to_account:function(e){return t=>{let i=e.strategy,r=e.pine?.syminfo?.currency,n=i?.account_currency??"USD";return r&&r!==n?NaN:t}},convert_to_symbol:function(e){return t=>{let i=e.strategy,r=e.pine?.syminfo?.currency,n=i?.account_currency??"USD";return r&&r!==n?NaN:t}},default_entry_qty:function(e){return t=>e.strategy?nr(e,void 0,1,t,!1,!0):0}},su={long:"long",short:"short",all:"all"},sd={none:"none",cancel:"cancel",reduce:"reduce"},sm={percent:"percent",cash_per_order:"cash_per_order",cash_per_contract:"cash_per_contract"};class sf{constructor(e){this.context=e,Object.entries(sp).forEach(([t,i])=>{this[t]=i(e)}),this.direction=()=>su,this.oca=()=>sd,this.commission=()=>sm;let t=function(e){return{allow_entry_in:t=>{e.strategy&&(e.strategy.risk_rules.allow_entry_in=na(t))},max_cons_loss_days:(t,i)=>{e.strategy&&(e.strategy.risk_rules.max_cons_loss_days={count:Number(na(t)),alert_message:na(i)})},max_drawdown:(t,i,r)=>{e.strategy&&(e.strategy.risk_rules.max_drawdown={value:Number(na(t)),type:na(i)})},max_intraday_filled_orders:(t,i)=>{e.strategy&&(e.strategy.risk_rules.max_intraday_filled_orders={count:Number(na(t)),alert_message:na(i)})},max_intraday_loss:(t,i,r)=>{e.strategy&&(e.strategy.risk_rules.max_intraday_loss={value:Number(na(t)),type:na(i)})},max_position_size:t=>{e.strategy&&(e.strategy.risk_rules.max_position_size=Number(na(t)))}}}(e);this.risk=()=>t}}class sy{constructor(e){this.context=e}logFormat(e,...t){return 0===t.length?e:this.context.pine.str.format(e,...t)}param(e,t=0,i){return m.from(e).get(t)}_formatTimestamp(){let e=this.context.data.openTime.data[this.context.idx],t=function(e,t){let i=t.trim();if("UTC"===i||"GMT"===i||"Etc/UTC"===i)return 0;let r=i.match(/^(?:UTC|GMT)([+-])(\d{1,2})(?::(\d{2}))?$/i);if(r){let e="+"===r[1]?1:-1;return e*(60*parseInt(r[2],10)+parseInt(r[3]||"0",10))}let n=tb(e,t);return Math.round((new Date(Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)).getTime()-e)/6e4)}(e,this.context.chartTimezone||this.context.pine?.syminfo?.timezone||"UTC"),i=e=>String(Math.floor(Math.abs(e))).padStart(2,"0"),r=(t>=0?"+":"-")+i(t/60)+":"+i(t%60);return`[${new Date(e+6e4*t).toISOString().slice(0,-1)}${r}]`}warning(e,...t){this.context.isSecondaryContext||console.warn(`${this._formatTimestamp()} ${this.logFormat(e,...t)}`)}error(e,...t){this.context.isSecondaryContext||console.error(`${this._formatTimestamp()} ${this.logFormat(e,...t)}`)}info(e,...t){this.context.isSecondaryContext||console.log(`${this._formatTimestamp()} ${this.logFormat(e,...t)}`)}}class s_{constructor(e){this.context=e}param(e,t=0,i){return m.from(e).get(t)}error(e){let t=m.from(e).get(0);throw new ei("string"==typeof t?t:String(t??""),"runtime.error")}}let sg=`
3
+ ACST|Australian Central Standard Time|ACDT|Australian Central Daylight Time=Australia/Adelaide Australia/Broken_Hill Australia/Darwin Australia/North Australia/South Australia/Yancowinna
4
+ ACT|Acre Standard Time|ACST|Acre Summer Time=America/Eirunepe America/Porto_Acre America/Rio_Branco Brazil/Acre
5
+ ACWST|Australian Central Western Standard Time|ACWDT|Australian Central Western Daylight Time=Australia/Eucla
6
+ AEST|Australian Eastern Standard Time|AEDT|Australian Eastern Daylight Time=Antarctica/Macquarie Australia/ACT Australia/Brisbane Australia/Canberra Australia/Currie Australia/Hobart Australia/Lindeman Australia/Melbourne Australia/NSW Australia/Queensland Australia/Sydney Australia/Tasmania Australia/Victoria
7
+ AFT|Afghanistan Time=Asia/Kabul
8
+ AKST|Alaska Standard Time|AKDT|Alaska Daylight Time=America/Anchorage America/Juneau America/Metlakatla America/Nome America/Sitka America/Yakutat US/Alaska
9
+ ALMT|East Kazakhstan Time|ALMST|Alma-Ata Summer Time=Asia/Almaty
10
+ AMT|Amazon Standard Time|AMST|Amazon Summer Time=America/Boa_Vista America/Campo_Grande America/Cuiaba America/Manaus America/Porto_Velho Brazil/West
11
+ AMT|Armenia Standard Time|AMST|Armenia Summer Time=Asia/Yerevan
12
+ ANAT|Anadyr Standard Time|ANAST|Anadyr Summer Time=Asia/Anadyr
13
+ AQTT|West Kazakhstan Time|AQTST|Aqtau Summer Time=Asia/Aqtau
14
+ AQTT|West Kazakhstan Time|AQTST|Aqtobe Summer Time=Asia/Aqtobe
15
+ ART|Argentina Standard Time|ARST|Argentina Summer Time=America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Buenos_Aires America/Catamarca America/Cordoba America/Jujuy America/Mendoza America/Rosario
16
+ AST|Arabian Standard Time=Asia/Aden Asia/Bahrain Asia/Kuwait Asia/Qatar Asia/Riyadh
17
+ AST|Arabian Standard Time|ADT|Arabian Daylight Time=Asia/Baghdad
18
+ AST|Atlantic Standard Time|ADT|Atlantic Daylight Time=America/Anguilla America/Antigua America/Aruba America/Barbados America/Blanc-Sablon America/Curacao America/Dominica America/Glace_Bay America/Goose_Bay America/Grenada America/Guadeloupe America/Halifax America/Kralendijk America/Lower_Princes America/Marigot America/Martinique America/Moncton America/Montserrat America/Port_of_Spain America/Puerto_Rico America/Santo_Domingo America/St_Barthelemy America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Thule America/Tortola America/Virgin Atlantic/Bermuda Canada/Atlantic
19
+ AWST|Australian Western Standard Time|AWDT|Australian Western Daylight Time=Australia/Perth Australia/West
20
+ AWST|Casey Time=Antarctica/Casey
21
+ AZOT|Azores Standard Time|AZOST|Azores Summer Time=Atlantic/Azores
22
+ AZT|Azerbaijan Standard Time|AZST|Azerbaijan Summer Time=Asia/Baku
23
+ BDT|Bangladesh Standard Time|BDST|Bangladesh Summer Time=Asia/Dacca Asia/Dhaka
24
+ BNT|Brunei Darussalam Time|BNST|Brunei Summer Time=Asia/Brunei
25
+ BOT|Bolivia Time|BOST|Bolivia Summer Time=America/La_Paz
26
+ BRT|Brasilia Standard Time|BRST|Brasilia Summer Time=America/Araguaina America/Bahia America/Belem America/Fortaleza America/Maceio America/Recife America/Santarem America/Sao_Paulo Brazil/East
27
+ BST|Bougainville Standard Time=Pacific/Bougainville
28
+ BTT|Bhutan Time=Asia/Thimbu Asia/Thimphu
29
+ CAT|Central Africa Time=Africa/Blantyre Africa/Bujumbura Africa/Gaborone Africa/Harare Africa/Kigali Africa/Lubumbashi Africa/Lusaka Africa/Maputo
30
+ CAT|Central Africa Time|CAST|Central African Summer Time=Africa/Juba Africa/Khartoum
31
+ CAT|Central Africa Time|WAT|Western African Time=Africa/Windhoek
32
+ CCT|Cocos Islands Time=Indian/Cocos
33
+ CET|Central European Standard Time|CEST|Central European Summer Time=Africa/Algiers Africa/Ceuta Africa/Tunis Arctic/Longyearbyen Atlantic/Jan_Mayen Europe/Amsterdam Europe/Andorra Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Budapest Europe/Busingen Europe/Copenhagen Europe/Gibraltar Europe/Ljubljana Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Monaco Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Rome Europe/San_Marino Europe/Sarajevo Europe/Skopje Europe/Stockholm Europe/Tirane Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Warsaw Europe/Zagreb Europe/Zurich Poland
34
+ CET|Central European Time|CEST|Central European Summer Time=CET
35
+ CHAST|Chatham Standard Time|CHADT|Chatham Daylight Time=NZ-CHAT Pacific/Chatham
36
+ CHOT|Ulaanbaatar Standard Time|CHOST|Ulaanbaatar Summer Time=Asia/Choibalsan
37
+ ChST|Chamorro Standard Time|ChDT|Chamorro Daylight Time=Pacific/Guam Pacific/Saipan
38
+ CHUT|Chuuk Time=Pacific/Chuuk Pacific/Truk Pacific/Yap
39
+ CKT|Cook Islands Standard Time|CKHST|Cook Islands Half Summer Time=Pacific/Rarotonga
40
+ CLT|Chile Standard Time|CLST|Chile Summer Time=America/Santiago Chile/Continental
41
+ CLT|Chile Time|CLST|Chile Summer Time=Antarctica/Palmer
42
+ COT|Colombia Standard Time|COST|Colombia Summer Time=America/Bogota
43
+ CST|Central Standard Time|CDT|Central Daylight Time=America/Bahia_Banderas America/Belize America/Chicago America/Chihuahua America/Costa_Rica America/El_Salvador America/Guatemala America/Indiana/Knox America/Indiana/Tell_City America/Knox_IN America/Managua America/Matamoros America/Menominee America/Merida America/Mexico_City America/Monterrey America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga America/Rainy_River America/Rankin_Inlet America/Regina America/Resolute America/Swift_Current America/Tegucigalpa America/Winnipeg CST6CDT Canada/Central Canada/Saskatchewan Mexico/General US/Central US/Indiana-Starke
44
+ CST|China Standard Time|CDT|China Daylight Time=Asia/Chongqing Asia/Chungking Asia/Harbin Asia/Macao Asia/Macau Asia/Shanghai PRC
45
+ CST|Cuba Standard Time|CDT|Cuba Daylight Time=America/Havana Cuba
46
+ CST|Taipei Standard Time|CDT|Taipei Daylight Time=Asia/Taipei
47
+ CVT|Cape Verde Standard Time|CVST|Cape Verde Summer Time=Atlantic/Cape_Verde
48
+ CXT|Christmas Island Time=Indian/Christmas
49
+ DAVT|Davis Time=Antarctica/Davis
50
+ DDUT|Dumont-d\u2019Urville Time=Antarctica/DumontDUrville
51
+ EAST|Easter Island Standard Time|EASST|Easter Island Summer Time=Chile/EasterIsland Pacific/Easter
52
+ EAT|East Africa Time=Africa/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Africa/Nairobi Indian/Antananarivo Indian/Comoro Indian/Mayotte
53
+ ECT|Ecuador Time|ECST|Ecuador Summer Time=America/Guayaquil
54
+ EET|Eastern European Standard Time|EEST|Eastern European Summer Time=Africa/Cairo Africa/Tripoli Asia/Beirut Asia/Gaza Asia/Hebron Asia/Nicosia Egypt Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kaliningrad Europe/Kiev Europe/Kyiv Europe/Mariehamn Europe/Nicosia Europe/Riga Europe/Sofia Europe/Tallinn Europe/Tiraspol Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye Libya
55
+ EET|Eastern European Time|EEST|Eastern European Summer Time=Asia/Amman Asia/Damascus Asia/Famagusta EET
56
+ EGT|East Greenland Standard Time|EGST|East Greenland Summer Time=America/Scoresbysund
57
+ EST|Eastern Standard Time=America/Atikokan America/Cayman America/Coral_Harbour America/Panama
58
+ EST|Eastern Standard Time|EDT|Eastern Daylight Time=America/Cancun America/Detroit America/Fort_Wayne America/Grand_Turk America/Indiana/Indianapolis America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Iqaluit America/Jamaica America/Kentucky/Louisville America/Kentucky/Monticello America/Louisville America/Montreal America/Nassau America/New_York America/Nipigon America/Pangnirtung America/Port-au-Prince America/Thunder_Bay America/Toronto Canada/Eastern EST5EDT Jamaica US/East-Indiana US/Eastern US/Michigan
59
+ FJT|Fiji Standard Time|FJST|Fiji Summer Time=Pacific/Fiji
60
+ FKT|Falkland Islands Standard Time|FKST|Falkland Islands Summer Time=Atlantic/Stanley
61
+ FNT|Fernando de Noronha Standard Time|FNST|Fernando de Noronha Summer Time=America/Noronha Brazil/DeNoronha
62
+ GALT|Galapagos Time|GALST|Galapagos Summer Time=Pacific/Galapagos
63
+ GAMT|Gambier Time=Pacific/Gambier
64
+ GET|Georgia Standard Time|GEST|Georgia Summer Time=Asia/Tbilisi
65
+ GFT|French Guiana Time=America/Cayenne
66
+ GILT|Gilbert Islands Time=Pacific/Tarawa
67
+ GMT-01:00|GMT-01:00=Etc/GMT+1
68
+ GMT-02:00|GMT-02:00=Etc/GMT+2
69
+ GMT-03:00|Coyhaique Standard Time|GMT-03:00|Coyhaique Daylight Time=America/Coyhaique
70
+ GMT-03:00|GMT-03:00=Etc/GMT+3
71
+ GMT-03:00|Punta Arenas Standard Time=America/Punta_Arenas
72
+ GMT-04:00|GMT-04:00=Etc/GMT+4
73
+ GMT-05:00|GMT-05:00=Etc/GMT+5
74
+ GMT-06:00|GMT-06:00=Etc/GMT+6
75
+ GMT-07:00|GMT-07:00=Etc/GMT+7
76
+ GMT-08:00|GMT-08:00=Etc/GMT+8
77
+ GMT-09:00|GMT-09:00=Etc/GMT+9
78
+ GMT-10:00|GMT-10:00=Etc/GMT+10
79
+ GMT-11:00|GMT-11:00=Etc/GMT+11
80
+ GMT-12:00|GMT-12:00=Etc/GMT+12
81
+ GMT+01:00|GMT+01:00=Etc/GMT-1
82
+ GMT+02:00|GMT+02:00=Etc/GMT-2
83
+ GMT+03:00|GMT+03:00=Etc/GMT-3
84
+ GMT+04:00|Astrakhan Standard Time=Europe/Astrakhan
85
+ GMT+04:00|GMT+04:00=Etc/GMT-4
86
+ GMT+04:00|Saratov Standard Time=Europe/Saratov
87
+ GMT+04:00|Ulyanovsk Standard Time=Europe/Ulyanovsk
88
+ GMT+05:00|GMT+05:00=Etc/GMT-5
89
+ GMT+05:00|West Kazakhstan Time|GMT+05:00|Atyrau Daylight Time=Asia/Atyrau
90
+ GMT+06:00|GMT+06:00=Etc/GMT-6
91
+ GMT+07:00|Barnaul Standard Time|GMT+07:00|Barnaul Daylight Time=Asia/Barnaul
92
+ GMT+07:00|GMT+07:00=Etc/GMT-7
93
+ GMT+07:00|Tomsk Standard Time|GMT+07:00|Tomsk Daylight Time=Asia/Tomsk
94
+ GMT+08:00|GMT+08:00=Etc/GMT-8
95
+ GMT+09:00|GMT+09:00=Etc/GMT-9
96
+ GMT+10:00|GMT+10:00=Etc/GMT-10
97
+ GMT+11:00|GMT+11:00=Etc/GMT-11
98
+ GMT+12:00|GMT+12:00=Etc/GMT-12
99
+ GMT+13:00|GMT+13:00=Etc/GMT-13
100
+ GMT+14:00|GMT+14:00=Etc/GMT-14
101
+ GMT|Greenwich Mean Time=Africa/Abidjan Africa/Accra Africa/Bamako Africa/Banjul Africa/Bissau Africa/Conakry Africa/Dakar Africa/Freetown Africa/Lome Africa/Monrovia Africa/Nouakchott Africa/Ouagadougou Africa/Sao_Tome Africa/Timbuktu America/Danmarkshavn Atlantic/Reykjavik Atlantic/St_Helena Etc/GMT Etc/GMT+0 Etc/GMT-0 Etc/GMT0 Etc/Greenwich GMT0 Greenwich Iceland
102
+ GMT|Greenwich Mean Time|BST|British Summer Time=Europe/Belfast Europe/Guernsey Europe/Isle_of_Man Europe/Jersey Europe/London GB GB-Eire
103
+ GMT|Greenwich Mean Time|CEST|Central European Summer Time=Antarctica/Troll
104
+ GMT|Greenwich Mean Time|IST|Irish Standard Time=Eire Europe/Dublin
105
+ GST|Gulf Standard Time=Asia/Dubai Asia/Muscat
106
+ GST|South Georgia Time=Atlantic/South_Georgia
107
+ GYT|Guyana Time=America/Guyana
108
+ HAST|Hawaii-Aleutian Standard Time|HADT|Hawaii-Aleutian Daylight Time=America/Adak America/Atka Pacific/Johnston US/Aleutian
109
+ HKT|Hong Kong Standard Time|HKST|Hong Kong Summer Time=Asia/Hong_Kong Hongkong
110
+ HOVT|Hovd Standard Time|HOVST|Hovd Summer Time=Asia/Hovd
111
+ HST|Hawaii-Aleutian Standard Time|HDT|Hawaii-Aleutian Daylight Time=Pacific/Honolulu US/Hawaii
112
+ ICT|Indochina Time=Asia/Bangkok Asia/Ho_Chi_Minh Asia/Phnom_Penh Asia/Saigon Asia/Vientiane
113
+ IOT|Indian Ocean Time=Indian/Chagos
114
+ IRKT|Irkutsk Standard Time|IRKST|Irkutsk Summer Time=Asia/Irkutsk
115
+ IRST|Iran Standard Time|IRDT|Iran Daylight Time=Asia/Tehran Iran
116
+ IST|India Standard Time|IDT|India Daylight Time=Asia/Calcutta Asia/Colombo Asia/Kolkata
117
+ IST|Israel Standard Time|IDT|Israel Daylight Time=Asia/Jerusalem Asia/Tel_Aviv Israel
118
+ JST|Japan Standard Time|JDT|Japan Daylight Time=Asia/Tokyo Japan
119
+ KGT|Kyrgyzstan Time|KGST|Kirgizstan Summer Time=Asia/Bishkek
120
+ KOST|Kosrae Time=Pacific/Kosrae
121
+ KRAT|Krasnoyarsk Standard Time|KRAST|Krasnoyarsk Summer Time=Asia/Krasnoyarsk Asia/Novokuznetsk
122
+ KST|Korean Standard Time=Asia/Pyongyang
123
+ KST|Korean Standard Time|KDT|Korean Daylight Time=Asia/Seoul ROK
124
+ LHST|Lord Howe Standard Time|LHDT|Lord Howe Daylight Time=Australia/LHI Australia/Lord_Howe
125
+ LINT|Line Islands Time=Pacific/Kiritimati
126
+ MAGT|Magadan Standard Time|MAGST|Magadan Summer Time=Asia/Magadan
127
+ MART|Marquesas Time=Pacific/Marquesas
128
+ MAWT|Mawson Time=Antarctica/Mawson
129
+ MET|Middle Europe Time|MEST|Middle Europe Summer Time=MET
130
+ MHT|Marshall Islands Time=Kwajalein Pacific/Kwajalein Pacific/Majuro
131
+ MMT|Myanmar Time=Asia/Rangoon Asia/Yangon
132
+ MSK|Moscow Standard Time|MSD|Moscow Daylight Time=Europe/Kirov
133
+ MSK|Moscow Standard Time|MSD|Moscow Summer Time=Europe/Minsk Europe/Moscow Europe/Simferopol W-SU
134
+ MSK|Volgograd Standard Time|MSD|Volgograd Summer Time=Europe/Volgograd
135
+ MST|Mexican Pacific Standard Time|MDT|Mexican Pacific Daylight Time=America/Hermosillo America/Mazatlan Mexico/BajaSur
136
+ MST|Mountain Standard Time|MDT|Mountain Daylight Time=America/Boise America/Cambridge_Bay America/Ciudad_Juarez America/Creston America/Dawson_Creek America/Denver America/Edmonton America/Fort_Nelson America/Inuvik America/Phoenix America/Shiprock America/Yellowknife Canada/Mountain MST7MDT Navajo US/Arizona US/Mountain
137
+ MST|Yukon Time|MDT|Mountain Daylight Time=America/Dawson America/Whitehorse Canada/Yukon
138
+ MUT|Mauritius Standard Time|MUST|Mauritius Summer Time=Indian/Mauritius
139
+ MVT|Maldives Time=Indian/Maldives
140
+ MYT|Malaysia Time|MYST|Malaysia Summer Time=Asia/Kuala_Lumpur Asia/Kuching
141
+ NCT|New Caledonia Standard Time|NCST|New Caledonia Summer Time=Pacific/Noumea
142
+ NFT|Norfolk Island Standard Time|NFST|Norfolk Island Daylight Time=Pacific/Norfolk
143
+ NOVT|Novosibirsk Standard Time|NOVST|Novosibirsk Summer Time=Asia/Novosibirsk
144
+ NPT|Nepal Time=Asia/Kathmandu Asia/Katmandu
145
+ NRT|Nauru Time=Pacific/Nauru
146
+ NST|Newfoundland Standard Time|NDT|Newfoundland Daylight Time=America/St_Johns Canada/Newfoundland
147
+ NUT|Niue Time=Pacific/Niue
148
+ NZST|New Zealand Standard Time|NZDT|New Zealand Daylight Time=Antarctica/McMurdo Antarctica/South_Pole NZ Pacific/Auckland
149
+ OMST|Omsk Standard Time|OMSST|Omsk Summer Time=Asia/Omsk
150
+ ORAT|West Kazakhstan Time|ORAST|Oral Summer Time=Asia/Oral
151
+ PET|Peru Standard Time|PEST|Peru Summer Time=America/Lima
152
+ PETT|Petropavlovsk-Kamchatski Standard Time|PETST|Petropavlovsk-Kamchatski Summer Time=Asia/Kamchatka
153
+ PGT|Papua New Guinea Time=Pacific/Port_Moresby
154
+ PHOT|Phoenix Islands Time=Pacific/Enderbury Pacific/Kanton
155
+ PKT|Pakistan Standard Time|PKST|Pakistan Summer Time=Asia/Karachi
156
+ PMST|St. Pierre & Miquelon Standard Time|PMDT|St. Pierre & Miquelon Daylight Time=America/Miquelon
157
+ PONT|Ponape Time=Pacific/Pohnpei Pacific/Ponape
158
+ PST|Northwest Mexico Standard Time|PDT|Northwest Mexico Daylight Time=America/Santa_Isabel
159
+ PST|Pacific Standard Time|PDT|Pacific Daylight Time=America/Ensenada America/Los_Angeles America/Tijuana America/Vancouver Canada/Pacific Mexico/BajaNorte PST8PDT US/Pacific
160
+ PST|Philippine Standard Time|PDT|Philippine Summer Time=Asia/Manila
161
+ PST|Pitcairn Time=Pacific/Pitcairn
162
+ PWT|Palau Time=Pacific/Palau
163
+ PYT|Paraguay Standard Time|PYST|Paraguay Summer Time=America/Asuncion
164
+ QOST|East Kazakhstan Time|QOSST|Kostanay Summer Time=Asia/Qostanay
165
+ QYZT|West Kazakhstan Time|QYZST|Qyzylorda Summer Time=Asia/Qyzylorda
166
+ RET|R\xe9union Time=Indian/Reunion
167
+ ROTT|Rothera Time=Antarctica/Rothera
168
+ SAKT|Sakhalin Standard Time|SAKST|Sakhalin Summer Time=Asia/Sakhalin
169
+ SAMT|Samara Standard Time|SAMST|Samara Summer Time=Europe/Samara
170
+ SAST|South Africa Standard Time|SAST|South Africa Summer Time=Africa/Johannesburg Africa/Maseru Africa/Mbabane
171
+ SBT|Solomon Islands Time=Pacific/Guadalcanal
172
+ SCT|Seychelles Time=Indian/Mahe
173
+ SGT|Singapore Standard Time|SGST|Singapore Summer Time=Asia/Singapore Singapore
174
+ SRET|Srednekolymsk Time|SREDT|Srednekolymsk Daylight Time=Asia/Srednekolymsk
175
+ SRT|Suriname Time=America/Paramaribo
176
+ SST|Samoa Standard Time=Pacific/Midway Pacific/Pago_Pago Pacific/Samoa US/Samoa
177
+ SYOT|Syowa Time=Antarctica/Syowa
178
+ TAHT|Tahiti Time=Pacific/Tahiti
179
+ TFT|French Southern & Antarctic Time=Indian/Kerguelen
180
+ TJT|Tajikistan Time|TJST|Tajikistan Summer Time=Asia/Dushanbe
181
+ TKT|Tokelau Time=Pacific/Fakaofo
182
+ TLT|East Timor Time=Asia/Dili
183
+ TMT|Turkmenistan Standard Time|TMST|Turkmenistan Summer Time=Asia/Ashgabat Asia/Ashkhabad
184
+ TOT|Tonga Standard Time|TOST|Tonga Summer Time=Pacific/Tongatapu
185
+ TRT|Turkey Time|TRST|Turkey Summer Time=Asia/Istanbul Europe/Istanbul Turkey
186
+ TVT|Tuvalu Time=Pacific/Funafuti
187
+ ULAT|Ulaanbaatar Standard Time|ULAST|Ulaanbaatar Summer Time=Asia/Ulaanbaatar Asia/Ulan_Bator
188
+ UTC|Coordinated Universal Time=Etc/UCT Etc/UTC Etc/Universal Etc/Zulu UCT Universal Zulu
189
+ UYT|Uruguay Standard Time|UYST|Uruguay Summer Time=America/Montevideo
190
+ UZT|Uzbekistan Standard Time|UZST|Uzbekistan Summer Time=Asia/Samarkand Asia/Tashkent
191
+ VET|Venezuela Time=America/Caracas
192
+ VLAT|Vladivostok Standard Time|VLAST|Vladivostok Summer Time=Asia/Ust-Nera Asia/Vladivostok
193
+ VOST|Vostok Time=Antarctica/Vostok
194
+ VUT|Vanuatu Standard Time|VUST|Vanuatu Summer Time=Pacific/Efate
195
+ WAKT|Wake Island Time=Pacific/Wake
196
+ WAT|West Africa Standard Time=Africa/Bangui Africa/Brazzaville Africa/Douala Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Luanda Africa/Malabo Africa/Niamey Africa/Porto-Novo
197
+ WAT|West Africa Standard Time|WAST|West Africa Summer Time=Africa/Ndjamena
198
+ WET|Western European Standard Time|WEST|Western European Summer Time=Atlantic/Canary Atlantic/Faeroe Atlantic/Faroe Atlantic/Madeira Europe/Lisbon Portugal
199
+ WET|Western European Time|WEST|Western European Summer Time=Africa/Casablanca Africa/El_Aaiun WET
200
+ WFT|Wallis & Futuna Time=Pacific/Wallis
201
+ WGT|West Greenland Standard Time|WGST|West Greenland Summer Time=America/Godthab America/Nuuk
202
+ WIB|Western Indonesia Time=Asia/Jakarta Asia/Pontianak
203
+ WIT|Eastern Indonesia Time=Asia/Jayapura
204
+ WITA|Central Indonesia Time=Asia/Makassar Asia/Ujung_Pandang
205
+ WSST|Apia Standard Time|WSDT|Apia Daylight Time=Pacific/Apia
206
+ XJT|Xinjiang Standard Time=Asia/Kashgar Asia/Urumqi
207
+ YAKT|Yakutsk Standard Time|YAKST|Yakutsk Summer Time=Asia/Chita Asia/Khandyga Asia/Yakutsk
208
+ YEKT|Yekaterinburg Standard Time|YEKST|Yekaterinburg Summer Time=Asia/Yekaterinburg
209
+ `,sx=`
210
+ Africa/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Africa/Nairobi Indian/Antananarivo Indian/Comoro Indian/Mayotte=-le7s00:-l4hs00
211
+ Africa/Casablanca=-fkuqo0:-cl6w40
212
+ Africa/Tunis=-fkt1k0:-f9hhc0 -f1kao0:-eqk5k0
213
+ Africa/Windhoek=ajtx40:cmzh40 ovois0:
214
+ America/Adak America/Atka America/Nome US/Aleutian=-ek1nw0:-cnomo0 6y2us0:77ss00
215
+ America/Anchorage US/Alaska=-ek1qo0:-cnopg0 6y2s00:77sp80
216
+ America/Anguilla America/Antigua America/Aruba America/Blanc-Sablon America/Curacao America/Dominica America/Grenada America/Guadeloupe America/Kralendijk America/Lower_Princes America/Marigot America/Montserrat America/Port_of_Spain America/Puerto_Rico America/St_Barthelemy America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Tortola America/Virgin=-efsnk0:-cnp640
217
+ America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Buenos_Aires America/Catamarca America/Cordoba America/Jujuy America/Mendoza America/Rosario=-eq30w0:-eba000 -e6yg00:-dse500 -doj680:-cfvuc0 -c4vgw0:-39hec0
218
+ America/Belize=-ecwso0:-cjqks0
219
+ America/Boise America/Cambridge_Bay America/Denver America/Edmonton America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Regina America/Shiprock America/Swift_Current America/Yellowknife Canada/Mountain Canada/Saskatchewan Navajo US/Mountain=-ek1z00:-cnoxs0
220
+ America/Chicago US/Central=-hnqf40:-haev80 -ek21s0:-cnp0k0
221
+ America/Coyhaique=-qs16wr:-qcwsw0 -c6kkw0:-bvifk0
222
+ America/Creston America/Phoenix US/Arizona=-ek1z00:-e3ctc0 -e0u2o0:-dkikmc
223
+ America/Dawson America/Whitehorse America/Yakutat Canada/Yukon=-ek1tg0:-cnos80
224
+ America/Dawson_Creek America/Fort_Nelson America/Los_Angeles America/Metlakatla America/Sitka US/Pacific=-ek1w80:-cnov00
225
+ America/Detroit America/New_York US/Eastern US/Michigan=-ek24k0:-cnp3c0
226
+ America/Ensenada America/Santa_Isabel America/Tijuana Mexico/BajaNorte=-oja5c0:-oik800 -eg90g0:-clbtw0
227
+ America/Fort_Wayne America/Indiana/Indianapolis America/Indiana/Marengo America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Kentucky/Monticello America/Menominee America/Rainy_River America/Winnipeg Canada/Central US/East-Indiana=-ek21s0:-cnp0k0
228
+ America/Glace_Bay America/Halifax America/Moncton Canada/Atlantic=-ek27c0:-cnp640
229
+ America/Goose_Bay America/St_Johns Canada/Newfoundland=-efdvm0:-cnp7i0
230
+ America/Indiana/Knox America/Knox_IN US/Indiana-Starke=-ek21s0:-cnp0k0 -3r1400:-3gy5c0
231
+ America/Indiana/Petersburg=-ek21s0:-cnp0k0 -26hxc0:-1wrxc0
232
+ America/Iqaluit America/Pangnirtung=-eb6ao0:-cnp3c0
233
+ America/Juneau=-ek1w80:-cnov00 5dweg0:5n9fs0
234
+ America/Kentucky/Louisville America/Louisville=-ek21s0:-cnp0k0 -4iy1s0:-4emkk0
235
+ America/Montevideo=-etxya0:-e482c0
236
+ America/Montreal America/Nassau America/Nipigon America/Thunder_Bay America/Toronto Canada/Eastern=-fhlj80:-cnp3c0
237
+ America/Punta_Arenas=-qs16wr:-qcwsw0 -c6kkw0:-bvifk0 ohmt80:ohn4c0
238
+ America/Santiago Chile/Continental=-qs16wr:-qcwsw0 -c6kno0:-bvifk0
239
+ America/Vancouver Canada/Pacific=-ek1w80:-cnov00 tntfo0:
240
+ Antarctica/McMurdo Antarctica/South_Pole NZ Pacific/Auckland=-f9pme0:-ciy9c0
241
+ Antarctica/Palmer=-2lxhc0:-2ivzo0
242
+ Arctic/Longyearbyen Atlantic/Jan_Mayen Europe/Berlin Europe/Bratislava Europe/Copenhagen Europe/Oslo Europe/Prague Europe/Stockholm Europe/Vienna=-fizzw0:-e6dzw0
243
+ Asia/Aqtau=64qao0:6e2vc0 b34ac0:bcheg0
244
+ Asia/Aqtobe Asia/Qyzylorda=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 b34ac0:bcheg0
245
+ Asia/Ashgabat Asia/Ashkhabad Asia/Yekaterinburg=b34ac0:bcheg0
246
+ Asia/Atyrau=64qao0:6e2vc0 b34ac0:bcheg0 f99uc0:fkfrs0 hv9940:i6f3s0
247
+ Asia/Barnaul=b344s0:bch8w0 d98v40:dfdjk0
248
+ Asia/Bishkek=b347k0:bazjk0 idzae0:il2ko0
249
+ Asia/Calcutta Asia/Karachi Asia/Kolkata=-e9lba0:-cmya20
250
+ Asia/Chongqing Asia/Chungking Asia/Harbin Asia/Shanghai PRC=-ekjy80:-cp63o0
251
+ Asia/Colombo=-elvwm0:-cmw9u0
252
+ Asia/Dacca Asia/Dhaka=-eqtpow:-ef78q0
253
+ Asia/Dushanbe=b347k0:bbgac0
254
+ Asia/Famagusta=ofoio0:onyo00
255
+ Asia/Gaza Asia/Hebron Asia/Jerusalem Asia/Tel_Aviv Israel=-f765c0:-epbk00 -envpc0:-e6fxc0
256
+ Asia/Ho_Chi_Minh Asia/Saigon=-cxyro0:-cp63o0
257
+ Asia/Hong_Kong Hongkong=-eqtn80:-emgia0
258
+ Asia/Istanbul Europe/Istanbul Turkey=-ehgdk0:-cnaz00 -3wa5k0:-3r1400 -3czk00:-3805o0
259
+ Asia/Jakarta Asia/Pontianak=-asj1c0:-art400
260
+ Asia/Kuala_Lumpur Asia/Singapore Singapore=-jb6gs0:-hquppc
261
+ Asia/Manila=-emx4w0:-ejxt00 -cyj500:-ckjfo0
262
+ Asia/Oral=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 a1b6c0:aaoag0 bi8t40:blud00 hv9940:i6f3s0
263
+ Asia/Qostanay=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 b34ac0:bcheg0 hv96c0:i6f100
264
+ Asia/Samarkand=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0
265
+ Asia/Tomsk=b344s0:bch8w0 gvea40:h4lu80
266
+ Atlantic/Azores=-1yevk0:-1p1u80
267
+ Atlantic/Cape_Verde=-e9kqg0:-cmxp80
268
+ Atlantic/Madeira=-1yeyc0:-1p1x00
269
+ CET Europe/Amsterdam Europe/Brussels Europe/Luxembourg MET=-fkul40:-e6dzw0
270
+ EET Europe/Athens=-eyqoc0:-e6dzw0
271
+ Europe/Astrakhan=a1b940:aaod80 bcc000:blufs0
272
+ Europe/Belgrade Europe/Ljubljana Europe/Podgorica Europe/Sarajevo Europe/Skopje Europe/Zagreb=-ezayw0:-epbk00 -efyio0:-e6dzw0
273
+ Europe/Budapest=-ezvc80:-epbk00 -egog00:-e6dzw0
274
+ Europe/Chisinau Europe/Tiraspol=-euq8c0:-e6dzw0 -dfqqk0:-d8e5k0
275
+ Europe/Gibraltar=-fkul40:-eyiyk0 -ethh80:-eh8qk0 -earek0:-dyinw0 -drod80:-dfsl80 -d75h80:-cx0nw0 -cro2k0:-cncfs0
276
+ Europe/Guernsey Europe/Isle_of_Man Europe/Jersey=-fkul40:-eyiyk0 -ethh80:-eh8qk0 -earek0:-dyinw0 -drod80:-dfsl80 -d75h80:-cx0nw0 -cro2k0:-cncfs0 -z4ns0:-m6840
277
+ Europe/Kaliningrad=-fizzw0:-e6dzw0 -cx0nw0:-cwm2w0
278
+ Europe/Kiev Europe/Kyiv Europe/Uzhgorod Europe/Zaporozhye=-erdv00:-e6dzw0
279
+ Europe/Kirov=a1b940:aaod80 bcc000:blufs0 bmeyo0:bv7jw0
280
+ Europe/Lisbon Portugal WET=-1yf140:-1p1zs0
281
+ Europe/Madrid=-gki5g0:-gj2dk0 -gb3c80:-gaxmo0 -g17mo0:-fs2000
282
+ Europe/Malta Europe/Rome Europe/San_Marino Europe/Vatican=-ff59g0:-e6dzw0
283
+ Europe/Minsk=-evpf00:-e6dzw0 -dfqqk0:-db2g80
284
+ Europe/Monaco Europe/Paris=-fkul40:-e6dzw0 -d62qs0:-cx0nw0
285
+ Europe/Riga=-fciw80:-e6dzw0
286
+ Europe/Saratov=9il6g0:9ryak0 bcc000:blufs0
287
+ Europe/Simferopol=-ep8300:-e6dzw0 -dfqqk0:-df8g80
288
+ Europe/Tallinn=-fakdc0:-eta5c0 -ern4c0:-e6dzw0 -dfqqk0:-d6wg80
289
+ Europe/Tirane=-ff3es0:-e6dzw0
290
+ Europe/Ulyanovsk=a1b940:aaod80 b34fw0:bchk00
291
+ Europe/Vilnius=-ptj1g0:-poyaw0 -fcmis0:-e6dzw0 -dfqqk0:-d9kqw0
292
+ Europe/Warsaw Poland=-qznjw0:-qrqd80 -feqak0:-e6dzw0
293
+ Pacific/Guam Pacific/Saipan=-5hlkw0:-56itc0 -4y8o00:-4nnvo0 -17w8w0:-10d9c0 -ohhc0:-hih6c
294
+ Pacific/Honolulu Pacific/Johnston US/Hawaii=-ek1pa0:-cnoo20
295
+ `,sb="str.format_time",sv=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],sw=["January","February","March","April","May","June","July","August","September","October","November","December"],sS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],sE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],sN=["GMT","Greenwich Mean Time"],sT=["UTC","Coordinated Universal Time"],sk=/^(?:GMT|UT)([+-])(?:(\d{1,2})(?::?(\d{2}))?|(\d{2}):(\d{2}):(\d{2})|(\d{2})(\d{2})(\d{2}))$/,sA=(e,t)=>String(e).padStart(t,"0"),sI=(e,t)=>(e%t+t)%t,sC=(e,t)=>e<0?"-"+sA(-e,t):sA(e,t),sM=e=>(e<0?"-":"")+sA(Math.abs(e)%100,2),sP=e=>new ei(`Invalid \`format\` value for the ${sb}() function: \`${e}\`.`,sb),sD=new Map,sR=null;function sO(e){if("Z"===e)return{fixedMs:0,names:sT};let t=e.startsWith("UTC")?"GMT"+e.slice(3):e;if("GMT"===t||"UT"===t)return{fixedMs:0,names:sN};let i=function(e){if(!sR)for(let e of(sR=new Map,sg.split(`
296
+ `))){let t=e.indexOf("=");if(t<0)continue;let i=e.slice(0,t).split("|");for(let r of e.slice(t+1).split(" "))sR.set(r,i)}return sR.get(e)}(t);if(i)return{id:t,names:i};let r=sk.exec(t);if(!r)return null;let n=Number(r[2]??r[4]??r[7]),s=Number(r[3]??r[5]??r[8]??0),a=Number(r[6]??r[9]??0),o=3600*n+60*s+a;if(s>59||a>59||o>64800)return null;if(0===o)return{fixedMs:0,names:sN};let l=`GMT${r[1]}${sA(n,2)}:${sA(s,2)}${a?":"+sA(a,2):""}`;return{fixedMs:("-"===r[1]?-1:1)*o*1e3,names:[l,l]}}let sj=null,sV=new Map,s$=new Map,sL=new Map,sB=new Map,sF=new Map,sq={EST5EDT:-5,CST6CDT:-6,MST7MDT:-7,PST8PDT:-8},sz=Date.UTC(1967,0,1),sU=[[1918,3,31,1918,10,27],[1919,3,30,1919,10,26],[1942,2,9,1945,9,30]];function sW(e,t){return sU.some(([i,r,n,s,a,o])=>t>=Date.UTC(i,r-1,n,2)-36e5*e&&t<Date.UTC(s,a-1,o,2)-(e+1)*36e5)}function sK(e,t){let i=Math.max(t,-22089888e5),r=sV.get(e);r||(r=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),sV.set(e,r));let n={};for(let e of r.formatToParts(i))"literal"!==e.type&&(n[e.type]=Number(e.value));return 864e5*sY(n.year,n.month,n.day)+n.hour%24*36e5+6e4*n.minute+1e3*n.second-(i-sI(i,1e3))}function sG(e,t,i){let r=e.get(i);return void 0===r&&(r=sK(t,6048e5*i),e.set(i,r)),r}function sH(e,t){if(t<-22089888e5)return!1;let i=sq[e];return void 0!==i&&t<sz?sW(i,t):function(e,t){if(t<-22089888e5)return!1;let i=s$.get(e);i||(i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"long"}),s$.set(e,i));let r=i.formatToParts(t).find(e=>"timeZoneName"===e.type)?.value??"";if(/Daylight|Summer/.test(r)||"Irish Standard Time"===r)return!0;if(!/^GMT([+-]|$)/.test(r))return!1;let[n,s]=function(e,t){let i=sB.get(e);i||sB.set(e,i=new Map);let r=i.get(t);if(!r){let n=sL.get(e);n||sL.set(e,n=new Map);let s=1/0,a=1/0;for(let i=1;i<=53;i++)s=Math.min(s,sG(n,e,t-i)),a=Math.min(a,sG(n,e,t+i));i.set(t,r=[s,a])}return r}(e,Math.floor(t/6048e5)),a=sK(e,t);return a>n&&a>s}(e,t)!==function(e,t){if(!sj)for(let e of(sj=new Map,sx.split(`
297
+ `))){let t=e.indexOf("=");if(t<0)continue;let i=e.slice(t+1).split(" ").flatMap(e=>e.split(":").map(e=>e?parseInt(e,36):1/0));for(let r of e.slice(0,t).split(" "))sj.set(r,i)}let i=sj.get(e);if(!i)return!1;let r=Math.floor(t/1e3),n=0,s=i.length/2;for(;n<s;){let e=n+s>>1;i[2*e+1]<=r?n=e+1:s=e}return n<i.length/2&&i[2*n]<=r}(e,t)}function sY(e,t,i){let r=Math.floor((e-=t<=2)/400),n=e-400*r;return 146097*r+365*n+Math.floor(n/4)-Math.floor(n/100)+(Math.floor((153*(t+(t>2?-3:9))+2)/5)+i-1)-719468}function sZ(e,t,i){let r=sY(e,t,i);return r>=-141427?r:function(e,t,i){let r=Math.floor((14-t)/12),n=e+4800-r;return i+Math.floor((153*(t+12*r-3)+2)/5)+365*n+Math.floor(n/4)-32083-2440588}(e,t,i)}function sJ(e,t,i){let r=function(e){let t=sD.get(e);if(t)return t;let i=[],r="",n=!1;for(let t=0;t<e.length;){let s=e[t];if("'"===s){"'"===e[t+1]?(r+="'",t+=2):(n=!n,t++);continue}if(!n&&(s>="a"&&s<="z"||s>="A"&&s<="Z")){let n=1;for(;e[t+n]===s;)n++;if(!"GyMdkHmsSEDFwWahKzZYuXL".includes(s)||"X"===s&&n>3)throw sP(e);r&&i.push(r),r="",i.push({letter:s,count:n}),t+=n;continue}r+=s,t++}if(n)throw sP(e);return r&&i.push(r),sD.size>=256&&sD.clear(),sD.set(e,i),i}(t),n=sO(i);if(!n)throw new ei(`Incorrect \`timezone\` value for the ${sb}() function: "${i}". The value must be a string in either UTC/GMT notation (e.g. "UTC-5", "GMT+0530") or an IANA time zone database name (e.g. "America/New_York").`,sb);let s=Math.floor(e),a=n.fixedMs??0,o=n.id;if(o)try{a=function(e,t){let i=sq[e];if(void 0!==i&&t>=-22089888e5&&t<sz)return(i+ +!!sW(i,t))*36e5;if(t>=-22089888e5)return sK(e,t);let r=sF.get(e);if(void 0===r){let t=1/0,i=1/0;for(let r=0;r<53;r++){let n=21143808e5+6048e5*r,s=sK(e,n);i=Math.min(i,s),sH(e,n)||(t=Math.min(t,s))}r=t!==1/0?t:i-36e5,sF.set(e,r)}return r}(o,s)}catch{o=void 0}let l=s+a,h=Math.floor(l/864e5),c=l-864e5*h,[p,u,d]=h>=-141427?function(e){let t=e+719468,i=Math.floor(t/146097),r=t-146097*i,n=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),s=r-(365*n+Math.floor(n/4)-Math.floor(n/100)),a=Math.floor((5*s+2)/153),o=s-Math.floor((153*a+2)/5)+1,l=a<10?a+3:a-9;return[n+400*i+ +(l<=2),l,o]}(h):function(e){let t=e+2440588+32082,i=Math.floor((4*t+3)/1461),r=t-Math.floor(1461*i/4),n=Math.floor((5*r+2)/153);return[i-4800+Math.floor(n/10),n+3-12*Math.floor(n/10),r-Math.floor((153*n+2)/5)+1]}(h),m=sI(h+4,7),f=Math.floor(c/36e5),y="";for(let e of r){if("string"==typeof e){y+=e;continue}let{letter:t,count:i}=e;switch(t){case"G":y+=p>0?"AD":"BC";break;case"y":{let e=p>0?p:1-p;y+=2===i?sM(e):sC(e,i);break}case"Y":case"w":{let e=sZ(p,1,1),r=h+(6-m)>=sZ(p+1,1,1);"w"===t?y+=sC(r?1:Math.floor((h-e+sI(e+4,7))/7)+1,i):y+=2===i?sM(r?p+1:p):sC(r?p+1:p,i);break}case"M":case"L":y+=i>=4?sw[u-1]:3===i?sv[u-1]:sC(u,i);break;case"W":{let e=h-(d-1);y+=sC(Math.floor((d-1+sI(e+4,7))/7)+1,i);break}case"D":y+=sC(h-sZ(p,1,1)+1,i);break;case"d":y+=sC(d,i);break;case"F":y+=sC(Math.floor((d-1)/7)+1,i);break;case"E":y+=i>=4?sE[m]:sS[m];break;case"u":y+=sC(0===m?7:m,i);break;case"a":y+=f<12?"AM":"PM";break;case"H":y+=sC(f,i);break;case"k":y+=sC(0===f?24:f,i);break;case"K":y+=sC(f%12,i);break;case"h":y+=sC(f%12==0?12:f%12,i);break;case"m":y+=sC(Math.floor(c/6e4)%60,i);break;case"s":y+=sC(Math.floor(c/1e3)%60,i);break;case"S":y+=sC(c%1e3,i);break;case"z":{let e=void 0!==o&&n.names.length>2&&sH(o,s);y+=n.names[2*!!e+ +(i>=4)];break}case"Z":case"X":{let e=Math.trunc(a/6e4);if("X"===t&&0===e){y+="Z";break}let r=e<0?"-":"+",n=sA(Math.floor(Math.abs(e)/60),2),s=sA(Math.abs(e)%60,2);y+=r+n+("Z"===t||2===i?s:3===i?":"+s:"")}}}return y}let sQ=["time","format","timezone"],sX={"":"#,##0.###",integer:"#,##0",percent:"#,##0%",currency:"$#,##0.00"},s0=e=>null==e||"number"==typeof e&&Number.isNaN(e),s1=e=>s0(e)?"":String(e),s2=/^[+-]?(?:\d+\.?\d*|\.\d+)$/;class s3{constructor(e){this.context=e}param(e,t=0,i){return m.from(e).get(t)}tostring(e,t){if("number"!=typeof e)return"string"==typeof e?e:String(e);if(!t)return ex(e);if("mintick"===t){let t=Math.max(0,-Math.floor(Math.log10(this.context.pine?.syminfo?.mintick||.01)));return eg(e,t?"0."+"0".repeat(t):"0","halfUp")}return"percent"===t?eg(e,"0.00","halfUp")+"%":"volume"===t?function(e){if(!Number.isFinite(e))return String(e);let t=Math.abs(e),i=eb.find(([e])=>t>=e),r=eg(i?t/i[0]:t,i?"#.###":"#","halfUp");return(e<0&&"0"!==r?"-":"")+r+(i?i[1]:"")}(e):eg(e,t,"halfUp")}tonumber(e){let t=s1(e).replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"");return s2.test(t)?Number(t):NaN}lower(e){return s1(e).toLowerCase()}upper(e){return s1(e).toUpperCase()}trim(e){return s1(e).trim()}repeat(e,t,i=""){return ej(("number"==typeof t&&t>0?Math.floor(t):0)*(s1(e).length+s1(i).length),"str.repeat"),Array(t).fill(s1(e)).join(s1(i))}replace_all(e,t,i){return s1(e).replaceAll(s1(t),s1(i))}replace(e,t,i,r=0){let n=s1(e),s=s1(t),a=s1(i),o=Math.floor(Number(r))||0;if(""===s)return n;let l=0,h=0;for(;;){let e=n.indexOf(s,l);if(-1===e)return n;if(h===o)return n.substring(0,e)+a+n.substring(e+s.length);h++,l=e+s.length}}contains(e,t){return s1(e).includes(s1(t))}endswith(e,t){return s1(e).endsWith(s1(t))}startswith(e,t){return s1(e).startsWith(s1(t))}pos(e,t){let i=s1(e).indexOf(s1(t));return -1===i?NaN:i}length(e){return s1(e).length}match(e,t){let i=s1(e).match(new RegExp(s1(t)));return i?i[0]:""}split(e,t){return new eO(s1(e).split(s1(t)),eR.string,this.context)}substring(e,t,i){return s1(e).substring(t,i)}format_time(...e){let{time:t,format:i,timezone:r}=function(e,t){let i={};for(let r in e.forEach((e,r)=>{let n;null!==(n=e)&&"object"==typeof n&&Object.getPrototypeOf(n)===Object.prototype?Object.assign(i,e):r<t.length&&(i[t[r]]=e)}),i)i[r]instanceof m&&(i[r]=i[r].get(0));return i}(e,sQ),n=s0(t)?0:Number(t),s=void 0===i?"yyyy-MM-dd'T'HH:mm:ssZ":s1(i);if(void 0!==r)return sJ(n,s,s1(r));let a=this.context.pine?.syminfo?.timezone;return sJ(n,s,a&&sO(a)?a:"UTC")}format(e,...t){let i=s1(e),r="",n=!1,s=0;for(;s<i.length;){let e=i[s];if("'"===e){"'"===i[s+1]?(r+="'",s+=2):(n=!n,s++);continue}if("{"!==e||n){r+=e,s++;continue}let a=["","",""],o=0,l=0,h=!1,c=s+1;for(;c<i.length;c++){let e=i[c];if(h)a[o]+=e,"'"===e&&(h=!1);else if(","===e&&o<2)o++;else if("{"===e)l++,a[o]+=e;else if("}"===e){if(0===l)break;l--,a[o]+=e}else" "===e?(1!==o||a[1].length>0)&&(a[o]+=e):("'"===e&&(h=!0),a[o]+=e)}if(c>=i.length)throw Error("Unmatched braces in the pattern.");r+=this._formatArgument(a,i.slice(s,c+1),t),s=c+1}return r}_formatArgument([e,t,i],r,n){if(!/^[+-]?\d+$/.test(e))throw Error(`can't parse argument number: ${e}`);let s=Number(e);if(s<0)throw Error(`negative argument number: ${e}`);let a=t.trim().toLowerCase();if(""!==a&&"number"!==a){if("date"===a||"time"===a||"choice"===a)return r;throw Error(`unknown format type: ${t}`)}if(s>=n.length||void 0===n[s])return`{${s}}`;let o=n[s];return""===a||"number"!=typeof o?"number"==typeof o?Number.isNaN(o)?"NaN":eg(o,sX[""],"halfEven"):o instanceof eO?"["+eS(o).join(", ")+"]":String(o):Number.isNaN(o)?"NaN":eg(o,sX[i.trim().toLowerCase()]??i,"halfEven")}}var s4=Object.defineProperty;let s6=e=>"function"==typeof e?e():e instanceof m?e.get(0):e;class s5{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?s4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_chart")}param(e,t=0,i){return m.from(e).get(t)}get chart(){return void 0===this._chart&&(this._chart=te(this.context.timeframe)),this._chart}resolve(e,t,i){let r=s6(e);if(null==r||""===r||"number"==typeof r&&isNaN(r))return this.chart??{unit:"D",multiplier:1};let n=te(r);if(!n)throw new ei(i(String(r)),t);return n}get periodString(){let e=this.chart;return e?tt(e,this.context.pineVersion>=6):this.context.timeframe}get main_period(){return this.periodString}get period(){return this.periodString}get multiplier(){return this.chart?.multiplier??1}get isdwm(){let e=this.chart?.unit;return"D"===e||"W"===e||"M"===e}get isdaily(){return this.chart?.unit==="D"}get isweekly(){return this.chart?.unit==="W"}get ismonthly(){return this.chart?.unit==="M"}get isticks(){return!1}get isseconds(){return this.chart?.unit==="S"}get isminutes(){return this.chart?.unit===""}get isintraday(){return!this.isdwm}change(e){let t=this.resolve(e,"timeframe.change",e=>`Cannot parse resolution '${e}'. - Invalid format`),i=m.from(this.context.data.openTime).get(0),r=m.from(this.context.data.openTime).get(1);if(isNaN(i)||isNaN(r))return!1;let n=this.context.pine?.syminfo,s=n?.timezone||"UTC";return ty(i,t,s,n?.session)!==ty(r,t,s,n?.session)}from_seconds(e){let t=s6(e);return null==t||isNaN(t)?NaN:t>=31536e3?"12M":t<=30?`${[1,5,10,15,30].find(e=>t<=e)}S`:t<86400?String(Math.ceil(t/60)):t%604800==0?`${t/604800}W`:t%2628003==0?`${t/2628003}M`:`${Math.ceil(t/86400)}D`}in_seconds(e){return tr(this.resolve(e,"timeframe.in_seconds",e=>`Invalid value of the 'period' argument ('${e}') in the 'timeframe.in_seconds()' function.`))}}var s9=Object.defineProperty,s8=Object.getOwnPropertyDescriptor,s7=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?s8(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&s9(t,i,s),s};let ae=["series","title","color","linewidth","style","trackprice","histbase","offset","join","editable","show_last","display","format","precision","force_overlay","linestyle"],at=["series","title","char","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],ai={series:"series",title:"string",char:"string",location:"string",color:"color",offset:"number",text:"string",textcolor:"color",editable:"boolean",size:"string",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},ar=["series","title","style","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],an=["series","title","colorup","colordown","offset","minheight","maxheight","editable","show_last","display","format","precision","force_overlay"],as=["open","high","low","close","title","color","editable","show_last","display","format","precision","force_overlay"],aa=["open","high","low","close","title","color","wickcolor","editable","show_last","bordercolor","display","format","precision","force_overlay"],ao=["color","offset","editable","show_last","title","display","force_overlay"],al=["price","title","color","linestyle","linewidth","editable","display"],ah=["plot1","plot2","color","title","editable","show_last","fillgaps","display"],ac=["plot1","plot2","color","title","editable","fillgaps","display"],ap=["plot1","plot2","top_value","bottom_value","top_color","bottom_color","title","display","fillgaps","editable"],au={plot1:"object",plot2:"object",top_value:"number",bottom_value:"number",top_color:"color",bottom_color:"color",title:"string",display:"string",fillgaps:"boolean",editable:"boolean"},ad=["top_value","bottom_value","top_color","bottom_color"],am={series:"series",title:"string",color:"color",linewidth:"number",style:"string",trackprice:"boolean",histbase:"number",offset:"number",join:"boolean",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean",linestyle:"string"},af={series:"series",title:"string",style:"string",location:"string",color:"color",offset:"number",text:"string",textcolor:"color",editable:"boolean",size:"string",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},ay={series:"series",title:"string",colorup:"color",colordown:"color",offset:"number",minheight:"number",maxheight:"number",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},a_={open:"series",high:"series",low:"series",close:"series",title:"string",color:"color",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},ag={open:"series",high:"series",low:"series",close:"series",title:"string",color:"color",wickcolor:"color",bordercolor:"color",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},ax={color:"color",offset:"number",editable:"boolean",show_last:"number",title:"string",display:"string",force_overlay:"boolean"},ab={price:"series",title:"string",color:"color",linestyle:"string",linewidth:"number",editable:"boolean",display:"string"},av={plot1:"object",plot2:"object",color:"color",title:"string",editable:"boolean",show_last:"number",fillgaps:"boolean",display:"string"};class aw{constructor(e){this.context=e}_resolvePlotKey(e,t){if(e){let i=this.context.plots[e];return i&&t&&i._callsiteId!==t?e+t:e}return t||"plot"}extractPlotOptions(e){let t={};for(let i in e)t[i]=m.from(e[i]).get(0);return t}get linestyle_dashed(){return"linestyle_dashed"}get linestyle_dotted(){return"linestyle_dotted"}get linestyle_solid(){return"linestyle_solid"}get style_area(){return"style_area"}get style_areabr(){return"style_areabr"}get style_circles(){return"style_circles"}get style_columns(){return"style_columns"}get style_cross(){return"style_cross"}get style_histogram(){return"style_histogram"}get style_line(){return"style_line"}get style_linebr(){return"style_linebr"}get style_stepline(){return"style_stepline"}get style_stepline_diamond(){return"style_stepline_diamond"}get style_steplinebr(){return"style_steplinebr"}param(e,t=0,i){return m.from(e).get(t)}plotchar(...e){let t=e6(e),{series:i,title:r,...n}=e5(e,at,ai),s=this.extractPlotOptions(n),a=this._resolvePlotKey(r,t);this.context.plots[a]||(this.context.plots[a]={data:[],options:{...s,style:"char"},title:r,_plotKey:a,_callsiteId:t});let o=m.from(i).get(0);return this.context.plots[a].data.push({title:r,time:this.context.marketData[this.context.idx].openTime,value:o,options:{char:s.char,color:s.color,textcolor:s.textcolor,location:s.location,size:s.size,offset:s.offset}}),this.context.plots[a]}any(...e){let t=e6(e),{series:i,title:r,...n}=e5(e,ae,am),s=this.extractPlotOptions(n),a=this._resolvePlotKey(r,t),o="color"in n;if(!this.context.plots[a]){let e=s.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[a]={data:[],options:{...s,overlay:e},title:r,_plotKey:a,_callsiteId:t}}let l=m.from(i).get(0),h=s.color;"function"==typeof h&&(h=h());let c={color:o?"string"==typeof h?h:void 0:h||"#2962ff"};return"offset"in n&&(c.offset=s.offset),this.context.plots[a].data.push({title:r,time:this.context.marketData[this.context.idx].openTime,value:l,options:c}),this.context.plots[a]}plotshape(...e){let t=e6(e),{series:i,title:r,...n}=e5(e,ar,af),s=this.extractPlotOptions(n),a=this._resolvePlotKey(r,t);if(!this.context.plots[a]){let e=s.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[a]={data:[],options:{...s,style:"shape",shape:s.style,overlay:e},title:r,_plotKey:a,_callsiteId:t}}let o=m.from(i).get(0);return this.context.plots[a].data.push({title:r,time:this.context.marketData[this.context.idx].openTime,value:o,options:s?.location==="absolute"||o?{text:s.text,textcolor:s.textcolor,color:s.color,offset:s.offset,shape:s.style,location:s.location,size:s.size}:void 0}),this.context.plots[a]}plotarrow(...e){let t=e6(e),{series:i,title:r,...n}=e5(e,an,ay),s=m.from(i).get(0),a=this.extractPlotOptions(n),o=this._resolvePlotKey(r,t);if(!this.context.plots[o]){let e=a.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[o]={data:[],options:{...a,style:"shape",overlay:e},title:r,_plotKey:o,_callsiteId:t}}return this.context.plots[o].data.push({title:r,time:this.context.marketData[this.context.idx].openTime,value:s,options:"number"!=typeof s||isNaN(s)||0===s?void 0:{text:void 0,textcolor:void 0,color:s>0?a.colorup:a.colordown,offset:a.offset,shape:s>0?"shape_arrow_up":"shape_arrow_down",location:s>0?"BelowBar":"AboveBar",height:a.maxheight}}),this.context.plots[o]}plotbar(...e){let t=e6(e),{open:i,high:r,low:n,close:s,title:a,...o}=e5(e,as,a_),l=this.extractPlotOptions(o),h=this._resolvePlotKey(a,t);if(!this.context.plots[h]){let e=l.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[h]={data:[],options:{...l,style:"bar",overlay:e},title:a,_plotKey:h,_callsiteId:t}}let c=[m.from(i).get(0),m.from(r).get(0),m.from(n).get(0),m.from(s).get(0)];this.context.plots[h].data.push({title:a,time:this.context.marketData[this.context.idx].openTime,value:c,options:{color:l.color}})}plotcandle(...e){let t=e6(e),{open:i,high:r,low:n,close:s,title:a,...o}=e5(e,aa,ag),l=this.extractPlotOptions(o),h=this._resolvePlotKey(a,t);if(!this.context.plots[h]){let e=l.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[h]={data:[],options:{...l,style:"candle",overlay:e},title:a,_plotKey:h,_callsiteId:t}}let c=[m.from(i).get(0),m.from(r).get(0),m.from(n).get(0),m.from(s).get(0)];return this.context.plots[h].data.push({title:a,time:this.context.marketData[this.context.idx].openTime,value:c,options:{color:l.color,wickcolor:l.wickcolor,bordercolor:l.bordercolor}}),this.context.plots[h]}bgcolor(...e){let t=e6(e),{title:i,...r}=e5(e,ao,ax),n=this.extractPlotOptions(r),s=this._resolvePlotKey(i,t);if(!this.context.plots[s]){let e=n.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[s]={data:[],options:{...n,style:"background",overlay:e},title:i,_plotKey:s,_callsiteId:t}}this.context.plots[s].data.push({title:i,time:this.context.marketData[this.context.idx].openTime,value:n.color&&"na"!==n.color&&n?.color.toString()!=="NaN",options:{color:n.color}})}barcolor(...e){let t=e6(e),{title:i,...r}=e5(e,ao,ax),n=this.extractPlotOptions(r),s=this._resolvePlotKey(i,t);return this.context.plots[s]||(this.context.plots[s]={data:[],options:{...n,style:"barcolor"},title:i,_plotKey:s,_callsiteId:t}),this.context.plots[s].data.push({title:i,time:this.context.marketData[this.context.idx].openTime,value:n.color&&"na"!==n.color&&n?.color.toString()!=="NaN",options:{color:n.color}}),this.context.plots[s]}}s7([tM],aw.prototype,"plotchar",1),s7([tM],aw.prototype,"any",1),s7([tM],aw.prototype,"plotshape",1),s7([tM],aw.prototype,"plotarrow",1),s7([tM],aw.prototype,"plotbar",1),s7([tM],aw.prototype,"plotcandle",1),s7([tM],aw.prototype,"bgcolor",1),s7([tM],aw.prototype,"barcolor",1);class aS{constructor(e){this.context=e}get style_dashed(){return"dashed"}get style_solid(){return"solid"}get style_dotted(){return"dotted"}param(e,t=0,i){return m.from(e).get(t)}any(...e){let t=e6(e),{price:i,title:r,color:n,linestyle:s,linewidth:a,editable:o,display:l}=e5(e,al,ab),h=[i,{title:r,color:n,linestyle:s,linewidth:a,editable:o,display:l,style:"hline"}];return t&&h.push({__callsiteId:t}),this.context.pine.plot.any(...h)}}s7([tM],aS.prototype,"any",1);class aE{constructor(e){this.context=e}param(e,t=0,i){return m.from(e).get(t)}any(...e){let t=e6(e),i=e.length>0&&e4(e[e.length-1])?e[e.length-1]:null,r=i?e.length-1:e.length;if(i&&("hline1"in i||"hline2"in i)){let{hline1:t,hline2:r,...n}=i;i={...n,...void 0!==t&&{plot1:t},...void 0!==r&&{plot2:r}},e=[...e.slice(0,-1),i]}if(null!==i&&ad.some(e=>e in i)||r>=4&&"number"==typeof e[2]&&"number"==typeof e[3]){let i=e5(e,ap,au),{plot1:r,plot2:n,editable:s,fillgaps:a,display:o}=i,l=m.from(i.top_value).get(0),h=m.from(i.bottom_value).get(0),c=m.from(i.top_color).get(0),p=m.from(i.bottom_color).get(0),u="string"==typeof i.title&&i.title?i.title:void 0,d=r?._plotKey||r?.title,f=n?._plotKey||n?.title,y=u||"fill",_=this.context.plots[y];_&&t&&_._callsiteId!==t&&(y=t),this.context.plots[y]||(this.context.plots[y]={title:u||"Fill",plot1:d,plot2:f,data:[],options:{plot1:d,plot2:f,editable:s,fillgaps:a,display:o,style:"fill",gradient:!0},_plotKey:y,_callsiteId:t}),this.context.plots[y].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{top_value:l,bottom_value:h,top_color:c,bottom_color:p}})}else{let r=m.from(i&&"plot1"in i?i.plot1:e[0]).get(0)?.options?.style==="hline"?ac:ah,{plot1:n,plot2:s,color:a,title:o,editable:l,show_last:h,fillgaps:c,display:p}=e5(e,r,av),u=o||"fill",d=this.context.plots[u];d&&t&&d._callsiteId!==t&&(u=t);let f=m.from(a).get(0);if(!this.context.plots[u]){let e=n?._plotKey||n?.title,i=s?._plotKey||s?.title;this.context.plots[u]={title:o||"Fill",plot1:e,plot2:i,data:[],options:{plot1:e,plot2:i,color:f,editable:l,show_last:h,fillgaps:c,display:p,style:"fill"},_plotKey:u,_callsiteId:t}}this.context.plots[u].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{color:f}})}}}s7([tM],aE.prototype,"any",1);var aN=Object.defineProperty;class aT{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?aN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"point");let t=this.context,i=e=>null==e?e:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e;this.point={new:(e,t,r)=>new e0(i(e),i(t),i(r)??NaN),from_index:(e,t)=>new e0(void 0,i(e),i(t)),from_time:(e,t)=>new e0(i(e),void 0,i(t)),copy:e=>e.copy(),now(e){let r=t.idx;return new e0(t.marketData[r]?.openTime,r,i(e))}}}param(e,t=0,i){return m.from(e).get(t)}bg_color(){return"#1e293b"}fg_color(){return"#d1d4dc"}is_standard(){let e=this.context?.chartStyle;return null==e||"standard"===e}is_heikinashi(){return this.context?.chartStyle==="heikinashi"}is_kagi(){return!1}is_linebreak(){return!1}is_pnf(){return!1}is_range(){return!1}is_renko(){return!1}}var ak=Object.defineProperty,aA=(e,t,i)=>((e,t,i)=>t in e?ak(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let aI=0;class aC{constructor(e,t,i="",r="bi",n="pr",s="",a="style_label_down",o="",l="normal",h="center",c="",p="default",u=!1,d="none"){aA(this,"id"),aA(this,"x"),aA(this,"y"),aA(this,"text"),aA(this,"xloc"),aA(this,"yloc"),aA(this,"color"),aA(this,"style"),aA(this,"textcolor"),aA(this,"size"),aA(this,"textalign"),aA(this,"tooltip"),aA(this,"text_font_family"),aA(this,"force_overlay"),aA(this,"text_formatting"),aA(this,"_deleted"),aA(this,"_helper"),aA(this,"_createdAtBar",-1),this.id=aI++,this.x=e,this.y=t,this.text=i,this.xloc=r,this.yloc=n,this.color=s,this.style=a,this.textcolor=o,this.size=l,this.textalign=h,this.tooltip=c,this.text_font_family=p,this.force_overlay=u,this.text_formatting=d,this._deleted=!1,this._helper=null}set_x(e){this._helper?this._helper.set_x(this,e):this._deleted||(this.x=e)}set_y(e){this._helper?this._helper.set_y(this,e):this._deleted||(this.y=e)}set_xy(e,t){this._helper?this._helper.set_xy(this,e,t):this._deleted||(this.x=e,this.y=t)}set_text(e){this._helper?this._helper.set_text(this,e):this._deleted||(this.text=e)}set_color(e){this._helper?this._helper.set_color(this,e):this._deleted||(this.color=e)}set_textcolor(e){this._helper?this._helper.set_textcolor(this,e):this._deleted||(this.textcolor=e)}set_size(e){this._helper?this._helper.set_size(this,e):this._deleted||(this.size=e)}set_style(e){this._helper?this._helper.set_style(this,e):this._deleted||(this.style=e)}set_textalign(e){this._helper?this._helper.set_textalign(this,e):this._deleted||(this.textalign=e)}set_tooltip(e){this._helper?this._helper.set_tooltip(this,e):this._deleted||(this.tooltip=e)}set_xloc(e,t){this._helper?this._helper.set_xloc(this,e,t):this._deleted||(this.x=e,this.xloc=t)}set_yloc(e){this._helper?this._helper.set_yloc(this,e):this._deleted||(this.yloc=e)}set_point(e){this._helper&&this._helper.set_point(this,e)}set_text_font_family(e){this._helper?this._helper.set_text_font_family(this,e):this._deleted||(this.text_font_family=e)}set_text_formatting(e){this._helper?this._helper.set_text_formatting(this,e):this._deleted||(this.text_formatting=e)}get_x(){return this._deleted?NaN:this.x}get_y(){return this._deleted?NaN:this.y}get_text(){return this._deleted?"":this.text}delete(){this._deleted=!0}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new aC(this.x,this.y,this.text,this.xloc,this.yloc,this.color,this.style,this.textcolor,this.size,this.textalign,this.tooltip,this.text_font_family,this.force_overlay,this.text_formatting)}toPlotData(){return{id:this.id,x:this.x,y:this.y,text:this.text,xloc:this.xloc,yloc:this.yloc,color:this.color,style:this.style,textcolor:this.textcolor,size:this.size,textalign:this.textalign,tooltip:this.tooltip,text_font_family:this.text_font_family,force_overlay:this.force_overlay,text_formatting:this.text_formatting,_deleted:this._deleted}}}let aM=e=>null!=e&&!("number"==typeof e&&isNaN(e));function aP(e,t){return"bt"===t?{x:aM(e.time)?e.time:NaN,xloc:t}:"bi"===t?{x:aM(e.index)?e.index:NaN,xloc:t}:aM(e.index)?{x:e.index,xloc:"bi"}:aM(e.time)?{x:e.time,xloc:"bt"}:{x:0,xloc:"bi"}}var aD=Object.defineProperty,aR=Object.getOwnPropertyDescriptor,aO=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?aR(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&aD(t,i,s),s};let aj=[["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay","text_formatting"],["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay","text_formatting"]],aV={x:"number",y:"number",text:"string",xloc:"string",yloc:"string",color:"color",style:"string",textcolor:"color",size:"size",textalign:"string",tooltip:"string",text_font_family:"string",force_overlay:"boolean",point:"point",text_formatting:"string"};class a${constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?aD(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_labels",[])}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__labels__||(this.context.plots.__labels__={title:"__labels__",data:[],options:{style:"label",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._labels=this._labels.filter(e=>!e._deleted);let t=this._labels.map(e=>e.toPlotData()),i=t.filter(e=>!e.force_overlay),r=t.filter(e=>e.force_overlay);this.context.plots.__labels__.data=[{time:e,value:i,options:{style:"label"}}],r.length>0?this.context.plots.__labels_overlay__={title:"__labels_overlay__",data:[{time:e,value:r,options:{style:"label"}}],options:{style:"label",overlay:!0}}:delete this.context.plots.__labels_overlay__}_resolve(e){if(null==e)return e;if(e instanceof tq)return null;if("object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get){let t=e.get(0);return"number"==typeof t&&isNaN(t)?null:t}return"function"==typeof e?e():"number"==typeof e&&isNaN(e)?null:e}_createLabel(e,t,i="",r="bi",n="pr",s="",a="style_label_down",o="",l="normal",h="center",c="",p="default",u=!1,d="none"){let m=new aC(e,t,this._resolve(i),this._resolve(r),this._resolve(n),this._resolve(s),this._resolve(a),this._resolve(o),this._resolve(l),this._resolve(h),this._resolve(c),this._resolve(p),u,this._resolve(d)||"none");return m._helper=this,m._createdAtBar=this.context.idx,this._labels.push(m),this._enforceMaxCount(),m}_enforceMaxCount(){let e=this.context.indicator?.max_labels_count??50,t=this._labels.filter(e=>!e._deleted);if(t.length>e){let i=t.length-e,r=0;for(let e of this._labels){if(r>=i)break;e._deleted||(e._deleted=!0,r++)}}}new(...e){let t=e5(e,aj,aV),i,r,n=t.xloc;if(t.point instanceof e0){let e=t.point,s=aP(e,n);i=s.x,n=n||s.xloc,r=e.price}else i=this._resolve(t.x),r=this._resolve(t.y);return this._createLabel(i,r,t.text,n,t.yloc,t.color,t.style,t.textcolor,t.size,t.textalign,t.tooltip,t.text_font_family,t.force_overlay,t.text_formatting)}any(...e){if(1===e.length){let t=e[0];if(null==t||t instanceof tq||"number"==typeof t&&isNaN(t))return null;if(t instanceof aC)return t;if(t instanceof m){let e=t.get(0);if(null==e||"number"==typeof e&&isNaN(e))return null;if(e instanceof aC)return e}return null}return this.new(...e)}set_x(e,t){e&&!e._deleted&&(e.x=t)}set_y(e,t){e&&!e._deleted&&(e.y=t)}set_xy(e,t,i){e&&!e._deleted&&(e.x=t,e.y=i)}set_text(e,t){e&&!e._deleted&&(e.text=t)}set_color(e,t){e&&!e._deleted&&(e.color=t)}set_textcolor(e,t){e&&!e._deleted&&(e.textcolor=t)}set_size(e,t){e&&!e._deleted&&(e.size=t)}set_style(e,t){e&&!e._deleted&&(e.style=t)}set_textalign(e,t){e&&!e._deleted&&(e.textalign=t)}set_tooltip(e,t){e&&!e._deleted&&(e.tooltip=t)}set_text_font_family(e,t){e&&!e._deleted&&(e.text_font_family=this._resolve(t))}set_text_formatting(e,t){e&&!e._deleted&&(e.text_formatting=this._resolve(t))}set_xloc(e,t,i){e&&!e._deleted&&(e.x=this._resolve(t),e.xloc=this._resolve(i))}set_yloc(e,t){e&&!e._deleted&&(e.yloc=t)}set_point(e,t){e&&!e._deleted&&t&&(e.x=aP(t,e.xloc).x,e.y=t.price)}get_x(e){return e&&!e._deleted?e.x:NaN}get_y(e){return e&&!e._deleted?e.y:NaN}get_text(e){return e&&!e._deleted?e.text:""}copy(e){if(!e)return;let t=e._clone();return t._helper=this,t._createdAtBar=this.context.idx,this._labels.push(t),this._enforceMaxCount(),t}delete(e){e&&(e._deleted=!0)}get all(){return this._labels.filter(e=>!e._deleted)}rollbackFromBar(e){this._labels=this._labels.filter(t=>t._createdAtBar<e),this.syncToPlot()}get style_label_down(){return"style_label_down"}get style_label_up(){return"style_label_up"}get style_label_left(){return"style_label_left"}get style_label_right(){return"style_label_right"}get style_label_lower_left(){return"style_label_lower_left"}get style_label_lower_right(){return"style_label_lower_right"}get style_label_upper_left(){return"style_label_upper_left"}get style_label_upper_right(){return"style_label_upper_right"}get style_label_center(){return"style_label_center"}get style_circle(){return"style_circle"}get style_square(){return"style_square"}get style_diamond(){return"style_diamond"}get style_flag(){return"style_flag"}get style_arrowup(){return"style_arrowup"}get style_arrowdown(){return"style_arrowdown"}get style_cross(){return"style_cross"}get style_xcross(){return"style_xcross"}get style_triangleup(){return"style_triangleup"}get style_triangledown(){return"style_triangledown"}get style_none(){return"style_none"}get style_text_outline(){return"style_text_outline"}}aO([tM],a$.prototype,"new",1),aO([tM],a$.prototype,"set_x",1),aO([tM],a$.prototype,"set_y",1),aO([tM],a$.prototype,"set_xy",1),aO([tM],a$.prototype,"set_text",1),aO([tM],a$.prototype,"set_color",1),aO([tM],a$.prototype,"set_textcolor",1),aO([tM],a$.prototype,"set_size",1),aO([tM],a$.prototype,"set_style",1),aO([tM],a$.prototype,"set_textalign",1),aO([tM],a$.prototype,"set_tooltip",1),aO([tM],a$.prototype,"set_text_font_family",1),aO([tM],a$.prototype,"set_text_formatting",1),aO([tM],a$.prototype,"set_xloc",1),aO([tM],a$.prototype,"set_yloc",1),aO([tM],a$.prototype,"set_point",1),aO([tM],a$.prototype,"copy",1),aO([tM],a$.prototype,"delete",1);var aL=Object.defineProperty,aB=(e,t,i)=>((e,t,i)=>t in e?aL(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let aF=0;class aq{constructor(e,t,i,r,n="bi",s="none",a="",o="style_solid",l=1,h=!1){aB(this,"id"),aB(this,"x1"),aB(this,"y1"),aB(this,"x2"),aB(this,"y2"),aB(this,"xloc"),aB(this,"extend"),aB(this,"color"),aB(this,"style"),aB(this,"width"),aB(this,"force_overlay"),aB(this,"_deleted"),aB(this,"_helper"),aB(this,"_createdAtBar",-1),this.id=aF++,this.x1=e,this.y1=t,this.x2=i,this.y2=r,this.xloc=n,this.extend=s,this.color=a,this.style=o,this.width=l,this.force_overlay=h,this._deleted=!1,this._helper=null}set_x1(e){this._helper?this._helper.set_x1(this,e):this._deleted||(this.x1=e)}set_y1(e){this._helper?this._helper.set_y1(this,e):this._deleted||(this.y1=e)}set_x2(e){this._helper?this._helper.set_x2(this,e):this._deleted||(this.x2=e)}set_y2(e){this._helper?this._helper.set_y2(this,e):this._deleted||(this.y2=e)}set_xy1(e,t){this._helper?this._helper.set_xy1(this,e,t):this._deleted||(this.x1=e,this.y1=t)}set_xy2(e,t){this._helper?this._helper.set_xy2(this,e,t):this._deleted||(this.x2=e,this.y2=t)}set_color(e){this._helper?this._helper.set_color(this,e):this._deleted||(this.color=e)}set_width(e){this._helper?this._helper.set_width(this,e):this._deleted||(this.width=e)}set_style(e){this._helper?this._helper.set_style(this,e):this._deleted||(this.style=e)}set_extend(e){this._helper?this._helper.set_extend(this,e):this._deleted||(this.extend=e)}set_xloc(e,t,i){this._helper?this._helper.set_xloc(this,e,t,i):this._deleted||(this.x1=e,this.x2=t,this.xloc=i)}set_first_point(e){this._helper&&this._helper.set_first_point(this,e)}set_second_point(e){this._helper&&this._helper.set_second_point(this,e)}get_x1(){return this._deleted?NaN:this.x1}get_y1(){return this._deleted?NaN:this.y1}get_x2(){return this._deleted?NaN:this.x2}get_y2(){return this._deleted?NaN:this.y2}get_price(e){return this._helper?this._helper.get_price(this,e):NaN}delete(){this._helper?this._helper.delete(this):this._deleted=!0}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new aq(this.x1,this.y1,this.x2,this.y2,this.xloc,this.extend,this.color,this.style,this.width,this.force_overlay)}toPlotData(){return{id:this.id,x1:this.x1,y1:this.y1,x2:this.x2,y2:this.y2,xloc:this.xloc,extend:this.extend,color:this.color,style:this.style,width:this.width,force_overlay:this.force_overlay,_deleted:this._deleted}}}var az=Object.defineProperty,aU=Object.getOwnPropertyDescriptor,aW=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?aU(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&az(t,i,s),s},aK=(e,t,i)=>((e,t,i)=>t in e?az(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let aG=[["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"],["first_point","second_point","xloc","extend","color","style","width","force_overlay"]],aH={x1:"number",y1:"number",x2:"number",y2:"number",xloc:"string",extend:"string",color:"color",style:"string",width:"number",force_overlay:"boolean",first_point:"point",second_point:"point"};class aY{constructor(e){this.context=e,aK(this,"_lines",[]),aK(this,"linefills",null)}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__lines__||(this.context.plots.__lines__={title:"__lines__",data:[],options:{style:"drawing_line",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._lines=this._lines.filter(e=>!e._deleted);let t=this._lines.map(e=>e.toPlotData()),i=t.filter(e=>!e.force_overlay),r=t.filter(e=>e.force_overlay);this.context.plots.__lines__.data=[{time:e,value:i,options:{style:"drawing_line"}}],r.length>0?this.context.plots.__lines_overlay__={title:"__lines_overlay__",data:[{time:e,value:r,options:{style:"drawing_line"}}],options:{style:"drawing_line",overlay:!0}}:delete this.context.plots.__lines_overlay__}_resolvePoint(e,t){return aP(e,t)}_resolve(e){return null==e?e:e instanceof tq?NaN:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e}_resolveColor(e){let t=this._resolve(e);return null==t?t:"number"==typeof t&&isNaN(t)?NaN:t}_createLine(e,t,i,r,n="bi",s="none",a="",o="style_solid",l=1,h=!1){let c=new aq(e,t,i,r,n,this._resolve(s),this._resolveColor(a),this._resolve(o),this._resolve(l)||1,h);return c._helper=this,c._createdAtBar=this.context.idx,this._lines.push(c),this._enforceMaxCount(),c}_enforceMaxCount(){let e=this.context.indicator?.max_lines_count??50,t=this._lines.filter(e=>!e._deleted);if(t.length>e){let i=t.length-e,r=0;for(let e of this._lines){if(r>=i)break;e._deleted||(e._deleted=!0,r++)}}}new(...e){let t=e5(e,aG,aH),i,r,n,s,a=t.xloc;if(t.first_point instanceof e0){let e=t.first_point,o=t.second_point,l=this._resolvePoint(e,a);i=l.x,r=e.price,a=a||l.xloc,o instanceof e0?(n=this._resolvePoint(o,a).x,s=o.price):(n=0,s=NaN)}else i=this._resolve(t.x1),r=this._resolve(t.y1),n=this._resolve(t.x2),s=this._resolve(t.y2);return this._createLine(i,r,n,s,a,t.extend,t.color,t.style,t.width,t.force_overlay)}any(...e){if(1===e.length){let t=e[0];if(null==t||t instanceof tq||"number"==typeof t&&isNaN(t))return null;if(t instanceof aq)return t;if(t instanceof m){let e=t.get(0);if(null==e||"number"==typeof e&&isNaN(e))return null;if(e instanceof aq)return e}return null}return this.new(...e)}set_x1(e,t){e&&!e._deleted&&(e.x1=this._resolve(t))}set_y1(e,t){e&&!e._deleted&&(e.y1=this._resolve(t))}set_x2(e,t){e&&!e._deleted&&(e.x2=this._resolve(t))}set_y2(e,t){e&&!e._deleted&&(e.y2=this._resolve(t))}set_xy1(e,t,i){e&&!e._deleted&&(e.x1=this._resolve(t),e.y1=this._resolve(i))}set_xy2(e,t,i){e&&!e._deleted&&(e.x2=this._resolve(t),e.y2=this._resolve(i))}set_color(e,t){e&&!e._deleted&&(e.color=this._resolveColor(t))}set_width(e,t){e&&!e._deleted&&(e.width=this._resolve(t)||1)}set_style(e,t){e&&!e._deleted&&(e.style=this._resolve(t))}set_extend(e,t){e&&!e._deleted&&(e.extend=this._resolve(t))}set_xloc(e,t,i,r){e&&!e._deleted&&(e.x1=t,e.x2=i,e.xloc=r)}set_first_point(e,t){e&&!e._deleted&&t&&(e.x1=this._resolvePoint(t,e.xloc).x,e.y1=t.price)}set_second_point(e,t){e&&!e._deleted&&t&&(e.x2=this._resolvePoint(t,e.xloc).x,e.y2=t.price)}get_x1(e){return e&&!e._deleted?e.x1:NaN}get_y1(e){return e&&!e._deleted?e.y1:NaN}get_x2(e){return e&&!e._deleted?e.x2:NaN}get_y2(e){return e&&!e._deleted?e.y2:NaN}get_price(e,t){if(!e||e._deleted||"bi"!==e.xloc)return NaN;let i=e.x2-e.x1;return 0===i?e.y1:e.y1+(t-e.x1)/i*(e.y2-e.y1)}copy(e){if(!e)return;let t=e._clone();return t._helper=this,t._createdAtBar=this.context.idx,this._lines.push(t),this._enforceMaxCount(),t}delete(e){e&&(e._deleted=!0,e instanceof aq&&this.linefills?.deleteForLine(e))}get all(){return this._lines.filter(e=>!e._deleted)}rollbackFromBar(e){this._lines=this._lines.filter(t=>t._createdAtBar<e),this.syncToPlot()}get style_solid(){return"style_solid"}get style_dotted(){return"style_dotted"}get style_dashed(){return"style_dashed"}get style_arrow_left(){return"style_arrow_left"}get style_arrow_right(){return"style_arrow_right"}get style_arrow_both(){return"style_arrow_both"}}aW([tM],aY.prototype,"new",1),aW([tM],aY.prototype,"set_x1",1),aW([tM],aY.prototype,"set_y1",1),aW([tM],aY.prototype,"set_x2",1),aW([tM],aY.prototype,"set_y2",1),aW([tM],aY.prototype,"set_xy1",1),aW([tM],aY.prototype,"set_xy2",1),aW([tM],aY.prototype,"set_color",1),aW([tM],aY.prototype,"set_width",1),aW([tM],aY.prototype,"set_style",1),aW([tM],aY.prototype,"set_extend",1),aW([tM],aY.prototype,"set_xloc",1),aW([tM],aY.prototype,"set_first_point",1),aW([tM],aY.prototype,"set_second_point",1),aW([tM],aY.prototype,"copy",1),aW([tM],aY.prototype,"delete",1);var aZ=Object.defineProperty,aJ=(e,t,i)=>((e,t,i)=>t in e?aZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let aQ=0;class aX{constructor(e,t,i,r,n="bi",s="none",a="#2962ff",o="style_solid",l=1,h="#2962ff",c="",p="#000000",u="auto",d="center",m="center",f="wrap_none",y="default",_="format_none",g=!1){aJ(this,"id"),aJ(this,"left"),aJ(this,"top"),aJ(this,"right"),aJ(this,"bottom"),aJ(this,"xloc"),aJ(this,"extend"),aJ(this,"border_color"),aJ(this,"border_style"),aJ(this,"border_width"),aJ(this,"bgcolor"),aJ(this,"text"),aJ(this,"text_color"),aJ(this,"text_size"),aJ(this,"text_halign"),aJ(this,"text_valign"),aJ(this,"text_wrap"),aJ(this,"text_font_family"),aJ(this,"text_formatting"),aJ(this,"force_overlay"),aJ(this,"_deleted"),aJ(this,"_helper"),aJ(this,"_createdAtBar",-1),this.id=aQ++,this.left=e,this.top=t,this.right=i,this.bottom=r,this.xloc=n,this.extend=s,this.border_color=a,this.border_style=o,this.border_width=l,this.bgcolor=h,this.text=c,this.text_color=p,this.text_size=u,this.text_halign=d,this.text_valign=m,this.text_wrap=f,this.text_font_family=y,this.text_formatting=_,this.force_overlay=g,this._deleted=!1,this._helper=null}set_left(e){this._helper?this._helper.set_left(this,e):this._deleted||(this.left=e)}set_right(e){this._helper?this._helper.set_right(this,e):this._deleted||(this.right=e)}set_top(e){this._helper?this._helper.set_top(this,e):this._deleted||(this.top=e)}set_bottom(e){this._helper?this._helper.set_bottom(this,e):this._deleted||(this.bottom=e)}set_lefttop(e,t){this._helper?this._helper.set_lefttop(this,e,t):this._deleted||(this.left=e,this.top=t)}set_rightbottom(e,t){this._helper?this._helper.set_rightbottom(this,e,t):this._deleted||(this.right=e,this.bottom=t)}set_top_left_point(e){this._helper&&this._helper.set_top_left_point(this,e)}set_bottom_right_point(e){this._helper&&this._helper.set_bottom_right_point(this,e)}set_xloc(e,t,i){this._helper?this._helper.set_xloc(this,e,t,i):this._deleted||(this.left=e,this.right=t,this.xloc=i)}set_bgcolor(e){this._helper?this._helper.set_bgcolor(this,e):this._deleted||(this.bgcolor=e)}set_border_color(e){this._helper?this._helper.set_border_color(this,e):this._deleted||(this.border_color=e)}set_border_width(e){this._helper?this._helper.set_border_width(this,e):this._deleted||(this.border_width=e)}set_border_style(e){this._helper?this._helper.set_border_style(this,e):this._deleted||(this.border_style=e)}set_extend(e){this._helper?this._helper.set_extend(this,e):this._deleted||(this.extend=e)}set_text(e){this._helper?this._helper.set_text(this,e):this._deleted||(this.text=e)}set_text_color(e){this._helper?this._helper.set_text_color(this,e):this._deleted||(this.text_color=e)}set_text_size(e){this._helper?this._helper.set_text_size(this,e):this._deleted||(this.text_size=e)}set_text_halign(e){this._helper?this._helper.set_text_halign(this,e):this._deleted||(this.text_halign=e)}set_text_valign(e){this._helper?this._helper.set_text_valign(this,e):this._deleted||(this.text_valign=e)}set_text_wrap(e){this._helper?this._helper.set_text_wrap(this,e):this._deleted||(this.text_wrap=e)}set_text_font_family(e){this._helper?this._helper.set_text_font_family(this,e):this._deleted||(this.text_font_family=e)}set_text_formatting(e){this._helper?this._helper.set_text_formatting(this,e):this._deleted||(this.text_formatting=e)}get_left(){return this._deleted?NaN:this.left}get_right(){return this._deleted?NaN:this.right}get_top(){return this._deleted?NaN:this.top}get_bottom(){return this._deleted?NaN:this.bottom}delete(){this._deleted=!0}toPlotData(){return{id:this.id,left:this.left,top:this.top,right:this.right,bottom:this.bottom,xloc:this.xloc,extend:this.extend,border_color:this.border_color,border_style:this.border_style,border_width:this.border_width,bgcolor:this.bgcolor,text:this.text,text_color:this.text_color,text_size:this.text_size,text_halign:this.text_halign,text_valign:this.text_valign,text_wrap:this.text_wrap,text_font_family:this.text_font_family,text_formatting:this.text_formatting,force_overlay:this.force_overlay,_deleted:this._deleted}}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new aX(this.left,this.top,this.right,this.bottom,this.xloc,this.extend,this.border_color,this.border_style,this.border_width,this.bgcolor,this.text,this.text_color,this.text_size,this.text_halign,this.text_valign,this.text_wrap,this.text_font_family,this.text_formatting,this.force_overlay)}}var a0=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,a2=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?a1(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&a0(t,i,s),s};let a3=[["left","top","right","bottom","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"],["top_left","bottom_right","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"]],a4={left:"number",top:"number",right:"number",bottom:"number",top_left:"point",bottom_right:"point",border_color:"color",border_width:"number",border_style:"string",extend:"string",xloc:"string",bgcolor:"color",text:"string",text_size:"size",text_color:"color",text_halign:"string",text_valign:"string",text_wrap:"string",text_font_family:"string",force_overlay:"boolean"};class a6{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?a0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_boxes",[])}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__boxes__||(this.context.plots.__boxes__={title:"__boxes__",data:[],options:{style:"drawing_box",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._boxes=this._boxes.filter(e=>!e._deleted);let t=this._boxes.map(e=>e.toPlotData()),i=t.filter(e=>!e.force_overlay),r=t.filter(e=>e.force_overlay);this.context.plots.__boxes__.data=[{time:e,value:i,options:{style:"drawing_box"}}],r.length>0?this.context.plots.__boxes_overlay__={title:"__boxes_overlay__",data:[{time:e,value:r,options:{style:"drawing_box"}}],options:{style:"drawing_box",overlay:!0}}:delete this.context.plots.__boxes_overlay__}_resolvePoint(e,t){return aP(e,t)}_resolve(e){return null==e?e:e instanceof tq?NaN:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e}_resolveColor(e,t){let i=this._resolve(e);return null==i?i:"number"==typeof i&&isNaN(i)?NaN:i||t}_createBox(e,t,i,r,n="bi",s="none",a="#2962ff",o="style_solid",l=1,h="#2962ff",c="",p="#000000",u="auto",d="center",m="center",f="wrap_none",y="default",_="format_none",g=!1){let x=new aX(e,t,i,r,n,this._resolve(s),this._resolveColor(a,"#2962ff"),this._resolve(o)||"style_solid",this._resolve(l)??1,this._resolveColor(h,"#2962ff"),this._resolve(c)||"",this._resolveColor(p,"#000000"),this._resolve(u)||"auto",this._resolve(d)||"center",this._resolve(m)||"center",this._resolve(f)||"wrap_none",this._resolve(y)||"default",this._resolve(_)||"format_none",g);return x._helper=this,x._createdAtBar=this.context.idx,this._boxes.push(x),this._enforceMaxCount(),x}_enforceMaxCount(){let e=this.context.indicator?.max_boxes_count??50,t=this._boxes.filter(e=>!e._deleted);if(t.length>e){let i=t.length-e,r=0;for(let e of this._boxes){if(r>=i)break;e._deleted||(e._deleted=!0,r++)}}}new(...e){let t=e5(e,a3,a4),i,r,n,s,a=t.xloc;if(t.top_left instanceof e0){let e=t.top_left,o=t.bottom_right,l=this._resolvePoint(e,a);i=l.x,r=e.price,a=a||l.xloc,o instanceof e0?(n=this._resolvePoint(o,a).x,s=o.price):(n=0,s=NaN)}else i=this._resolve(t.left),r=this._resolve(t.top),n=this._resolve(t.right),s=this._resolve(t.bottom);return this._createBox(i,r,n,s,a,t.extend,t.border_color,t.border_style,t.border_width,t.bgcolor,t.text,t.text_color,t.text_size,t.text_halign,t.text_valign,t.text_wrap,t.text_font_family,void 0,t.force_overlay)}any(...e){if(1===e.length){let t=e[0];if(null==t||t instanceof tq||"number"==typeof t&&isNaN(t))return null;if(t instanceof aX)return t;if(t instanceof m){let e=t.get(0);if(null==e||"number"==typeof e&&isNaN(e))return null;if(e instanceof aX)return e}return null}return this.new(...e)}set_left(e,t){e&&!e._deleted&&(e.left=this._resolve(t))}set_right(e,t){e&&!e._deleted&&(e.right=this._resolve(t))}set_top(e,t){e&&!e._deleted&&(e.top=this._resolve(t))}set_bottom(e,t){e&&!e._deleted&&(e.bottom=this._resolve(t))}set_lefttop(e,t,i){e&&!e._deleted&&(e.left=this._resolve(t),e.top=this._resolve(i))}set_rightbottom(e,t,i){e&&!e._deleted&&(e.right=this._resolve(t),e.bottom=this._resolve(i))}set_top_left_point(e,t){e&&!e._deleted&&t&&(e.left=this._resolvePoint(t,e.xloc).x,e.top=t.price)}set_bottom_right_point(e,t){e&&!e._deleted&&t&&(e.right=this._resolvePoint(t,e.xloc).x,e.bottom=t.price)}set_xloc(e,t,i,r){e&&!e._deleted&&(e.left=this._resolve(t),e.right=this._resolve(i),e.xloc=this._resolve(r))}set_bgcolor(e,t){e&&!e._deleted&&(e.bgcolor=this._resolve(t))}set_border_color(e,t){e&&!e._deleted&&(e.border_color=this._resolve(t))}set_border_width(e,t){e&&!e._deleted&&(e.border_width=this._resolve(t)??1)}set_border_style(e,t){e&&!e._deleted&&(e.border_style=this._resolve(t))}set_extend(e,t){e&&!e._deleted&&(e.extend=this._resolve(t))}set_text(e,t){e&&!e._deleted&&(e.text=this._resolve(t)||"")}set_text_color(e,t){e&&!e._deleted&&(e.text_color=this._resolve(t))}set_text_size(e,t){e&&!e._deleted&&(e.text_size=this._resolve(t))}set_text_halign(e,t){e&&!e._deleted&&(e.text_halign=this._resolve(t))}set_text_valign(e,t){e&&!e._deleted&&(e.text_valign=this._resolve(t))}set_text_wrap(e,t){e&&!e._deleted&&(e.text_wrap=this._resolve(t))}set_text_font_family(e,t){e&&!e._deleted&&(e.text_font_family=this._resolve(t))}set_text_formatting(e,t){e&&!e._deleted&&(e.text_formatting=this._resolve(t))}get_left(e){return e&&!e._deleted?e.left:NaN}get_right(e){return e&&!e._deleted?e.right:NaN}get_top(e){return e&&!e._deleted?e.top:NaN}get_bottom(e){return e&&!e._deleted?e.bottom:NaN}copy(e){if(!e)return;let t=e._clone();return t._helper=this,t._createdAtBar=this.context.idx,this._boxes.push(t),this._enforceMaxCount(),t}delete(e){e&&(e._deleted=!0)}get all(){return this._boxes.filter(e=>!e._deleted)}rollbackFromBar(e){this._boxes=this._boxes.filter(t=>t._createdAtBar<e),this.syncToPlot()}}a2([tM],a6.prototype,"new",1),a2([tM],a6.prototype,"set_left",1),a2([tM],a6.prototype,"set_right",1),a2([tM],a6.prototype,"set_top",1),a2([tM],a6.prototype,"set_bottom",1),a2([tM],a6.prototype,"set_lefttop",1),a2([tM],a6.prototype,"set_rightbottom",1),a2([tM],a6.prototype,"set_top_left_point",1),a2([tM],a6.prototype,"set_bottom_right_point",1),a2([tM],a6.prototype,"set_xloc",1),a2([tM],a6.prototype,"set_bgcolor",1),a2([tM],a6.prototype,"set_border_color",1),a2([tM],a6.prototype,"set_border_width",1),a2([tM],a6.prototype,"set_border_style",1),a2([tM],a6.prototype,"set_extend",1),a2([tM],a6.prototype,"set_text",1),a2([tM],a6.prototype,"set_text_color",1),a2([tM],a6.prototype,"set_text_size",1),a2([tM],a6.prototype,"set_text_halign",1),a2([tM],a6.prototype,"set_text_valign",1),a2([tM],a6.prototype,"set_text_wrap",1),a2([tM],a6.prototype,"set_text_font_family",1),a2([tM],a6.prototype,"set_text_formatting",1),a2([tM],a6.prototype,"copy",1),a2([tM],a6.prototype,"delete",1);var a5=Object.defineProperty,a9=(e,t,i)=>((e,t,i)=>t in e?a5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let a8=0;class a7{constructor(e,t,i){a9(this,"id"),a9(this,"line1"),a9(this,"line2"),a9(this,"color"),a9(this,"_deleted"),a9(this,"_createdAtBar",-1),this.id=a8++,this.line1=e,this.line2=t,this.color=i,this._deleted=!1}get_line1(){return this.line1}get_line2(){return this.line2}set_color(...e){let[t]=eN(e,["color"]);this._deleted||("function"==typeof t&&(t=t()),t&&"object"==typeof t&&Array.isArray(t.data)&&"function"==typeof t.get&&(t=t.get(0)),this.color=t||"")}delete(){this._deleted=!0}toPlotData(){let e=e=>e?{id:e.id,x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,xloc:e.xloc,extend:e.extend,color:e.color,style:e.style,width:e.width,_deleted:e._deleted}:null,t=!!(this.line1?.force_overlay||this.line2?.force_overlay);return{id:this.id,line1:e(this.line1),line2:e(this.line2),color:this.color,force_overlay:t,_deleted:this._deleted}}}var oe=Object.defineProperty,ot=Object.getOwnPropertyDescriptor,oi=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?ot(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&oe(t,i,s),s};class or{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_linefills",[])}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__linefills__||(this.context.plots.__linefills__={title:"__linefills__",data:[],options:{style:"linefill",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._linefills=this._linefills.filter(e=>!e._deleted);let t=this._linefills.map(e=>e.toPlotData()),i=t.filter(e=>!e.force_overlay),r=t.filter(e=>e.force_overlay);this.context.plots.__linefills__.data=[{time:e,value:i,options:{style:"linefill"}}],r.length>0?this.context.plots.__linefills_overlay__={title:"__linefills_overlay__",data:[{time:e,value:r,options:{style:"linefill"}}],options:{style:"linefill",overlay:!0}}:delete this.context.plots.__linefills_overlay__}_resolve(e){return null==e?e:e instanceof tq?NaN:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e}_resolveColor(e){let t=this._resolve(e);return null==t?t:"number"==typeof t&&isNaN(t)?NaN:t}new(e,t,i){let r=this._resolve(e),n=this._resolve(t);if(!(r instanceof aq)||!(n instanceof aq))return null;let s=i&&"object"==typeof i&&!Array.isArray(i)&&"color"in i?i.color:i,a=this._resolveColor(s);if(r&&n){let e=r.id,t=n.id;for(let i of this._linefills){if(i._deleted)continue;let r=i.line1?.id,n=i.line2?.id;if(r===e&&n===t||r===t&&n===e)return i.color=a,i._createdAtBar=this.context.idx,i}}let o=new a7(r,n,a);return o._createdAtBar=this.context.idx,this._linefills.push(o),this._enforceMaxCount(),o}_enforceMaxCount(){let e=this.context.indicator?.max_lines_count??50,t=this._linefills.filter(e=>!e._deleted).length-e;for(let e of this._linefills){if(t<=0)break;e._deleted||(e._deleted=!0,t--)}}any(...e){if(1===e.length){let t=e[0];return null==t||t instanceof tq||"number"==typeof t&&isNaN(t)?null:t instanceof a7?t:null}return this.new(e[0],e[1],e[2])}set_color(e,t){e&&!e._deleted&&(e.color=this._resolveColor(t))}get_line1(e){return e?e.line1:void 0}get_line2(e){return e?e.line2:void 0}delete(e){e&&(e._deleted=!0)}deleteForLine(e){for(let t of this._linefills)t._deleted||t.line1!==e&&t.line2!==e||(t._deleted=!0)}get all(){return this._linefills.filter(e=>!e._deleted)}rollbackFromBar(e){this._linefills=this._linefills.filter(t=>t._createdAtBar<e),this.syncToPlot()}}oi([tM],or.prototype,"new",1),oi([tM],or.prototype,"set_color",1),oi([tM],or.prototype,"delete",1);var on=Object.defineProperty,os=(e,t,i)=>((e,t,i)=>t in e?on(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let oa=0;class oo{constructor(e,t=!1,i=!1,r="bi",n="#2962ff",s="",a="style_solid",o=1,l=!1){os(this,"id"),os(this,"points"),os(this,"curved"),os(this,"closed"),os(this,"xloc"),os(this,"line_color"),os(this,"fill_color"),os(this,"line_style"),os(this,"line_width"),os(this,"force_overlay"),os(this,"_deleted"),os(this,"_createdAtBar",-1),this.id=oa++,this.points=e,this.curved=t,this.closed=i,this.xloc=r,this.line_color=n,this.fill_color=s,this.line_style=a,this.line_width=o,this.force_overlay=l,this._deleted=!1}delete(){this._deleted=!0}toPlotData(){return{id:this.id,points:this.points.map(e=>({time:e.time,index:e.index,price:e.price})),curved:this.curved,closed:this.closed,xloc:this.xloc,line_color:this.line_color,fill_color:this.fill_color,line_style:this.line_style,line_width:this.line_width,force_overlay:this.force_overlay,_deleted:this._deleted}}}var ol=Object.defineProperty,oh=Object.getOwnPropertyDescriptor,oc=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?oh(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&ol(t,i,s),s};class op{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?ol(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_polylines",[])}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__polylines__||(this.context.plots.__polylines__={title:"__polylines__",data:[],options:{style:"drawing_polyline",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._polylines=this._polylines.filter(e=>!e._deleted),this.context.plots.__polylines__.data=[{time:e,value:this._polylines.map(e=>e.toPlotData()),options:{style:"drawing_polyline"}}]}_resolve(e){return null==e?e:e instanceof tq?NaN:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e}_resolveColor(e,t){let i=this._resolve(e);return null==i?i:"number"==typeof i&&isNaN(i)?NaN:i||t}_extractPoints(e){let t=this._resolve(e),i=t&&t.array?t.array:t;return Array.isArray(i)?i.filter(e=>e instanceof e0):[]}new(...e){let t,i=!1,r=!1,n="bi",s="#2962ff",a="",o="style_solid",l=1,h=!1,c=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),p=e=>{c(e,"curved")&&(i=e.curved),c(e,"closed")&&(r=e.closed),c(e,"xloc")&&(n=e.xloc),c(e,"line_color")&&(s=e.line_color),c(e,"fill_color")&&(a=e.fill_color),c(e,"line_style")&&(o=e.line_style),c(e,"line_width")&&(l=e.line_width),c(e,"force_overlay")&&(h=e.force_overlay)},u=e.length>=1?e[e.length-1]:null,d=e.length>=2&&u&&"object"==typeof u&&!Array.isArray(u)&&!(u instanceof m)&&!(u instanceof e0);if(1===e.length&&u&&"object"==typeof u&&!Array.isArray(u)&&"points"in u)t=u.points,p(u);else{let c=d?e.slice(0,-1):e;t=c[0],c.length>1&&(i=c[1]),c.length>2&&(r=c[2]),c.length>3&&(n=c[3]),c.length>4&&(s=c[4]),c.length>5&&(a=c[5]),c.length>6&&(o=c[6]),c.length>7&&(l=c[7]),c.length>8&&(h=c[8]),d&&p(u)}let f=new oo(this._extractPoints(t),this._resolve(i)??!1,this._resolve(r)??!1,this._resolve(n)||"bi",this._resolveColor(s,"#2962ff"),this._resolveColor(a,""),this._resolve(o)||"style_solid",this._resolve(l)||1,this._resolve(h)??!1);return f._createdAtBar=this.context.idx,this._polylines.push(f),this._enforceMaxCount(),f}_enforceMaxCount(){let e=this.context.indicator?.max_polylines_count??50,t=this._polylines.filter(e=>!e._deleted);if(t.length>e){let i=t.length-e,r=0;for(let e of this._polylines){if(r>=i)break;e._deleted||(e._deleted=!0,r++)}}}any(...e){if(1===e.length){let t=e[0];if(null==t||t instanceof tq||"number"==typeof t&&isNaN(t))return null;if(t instanceof oo)return t;if(t instanceof m){let e=t.get(0);if(null==e||"number"==typeof e&&isNaN(e))return null;if(e instanceof oo)return e}return null}return this.new(...e)}delete(e){e&&(e._deleted=!0)}get all(){return this._polylines.filter(e=>!e._deleted)}rollbackFromBar(e){this._polylines=this._polylines.filter(t=>t._createdAtBar<e),this.syncToPlot()}}oc([tM],op.prototype,"new",1),oc([tM],op.prototype,"delete",1);var ou=Object.defineProperty,od=(e,t,i)=>((e,t,i)=>t in e?ou(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let om=0;function of(e){return Number.isFinite(e)?Math.trunc(e):NaN}class oy{constructor(e="top_right",t=1,i=1,r="",n="",s=0,a="",o=0,l=!1){od(this,"id"),od(this,"position"),od(this,"columns"),od(this,"rows"),od(this,"bgcolor"),od(this,"frame_color"),od(this,"frame_width"),od(this,"border_color"),od(this,"border_width"),od(this,"force_overlay"),od(this,"_deleted"),od(this,"cells"),od(this,"merges"),od(this,"_helper"),this.id=om++,this.position=e,this.columns=of(t),this.rows=of(i),this.bgcolor=r,this.frame_color=n,this.frame_width=s,this.border_color=a,this.border_width=o,this.force_overlay=l,this._deleted=!1,this.merges=[],ej((this.rows>0?this.rows:0)*(this.columns>0?this.columns:0),"table.new"),this.cells=[];for(let e=0;e<this.rows;e++){this.cells[e]=[];for(let t=0;t<this.columns;t++)this.cells[e][t]=null}}delete(){this._deleted=!0}toPlotData(){let e=this.cells.map(e=>e.map(e=>e?{...e}:null));return{id:this.id,position:this.position,columns:this.columns,rows:this.rows,bgcolor:this.bgcolor,frame_color:this.frame_color,frame_width:this.frame_width,border_color:this.border_color,border_width:this.border_width,force_overlay:this.force_overlay,_deleted:this._deleted,cells:e,merges:this.merges.map(e=>({...e}))}}setCell(e,t,i){if(e=of(e),!((t=of(t))>=0&&t<this.rows&&e>=0&&e<this.columns))return;let r=new Set;for(;;){let i=this.cells[t][e];if(!i?._merged||!i._merge_parent)break;r.add(t*this.columns+e);let[n,s]=i._merge_parent;if(!(s>=0&&s<this.rows&&n>=0&&n<this.columns)||r.has(s*this.columns+n)){i._merged=!1,i._merge_parent=null;break}e=n,t=s}let n=this.cells[t][e]||this._defaultCell();Object.assign(n,i),this.cells[t][e]=n}markMerged(e,t,i,r){if(!(t>=0&&t<this.rows&&e>=0&&e<this.columns))return;let n=this.cells[t][e]||this._defaultCell();n._merged=!0,n._merge_parent=[i,r],this.cells[t][e]=n}getCell(e,t){return e=of(e),(t=of(t))>=0&&t<this.rows&&e>=0&&e<this.columns?this.cells[t][e]:null}clearCell(e,t){e=of(e),(t=of(t))>=0&&t<this.rows&&e>=0&&e<this.columns&&(this.cells[t][e]=null)}_setHelper(e){this._helper=e}cell(...e){return this._helper.cell(this,...e)}clear(...e){return this._helper.clear(this,...e)}merge_cells(...e){return this._helper.merge_cells(this,...e)}cell_set_text(...e){return this._helper.cell_set_text(this,...e)}cell_set_bgcolor(...e){return this._helper.cell_set_bgcolor(this,...e)}cell_set_text_color(...e){return this._helper.cell_set_text_color(this,...e)}cell_set_text_size(...e){return this._helper.cell_set_text_size(this,...e)}cell_set_height(...e){return this._helper.cell_set_height(this,...e)}cell_set_width(...e){return this._helper.cell_set_width(this,...e)}cell_set_tooltip(...e){return this._helper.cell_set_tooltip(this,...e)}cell_set_text_halign(...e){return this._helper.cell_set_text_halign(this,...e)}cell_set_text_valign(...e){return this._helper.cell_set_text_valign(this,...e)}cell_set_text_font_family(...e){return this._helper.cell_set_text_font_family(this,...e)}cell_set_text_formatting(...e){return this._helper.cell_set_text_formatting(this,...e)}set_position(...e){return this._helper.set_position(this,...e)}set_bgcolor(...e){return this._helper.set_bgcolor(this,...e)}set_border_color(...e){return this._helper.set_border_color(this,...e)}set_border_width(...e){return this._helper.set_border_width(this,...e)}set_frame_color(...e){return this._helper.set_frame_color(this,...e)}set_frame_width(...e){return this._helper.set_frame_width(this,...e)}_defaultCell(){return{text:"",width:0,height:0,text_color:"#000000",text_halign:"center",text_valign:"center",text_size:"normal",bgcolor:"",tooltip:"",text_font_family:"default",text_formatting:"none",_merged:!1,_merge_parent:null}}}var o_=Object.defineProperty,og=Object.getOwnPropertyDescriptor,ox=(e,t,i,r)=>{for(var n,s=r>1?void 0:r?og(t,i):t,a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r?n(t,i,s):n(s))||s);return r&&s&&o_(t,i,s),s};let ob=["position","columns","rows","bgcolor","frame_color","frame_width","border_color","border_width","force_overlay"],ov=["table_id","column","row","text","width","height","text_color","text_halign","text_valign","text_size","bgcolor","tooltip","text_font_family","text_formatting"],ow=["table_id","start_column","start_row","end_column","end_row"];class oS{constructor(e){this.context=e,((e,t,i)=>((e,t,i)=>t in e?o_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_tables",[])}param(e,t=0,i){return m.from(e).get(t)}_ensurePlotsEntry(){this.context.plots.__tables__||(this.context.plots.__tables__={title:"__tables__",data:[],options:{style:"table",overlay:!0}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._tables=this._tables.filter(e=>!e._deleted),this.context.plots.__tables__.data=[{time:e,value:this._tables.map(e=>e.toPlotData()),options:{style:"table"}}]}_resolve(e){return null==e?e:"object"==typeof e&&"__value"in e?e.__value:"object"==typeof e&&Array.isArray(e.data)&&"function"==typeof e.get?e.get(0):"function"==typeof e?e():e}new(...e){let t="top_right",i=1,r=1,n="",s="",a=0,o="",l=0,h=!1;t=(e=eN(e,ob))[0]??t,i=e[1]??i,r=e[2]??r,n=e[3]??n,s=e[4]??s,a=e[5]??a,o=e[6]??o,l=e[7]??l,h=e[8]??h;let c=new oy(this._resolve(t)||"top_right",this._resolve(i)||1,this._resolve(r)||1,this._resolve(n)||"",this._resolve(s)||"",this._resolve(a)||0,this._resolve(o)||"",this._resolve(l)||0,this._resolve(h)??!1);return c._setHelper(this),this._takePosition(c),this._tables.push(c),c}_takePosition(e){for(let t of this._tables)t===e||t._deleted||t.position!==e.position||(t._deleted=!0)}any(...e){if(1===e.length){let t=e[0];return null==t||"object"==typeof t&&"__value"in t||"number"==typeof t&&isNaN(t)?null:t instanceof oy?t:null}return this.new(...e)}cell(...e){let t,i,r,n="",s=0,a=0,o="#000000",l="center",h="center",c="normal",p="",u="",d="default",m="none";t=(e=eN(e,ov))[0],i=e[1]??0,r=e[2]??0,n=e[3]??n,s=e[4]??s,a=e[5]??a,o=e[6]??o,l=e[7]??l,h=e[8]??h,c=e[9]??c,p=e[10]??p,u=e[11]??u,d=e[12]??d,m=e[13]??m;let f=this._resolve(t);if(!f||f._deleted)return;let y=this._resolve(i)??0,_=this._resolve(r)??0;f.setCell(y,_,{text:this._resolveText(this._resolve(n)),width:this._resolve(s)||0,height:this._resolve(a)||0,text_color:this._resolve(o)||"#000000",text_halign:this._resolve(l)||"center",text_valign:this._resolve(h)||"center",text_size:this._resolve(c)||"normal",bgcolor:this._resolve(p)||"",tooltip:this._resolveText(this._resolve(u)),text_font_family:this._resolve(d)||"default",text_formatting:this._resolve(m)||"none"})}delete(e){e&&(e._deleted=!0)}clear(...e){let t,i,r,n,s;t=(e=eN(e,ow))[0],i=e[1]??0,r=e[2]??0,n=e[3]??i,s=e[4]??r;let a=this._resolve(t);if(!a||a._deleted)return;let o=of(this._resolve(i)??0),l=of(this._resolve(r)??0),h=of(this._resolve(n)??o),c=of(this._resolve(s)??l);for(let e=l;e<=c;e++)for(let t=o;t<=h;t++)a.clearCell(t,e)}merge_cells(...e){let t,i,r,n,s;t=(e=eN(e,ow))[0],i=e[1]??0,r=e[2]??0,n=e[3]??0,s=e[4]??0;let a=this._resolve(t);if(!a||a._deleted)return;let o=of(this._resolve(i)??0),l=of(this._resolve(r)??0),h=of(this._resolve(n)??0),c=of(this._resolve(s)??0);if(!(isNaN(o)||isNaN(l)||isNaN(h)||isNaN(c))){for(let e=l;e<=c;e++)for(let t=o;t<=h;t++)e===l&&t===o||a.markMerged(t,e,o,l);a.merges.push({startCol:o,startRow:l,endCol:h,endRow:c})}}cell_set_text(e,t,i,r){this._setCellProp(e,t,i,"text",r,!0)}cell_set_bgcolor(e,t,i,r){this._setCellProp(e,t,i,"bgcolor",r)}cell_set_text_color(e,t,i,r){this._setCellProp(e,t,i,"text_color",r)}cell_set_text_size(e,t,i,r){this._setCellProp(e,t,i,"text_size",r)}cell_set_height(e,t,i,r){this._setCellProp(e,t,i,"height",r)}cell_set_width(e,t,i,r){this._setCellProp(e,t,i,"width",r)}cell_set_tooltip(e,t,i,r){this._setCellProp(e,t,i,"tooltip",r,!0)}cell_set_text_halign(e,t,i,r){this._setCellProp(e,t,i,"text_halign",r)}cell_set_text_valign(e,t,i,r){this._setCellProp(e,t,i,"text_valign",r)}cell_set_text_font_family(e,t,i,r){this._setCellProp(e,t,i,"text_font_family",r)}cell_set_text_formatting(e,t,i,r){this._setCellProp(e,t,i,"text_formatting",r)}set_position(e,t){let i=this._resolve(e);!i||i._deleted||(i.position=this._resolve(t)||i.position,this._takePosition(i))}set_bgcolor(e,t){let i=this._resolve(e);!i||i._deleted||(i.bgcolor=this._resolve(t)||"")}set_border_color(e,t){let i=this._resolve(e);!i||i._deleted||(i.border_color=this._resolve(t)||"")}set_border_width(e,t){let i=this._resolve(e);!i||i._deleted||(i.border_width=this._resolve(t)||0)}set_frame_color(e,t){let i=this._resolve(e);!i||i._deleted||(i.frame_color=this._resolve(t)||"")}set_frame_width(e,t){let i=this._resolve(e);!i||i._deleted||(i.frame_width=this._resolve(t)||0)}get all(){return this._tables.filter(e=>!e._deleted)}rollbackFromBar(e){this.syncToPlot()}_setCellProp(e,t,i,r,n,s=!1){let a=this._resolve(e);if(!a||a._deleted)return;let o=this._resolve(t)??0,l=this._resolve(i)??0,h=this._resolve(n);a.setCell(o,l,{[r]:s?this._resolveText(h):h})}_resolveText(e){return null==e||e!=e?"":String(e)}}function oE(e,t){let i=iF(e);if(i instanceof iK)return i;throw new ei(`The \`footprint\` ID used in the \`${t}()\` call cannot be \`na\`.`,`footprint.${t}`)}ox([tM],oS.prototype,"new",1),ox([tM],oS.prototype,"cell",1),ox([tM],oS.prototype,"delete",1),ox([tM],oS.prototype,"clear",1),ox([tM],oS.prototype,"merge_cells",1),ox([tM],oS.prototype,"cell_set_text",1),ox([tM],oS.prototype,"cell_set_bgcolor",1),ox([tM],oS.prototype,"cell_set_text_color",1),ox([tM],oS.prototype,"cell_set_text_size",1),ox([tM],oS.prototype,"cell_set_height",1),ox([tM],oS.prototype,"cell_set_width",1),ox([tM],oS.prototype,"cell_set_tooltip",1),ox([tM],oS.prototype,"cell_set_text_halign",1),ox([tM],oS.prototype,"cell_set_text_valign",1),ox([tM],oS.prototype,"cell_set_text_font_family",1),ox([tM],oS.prototype,"cell_set_text_formatting",1),ox([tM],oS.prototype,"set_position",1),ox([tM],oS.prototype,"set_bgcolor",1),ox([tM],oS.prototype,"set_border_color",1),ox([tM],oS.prototype,"set_border_width",1),ox([tM],oS.prototype,"set_frame_color",1),ox([tM],oS.prototype,"set_frame_width",1);class oN{constructor(e){this.context=e}param(e,t=0,i){return m.from(e).get(t)}any(){throw new ei("Could not find function or function reference 'footprint'","footprint")}buy_volume(e){return oE(e,"buy_volume").buy_volume()}sell_volume(e){return oE(e,"sell_volume").sell_volume()}total_volume(e){return oE(e,"total_volume").total_volume()}delta(e){return oE(e,"delta").delta()}poc(e){return oE(e,"poc").poc()}vah(e){return oE(e,"vah").vah()}val(e){return oE(e,"val").val()}rows(e){return oE(e,"rows").rows()}get_row_by_price(e,t){return oE(e,"get_row_by_price").get_row_by_price(t)}}function oT(e,t){let i=iF(e);if(i instanceof iB)return i;throw new ei(`The \`volume_row\` ID used in the \`${t}()\` call cannot be \`na\`.`,`volume_row.${t}`)}class ok{constructor(e){this.context=e}param(e,t=0,i){return m.from(e).get(t)}any(){throw new ei("Could not find function or function reference 'volume_row'","volume_row")}up_price(e){return oT(e,"up_price").up_price()}down_price(e){return oT(e,"down_price").down_price()}buy_volume(e){return oT(e,"buy_volume").buy_volume()}sell_volume(e){return oT(e,"sell_volume").sell_volume()}total_volume(e){return oT(e,"total_volume").total_volume()}delta(e){return oT(e,"delta").delta()}has_buy_imbalance(e){return oT(e,"has_buy_imbalance").has_buy_imbalance()}has_sell_imbalance(e){return oT(e,"has_sell_imbalance").has_sell_imbalance()}}let oA=["session","adjustment","backadjustment","settlement_as_close"];function oI(e,t){let i={};return e.forEach((e,r)=>{null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype?Object.assign(i,e):r<t.length&&void 0!==e&&(i[t[r]]=e)}),i}function oC(e){let{modifier:t}=i3(e);return t?{base:e.slice(0,e.lastIndexOf(";")),chartType:t}:{base:e,chartType:null}}class oM{constructor(e){this.context=e}param(e,t=0,i){return"string"==typeof e?e:m.from(e).get(t)}inherit(e,t){let{base:i,chartType:r}=oC(this._coerce(e)),n=i2(i6(this._coerce(t)),i1(i).modifiers);return r&&"standard"!==r?`${n};${r}`:n}new(e,t,...i){let r=oI([e,t,...i],["prefix","ticker",...oA]),n=this._coerce(r.prefix),s=this._coerce(r.ticker);return i2(n?s?`${n}:${s}`:n:s,this._applyModifiers({},r))}modify(e,...t){let i=oI([e,...t],["tickerid",...oA]),{base:r,chartType:n}=oC(this._coerce(i.tickerid)),{symbol:s,modifiers:a}=i1(r),o=i2(s,this._applyModifiers(a,i));return n?`${o};${n}`:o}_applyModifiers(e,t){let i={...e},r=e=>{let t=void 0===e?"":this._coerce(e);return""===t?void 0:t},n=r(t.session);"regular"===n?delete i.session:void 0!==n&&(i.session=n);let s=r(t.adjustment);void 0!==s&&(i.adjustment=s);let a=r(t.backadjustment);"on"===a?i.backadjustment="default":"off"===a&&delete i.backadjustment;let o=r(t.settlement_as_close);return"on"===o?i["settlement-as-close"]=!0:"off"===o&&(i["settlement-as-close"]=!1),i}standard(e){return null==e?i6(this.context?.pine?.syminfo?.tickerid||this.context?.tickerId||""):i6(this._coerce(e))}heikinashi(e){return i5(this._coerce(e),"heikinashi")}renko(e,t,i,r,n){return this._coerce(e)}kagi(e,t){return this._coerce(e)}linebreak(e,t){return this._coerce(e)}pointfigure(e,t,i,r,n){return this._coerce(e)}_coerce(e){if(null==e)return"";if(e instanceof m){let t=e.get(0);return null==t?"":String(t)}return"number"==typeof e&&isNaN(e)?"":String(e)}}let oP=["ta","math","request","array","input","color","ticker","strategy"],oD=["hline","plot","fill","label","line","box","linefill","polyline","table","footprint","volume_row","na","alert","time","time_close","dayofmonth","dayofweek","hour","minute","month","second","weekofyear","year"],oR=["request.security","request.security_lower_tf","request.footprint"],oO=["chart.left_visible_bar_time","chart.right_visible_bar_time"],oj=["plot","hline","fill","strategy.exit"],oV=["plotchar","plotshape","plotarrow","plotbar","plotcandle","bgcolor","barcolor"],o$=["line.new","line.copy","label.new","label.copy","polyline.new","box.new","box.copy","table.new","linefill.new"],oL=new Set([...oP,"fill","plot","hline","label","line","size","extend","display","format","location","shape","text","xloc","yloc","linefill","polyline","box","table","map","matrix","chart","alert","barstate","syminfo","session","timeframe","strategy","log","str","footprint","volume_row","position","font","order","currency","dayofweek","adjustment","barmerge","scale","settlement_as_close"]),oB=new Set(["arguments","await","case","catch","class","const","debugger","default","delete","do","enum","eval","extends","finally","function","implements","Infinity","instanceof","interface","let","NaN","new","package","private","protected","public","return","static","super","this","throw","try","typeof","undefined","void","with","yield"]),oF=new Set(["abs","add_col","add_row","avg","binary_search","binary_search_leftmost","binary_search_rightmost","buy_volume","cell","cell_set_bgcolor","cell_set_height","cell_set_text","cell_set_text_color","cell_set_text_font_family","cell_set_text_formatting","cell_set_text_halign","cell_set_text_size","cell_set_text_valign","cell_set_tooltip","cell_set_width","clear","col","columns","concat","contains","copy","covariance","delete","delta","det","diff","down_price","eigenvalues","eigenvectors","elements_count","every","fill","first","get","get_bottom","get_left","get_line1","get_line2","get_price","get_right","get_row_by_price","get_text","get_top","get_x","get_x1","get_x2","get_y","get_y1","get_y2","has_buy_imbalance","has_sell_imbalance","includes","indexof","insert","inv","is_antidiagonal","is_antisymmetric","is_binary","is_diagonal","is_identity","is_square","is_stochastic","is_symmetric","is_triangular","is_zero","join","keys","kron","last","lastindexof","max","median","merge_cells","min","mode","mult","percentile_linear_interpolation","percentile_nearest_rank","percentrank","pinv","poc","pop","pow","push","put","put_all","range","rank","remove","remove_col","remove_row","reshape","reverse","row","rows","sell_volume","set","set_bgcolor","set_border_color","set_border_style","set_border_width","set_bottom","set_bottom_right_point","set_color","set_extend","set_first_point","set_frame_color","set_frame_width","set_left","set_lefttop","set_point","set_position","set_right","set_rightbottom","set_second_point","set_size","set_style","set_text","set_text_color","set_text_font_family","set_text_formatting","set_text_halign","set_text_size","set_text_valign","set_text_wrap","set_textalign","set_textcolor","set_tooltip","set_top","set_top_left_point","set_width","set_x","set_x1","set_x2","set_xloc","set_xy","set_xy1","set_xy2","set_y","set_y1","set_y2","set_yloc","shift","size","slice","some","sort","sort_indices","standardize","stdev","submatrix","sum","swap_columns","swap_rows","total_volume","trace","transpose","unshift","up_price","vah","val","values","variance"]),oq={footprint:new Set(["buy_volume","sell_volume","total_volume","delta","poc","vah","val","rows","get_row_by_price"]),volume_row:new Set(["up_price","down_price","buy_volume","sell_volume","total_volume","delta","has_buy_imbalance","has_sell_imbalance"])},oz=new Set(["poc","vah","val","get_row_by_price"]),oU=["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","openTime","closeTime"],oW=[...oP,"plotchar","plotshape","plotarrow","plotbar","plotcandle","plot","bgcolor","barcolor","hline","fill","indicator","library","alertcondition","alert","error","max_bars_back","fixnan","na","nz","timestamp","str","box","line","label","table","chart","linefill","polyline","map","matrix","log","runtime","footprint","volume_row","Type","bool","int","float","string","timeframe","syminfo","barstate","session","bar_index","last_bar_index","last_bar_time","timenow","ask","bid","inputs","time","time_close","time_tradingday","dayofmonth","hour","minute","month","second","weekofyear","year","order","currency","display","shape","location","size","format","dayofweek","xloc","yloc","text","font","extend","position","scale","barmerge","adjustment","backadjustment","settlement_as_close","earnings","dividends","splits"],oK=["na","nz","plot","plotchar","color","hline","fill"],oG=["id"],oH=e=>["id",e],oY={set_x1:oH("x"),set_y1:oH("y"),set_x2:oH("x"),set_y2:oH("y"),set_xy1:["id","x","y"],set_xy2:["id","x","y"],set_color:oH("color"),set_width:oH("width"),set_style:oH("style"),set_extend:oH("extend"),set_xloc:["id","x1","x2","xloc"],set_first_point:oH("point"),set_second_point:oH("point"),get_x1:oG,get_y1:oG,get_x2:oG,get_y2:oG,get_price:oH("x"),copy:oG,delete:oG},oZ={set_left:oH("left"),set_right:oH("right"),set_top:oH("top"),set_bottom:oH("bottom"),set_lefttop:["id","left","top"],set_rightbottom:["id","right","bottom"],set_top_left_point:oH("point"),set_bottom_right_point:oH("point"),set_xloc:["id","left","right","xloc"],set_bgcolor:oH("color"),set_border_color:oH("color"),set_border_width:oH("width"),set_border_style:oH("style"),set_extend:oH("extend"),set_text:oH("text"),set_text_color:oH("text_color"),set_text_size:oH("text_size"),set_text_halign:oH("text_halign"),set_text_valign:oH("text_valign"),set_text_wrap:oH("text_wrap"),set_text_font_family:oH("text_font_family"),set_text_formatting:oH("text_formatting"),get_left:oG,get_right:oG,get_top:oG,get_bottom:oG,copy:oG,delete:oG},oJ={set_x:oH("x"),set_y:oH("y"),set_xy:["id","x","y"],set_text:oH("text"),set_color:oH("color"),set_textcolor:oH("textcolor"),set_size:oH("size"),set_style:oH("style"),set_textalign:oH("textalign"),set_tooltip:oH("tooltip"),set_text_font_family:oH("text_font_family"),set_text_formatting:oH("text_formatting"),set_xloc:["id","x","xloc"],set_yloc:oH("yloc"),set_point:oH("point"),get_x:oG,get_y:oG,get_text:oG,copy:oG,delete:oG},oQ={set_color:oH("color"),get_line1:oG,get_line2:oG,delete:oG},oX=e=>["table_id","column","row",e],o0=e=>["table_id",e],o1={line:oY,box:oZ,label:oJ,linefill:oQ,polyline:{delete:oG},table:{delete:["table_id"],cell_set_text:oX("text"),cell_set_bgcolor:oX("bgcolor"),cell_set_text_color:oX("text_color"),cell_set_text_size:oX("text_size"),cell_set_height:oX("height"),cell_set_width:oX("width"),cell_set_tooltip:oX("tooltip"),cell_set_text_halign:oX("text_halign"),cell_set_text_valign:oX("text_valign"),cell_set_text_font_family:oX("text_font_family"),cell_set_text_formatting:oX("text_formatting"),set_position:o0("position"),set_bgcolor:o0("bgcolor"),set_border_color:o0("border_color"),set_border_width:o0("border_width"),set_frame_color:o0("frame_color"),set_frame_width:o0("frame_width")}};var o2=Object.defineProperty,o3=(e,t,i)=>((e,t,i)=>t in e?o2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let o4=new Proxy({},{get:(e,t)=>"get_text"===t||"get_tooltip"===t?()=>"":()=>NaN}),o6=class e{constructor({marketData:e,source:t,tickerId:i,timeframe:r,limit:n,sDate:s,eDate:a,fullContext:o,inputs:l}){o3(this,"data",{open:new m([]),high:new m([]),low:new m([]),close:new m([]),volume:new m([]),hl2:new m([]),hlc3:new m([]),ohlc4:new m([]),hlcc4:new m([]),bar_index:new m([])}),o3(this,"indicator"),o3(this,"cache",{}),o3(this,"taState",{}),o3(this,"strategy"),o3(this,"isSecondaryContext",!1),o3(this,"chartTimezone",null),o3(this,"chartStyle","standard"),o3(this,"dataVersion",0),o3(this,"__maxLoops",5e5),o3(this,"NA",NaN),o3(this,"warnings",[]),o3(this,"alerts",[]),o3(this,"_alertMode","realtime"),o3(this,"_fillsOnTickGrid",!1),o3(this,"importResolver",null),o3(this,"_rawBar"),o3(this,"_propOverrides",{}),o3(this,"_execTick",0),o3(this,"lang"),o3(this,"length",0),o3(this,"_drawingHelpers",[]),o3(this,"pine"),o3(this,"idx",0),o3(this,"params",{}),o3(this,"const",{}),o3(this,"var",{}),o3(this,"let",{}),o3(this,"lctx",new Map),o3(this,"result"),o3(this,"plots",{}),o3(this,"marketData"),o3(this,"source"),o3(this,"tickerId"),o3(this,"timeframe",""),o3(this,"pineVersion",null),o3(this,"limit"),o3(this,"sDate"),o3(this,"eDate"),o3(this,"fullContext"),o3(this,"viewportLeft"),o3(this,"viewportRight"),o3(this,"pineTSCode"),o3(this,"transpiledFn",null),o3(this,"inputs",{}),o3(this,"_callStack",[]),o3(this,"_pathStack",[]),this.marketData=e,this.source=t,this.tickerId=i,this.timeframe=r,this.limit=n,this.sDate=s,this.eDate=a,this.fullContext=o||this,this.inputs=l||{};let h=new tG(this),c={Type:h.Type.bind(h),na:new tq,nz:h.nz.bind(h),indicator:h.indicator.bind(h),library:h.library.bind(h),fixnan:h.fixnan.bind(h),alertcondition:h.alertcondition.bind(h),alert:new tK(this),error:h.error.bind(h),max_bars_back:h.max_bars_back.bind(h),timestamp:h.timestamp.bind(h),time:new tS(this,"openTime"),time_close:new tS(this,"closeTime"),dayofmonth:new tT(this,tk.dayofmonth),dayofweek:new tT(this,tk.dayofweek),hour:new tT(this,tk.hour),minute:new tT(this,tk.minute),month:new tT(this,tk.month),second:new tT(this,tk.second),weekofyear:new tT(this,tk.weekofyear),year:new tT(this,tk.year),bool:h.bool.bind(h),int:h.int.bind(h),float:h.float.bind(h),string:h.string.bind(h)},p=this;this.pine={input:new t6(this),ta:new r1(this),math:new iO(this),request:new ry(this),array:new e$(this),map:new ez(this),matrix:new eY(this),ticker:new oM(this),strategy:new sf(this),syminfo:null,timeframe:new s5(this),barstate:new eJ(this),session:new tC(this),get bar_index(){return p.data.bar_index},get last_bar_index(){let e=p.marketData;return Array.isArray(e)&&e.length>0?e.length-1:p.data.close.length-1},get last_bar_time(){let e=p.marketData;return Array.isArray(e)&&e.length>0?e[e.length-1].openTime:p.data.openTime.get(0)},get timenow(){return new Date().getTime()},get ask(){return NaN},get bid(){return NaN},get time_tradingday(){let e=m.from(p.data.closeTime).get(0);if(isNaN(e))return NaN;let t=tb(e,p.pine?.syminfo?.timezone||"UTC");return Date.UTC(t.year,t.month-1,t.day,0,0,0)},get inputs(){return p.inputs},log:new sy(this),runtime:new s_(this),str:new s3(this),...c,...X};let u=c.dayofweek;Object.assign(u,{sunday:1,monday:2,tuesday:3,wednesday:4,thursday:5,friday:6,saturday:7}),this.pine.dayofweek=u;let d=new aw(this),f=new aS(this),y=new aE(this);this.bindContextObject(d,["plotchar","plotshape","plotarrow","plotbar","plotcandle","bgcolor","barcolor"]),this.bindContextObject(d,["any","param","linestyle_dashed","linestyle_dotted","linestyle_solid","style_area","style_areabr","style_circles","style_columns","style_cross","style_histogram","style_line","style_linebr","style_stepline","style_stepline_diamond","style_steplinebr"],"plot"),this.bindContextObject(f,["any","style_dashed","style_solid","style_dotted","param"],"hline"),this.bindContextObject(y,["any","param"],"fill");let _=new aT(this);this.pine.chart={param:_.param.bind(_),get bg_color(){return _.bg_color()},get fg_color(){return _.fg_color()},get is_standard(){return _.is_standard()},get is_heikinashi(){return _.is_heikinashi()},get is_kagi(){return _.is_kagi()},get is_linebreak(){return _.is_linebreak()},get is_pnf(){return _.is_pnf()},get is_range(){return _.is_range()},get is_renko(){return _.is_renko()},point:_.point,get left_visible_bar_time(){if(void 0!==p.viewportLeft)return p.viewportLeft;let e=p.marketData;return Array.isArray(e)&&e.length>0?e[0].openTime:NaN},get right_visible_bar_time(){if(void 0!==p.viewportRight)return p.viewportRight;let e=p.marketData;return Array.isArray(e)&&e.length>0?e[e.length-1].openTime:NaN}};let g=new a$(this);this.bindContextObject(g,["any","new","param","set_x","set_y","set_xy","set_text","set_color","set_textcolor","set_size","set_style","set_textalign","set_tooltip","set_text_font_family","set_text_formatting","set_point","set_xloc","set_yloc","get_x","get_y","get_text","copy","delete","style_label_down","style_label_up","style_label_left","style_label_right","style_label_lower_left","style_label_lower_right","style_label_upper_left","style_label_upper_right","style_label_center","style_circle","style_square","style_diamond","style_flag","style_arrowup","style_arrowdown","style_cross","style_xcross","style_triangleup","style_triangledown","style_none","style_text_outline"],"label"),Object.defineProperty(this.pine.label,"all",{get:()=>new eO(g.all,eR.label,this)});let x=new aY(this);this.bindContextObject(x,["any","new","param","set_x1","set_y1","set_x2","set_y2","set_xy1","set_xy2","set_color","set_width","set_style","set_extend","set_xloc","set_first_point","set_second_point","get_x1","get_y1","get_x2","get_y2","get_price","copy","delete","style_solid","style_dotted","style_dashed","style_arrow_left","style_arrow_right","style_arrow_both"],"line"),Object.defineProperty(this.pine.line,"all",{get:()=>new eO(x.all,eR.line,this)});let b=new a6(this);this.bindContextObject(b,["any","new","param","copy","delete","set_left","set_right","set_top","set_bottom","set_lefttop","set_rightbottom","set_top_left_point","set_bottom_right_point","set_bgcolor","set_border_color","set_border_width","set_border_style","set_extend","set_xloc","set_text","set_text_color","set_text_size","set_text_halign","set_text_valign","set_text_wrap","set_text_font_family","set_text_formatting","get_left","get_right","get_top","get_bottom"],"box"),Object.defineProperty(this.pine.box,"all",{get:()=>new eO(b.all,eR.box,this)});let v=new or(this);x.linefills=v,this.bindContextObject(v,["any","new","param","set_color","get_line1","get_line2","delete"],"linefill"),Object.defineProperty(this.pine.linefill,"all",{get:()=>new eO(v.all,eR.linefill,this)});let w=new op(this);this.bindContextObject(w,["any","new","param","delete"],"polyline"),Object.defineProperty(this.pine.polyline,"all",{get:()=>new eO(w.all,eR.any,this)});let E=new oS(this);this.bindContextObject(E,["any","new","param","cell","delete","clear","merge_cells","cell_set_text","cell_set_bgcolor","cell_set_text_color","cell_set_text_size","cell_set_height","cell_set_width","cell_set_tooltip","cell_set_text_halign","cell_set_text_valign","cell_set_text_font_family","cell_set_text_formatting","set_position","set_bgcolor","set_border_color","set_border_width","set_frame_color","set_frame_width"],"table"),Object.defineProperty(this.pine.table,"all",{get:()=>new eO(E.all,eR.table,this)}),this._drawingHelpers=[g,x,b,v,w,E];let N=new oN(this);this.bindContextObject(N,["any","param","buy_volume","sell_volume","total_volume","delta","poc","vah","val","rows","get_row_by_price"],"footprint");let T=new ok(this);this.bindContextObject(T,["any","param","up_price","down_price","buy_volume","sell_volume","total_volume","delta","has_buy_imbalance","has_sell_imbalance"],"volume_row");let k=new S(this);this.bindContextObject(k,["any","param","new","rgb","from_gradient","r","g","b","t","aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow"],"color")}warn(e,t){this.warnings.push({message:e,method:t,bar:this.idx})}rollbackDrawings(e){for(let t of this._drawingHelpers)t.rollbackFromBar(e)}bindContextObject(e,t,i=""){i&&!this.pine[i]&&(this.pine[i]={});let r=i?this.pine[i]:this.pine,n=o1[i];for(let i of t)"function"==typeof e[i]?(n&&n[i]&&(e[i]=eT(e[i].bind(e),n[i])),r[i]=e[i].bind(e)):r[i]=e[i]}toTuple(e,t){return Array.isArray(e)?Array.isArray(e[0])?e:[e]:[Array(t).fill(NaN)]}init(e,t,i=0){let r;return r=t instanceof m?t.get(0):Array.isArray(t)?Array.isArray(t[0])?t[0]:t[t.length-1+i]:t,e?e instanceof m?(e.data[e.data.length-1]=r,"boolean"==typeof r&&this.pineVersion>=6&&(e.beforeStart=!1),e):Array.isArray(e)?(e[e.length-1]=r,this.typedSeries(e,r)):this.typedSeries([r],r):this.typedSeries([r],r)}typedSeries(e,t,i=0){let r=new m(e,i);return"boolean"==typeof t&&this.pineVersion>=6&&(r.beforeStart=!1),r}initVar(e,t,i=!1){let r;if(e)return e;if("function"==typeof t&&(t=t()),t instanceof p){let e=t.__def__;for(let i in e)"function"==typeof t[i]&&(t[i]=t[i]())}r=t instanceof m?t.get(0):Array.isArray(t)?Array.isArray(t[0])?t[0]:this.precision(t[t.length-1]):this.precision(t);let n=this.typedSeries([r],r);return i&&(n.varip=!0),n}precision(t,i=10){if("number"!=typeof t)return t;let r=10===i?e.PRECISION_EPSILON:10**i;return Math.abs(t)*r<0x20000000000000?Math.round(t*r)/r:t}param(e,t,i){if("string"==typeof e)return e;if(e instanceof m){if(t){let i=new m(e.data,e.offset+t);return i.beforeStart=e.beforeStart,i}return e}return e1(e)&&(e=e.__value),Array.isArray(e)||"object"!=typeof e?(this.params[i]||(this.params[i]=[]),Array.isArray(e)?new m(e,t||0):(0===this.params[i].length?this.params[i].push(e):this.params[i][this.params[i].length-1]=e,this.typedSeries(this.params[i],e,t||0))):e}get(e,t){if((null==t||Number.isNaN(t))&&(t=0),"number"!=typeof t||Number.isInteger(t)||(t=Math.trunc(t)),e instanceof m)return e.get(t);if(Array.isArray(e)){let i=e.length-1-t;return i<0||i>=e.length?NaN:e[i]}return e}set(e,t){return e instanceof m?void e.set(0,"number"==typeof t?this.precision(t):t):Array.isArray(e)?void(e.length>0?e[e.length-1]=t:e.push(t)):void 0}iter(e){return null==e?[]:Array.isArray(e.array)?e.array:e.map instanceof Map?e.map:e instanceof eG?this._matrixRows(e):e}_matrixRows(e){return e.matrix.map((t,i)=>e.row(i))}entries(e){return null==e?[].entries():Array.isArray(e.array)?e.array.entries():e.map instanceof Map?e.map.entries():e instanceof eG?this._matrixRows(e).entries():Array.isArray(e)||"function"==typeof e.entries?e.entries():[].entries()}pushId(e){let t=this._pathStack.length>0?this._pathStack[this._pathStack.length-1]:"",i=t?t+"|"+e:e;this._callStack.push(e),this._pathStack.push(i)}popId(){this._callStack.pop(),this._pathStack.pop()}peekId(){return this._pathStack.length>0?this._pathStack[this._pathStack.length-1]:""}peekCtx(){let e=this.peekId();if(!e)return this;let t=this.lctx.get(e);return t||(t={id:e,let:{},const:{},var:{}},this.lctx.set(e,t)),t}loopError(e){throw new ei(e)}drawingOrNa(e){return null==e||"number"==typeof e&&isNaN(e)?o4:e}call(e,t,...i){this.pushId(t);try{let t=e(...i);return void 0===t?NaN:t}finally{this.popId()}}callMethod(e,t,i,r,...n){let s=e=>e instanceof m?e.get(0):e,a=s(r);if(null==a||"number"==typeof a&&Number.isNaN(a))return;for(let[e,s]of i)if(function(e,t,i){if(t)return i instanceof p&&i._udt?.__name__===t;let r=e?.__pineReceiverType__;if("string"!=typeof r)return!1;switch(function(e){let t=e.trim();if(t.endsWith("[]"))return"array";let i=t.indexOf("<");i>=0&&(t=t.slice(0,i));let r=t.split(/\s+/).filter(Boolean);return r.length?r[r.length-1]:""}(r)){case"line":return i instanceof aq;case"box":return i instanceof aX;case"label":return i instanceof aC;case"polyline":return i instanceof oo;case"linefill":return i instanceof a7;case"table":return i instanceof oy;case"array":return i instanceof eO||Array.isArray(i);case"map":return i instanceof eq;case"matrix":return i instanceof eG;case"chart.point":return i instanceof e0;case"string":return"string"==typeof i;case"bool":return"boolean"==typeof i;case"int":case"float":return"number"==typeof i;default:return!1}}(e,s,a))return this.call(e,t,r,...n);if(!oF.has(e))return;let o=a[e];return"function"==typeof o?o.apply(a,n.map(s)):void 0}get math(){return this._showDeprecationWarning("const math = context.math","const { math, ta, input } = context.pine"),this.pine.math}get ta(){return this._showDeprecationWarning("const ta = context.ta","const { ta, math, input } = context.pine"),this.pine.ta}get input(){return this._showDeprecationWarning("const input = context.input","const { input, math, ta } = context.pine"),this.pine.input}get request(){return this._showDeprecationWarning("const request = context.request","const { request, math, ta } = context.pine"),this.pine.request}get array(){return this._showDeprecationWarning("const array = context.array","const { array, math, ta } = context.pine"),this.pine.array}get core(){return this._showDeprecationWarning("context.core.*","context.pine (e.g., const { na, plotchar, color, plot, nz } = context.pine)"),{na:this.pine.na,fill:this.pine.fill,plotchar:this.pine.plotchar,plotshape:this.pine.plotshape,plotarrow:this.pine.plotarrow,color:this.pine.color,plot:this.pine.plot,nz:this.pine.nz}}_showDeprecationWarning(t,i){let r=`${t}->${i}`;e._deprecationWarningsShown.has(r)||(e._deprecationWarningsShown.add(r),"u">typeof window?console.warn("%c[WARNING]%c %s syntax is deprecated. Use %s instead. This will be removed in a future version.","color: #FFA500; font-weight: bold;","color: #FFA500;",t,i):console.warn(`\x1b[33m[WARNING] ${t} syntax is deprecated. Use ${i} instead. This will be removed in a future version.\x1b[0m`))}};o3(o6,"_deprecationWarningsShown",new Set),o3(o6,"PRECISION_EPSILON",1e10);let o5=o6;function o9(e){let t=m.from(e).get(0);if(null==t||"number"==typeof t&&isNaN(t))return["",""];let i=i6(String(t)),r=i.indexOf(":");return r<0?["",""]:[i.slice(0,r),i.slice(r+1)]}function o8(e){return{...e,param:(e,t=0)=>m.from(e).get(t),__ticker:e=>o9(e)[1],__prefix:e=>o9(e)[0]}}var o7=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],le=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],lt="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-࢏ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚ౜ౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ೜-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ƛ꟱-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",li={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},lr="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",ln={5:lr,"5module":lr+" export import",6:lr+" const class extends export import super"},ls=/^in(stanceof)?$/,la=RegExp("["+lt+"]"),lo=RegExp("["+lt+"‌‍\xb7̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-᫝᫠-᫫ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・]");function ll(e,t){for(var i=65536,r=0;r<t.length&&!((i+=t[r])>e);r+=2)if((i+=t[r+1])>=e)return!0;return!1}function lh(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&la.test(String.fromCharCode(e)):!1!==t&&ll(e,le)))}function lc(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&lo.test(String.fromCharCode(e)):!1!==t&&(ll(e,le)||ll(e,o7)))))}var lp=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function lu(e,t){return new lp(e,{beforeExpr:!0,binop:t})}var ld={beforeExpr:!0},lm={startsExpr:!0},lf={};function ly(e,t){return void 0===t&&(t={}),t.keyword=e,lf[e]=new lp(e,t)}var l_={num:new lp("num",lm),regexp:new lp("regexp",lm),string:new lp("string",lm),name:new lp("name",lm),privateId:new lp("privateId",lm),eof:new lp("eof"),bracketL:new lp("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new lp("]"),braceL:new lp("{",{beforeExpr:!0,startsExpr:!0}),braceR:new lp("}"),parenL:new lp("(",{beforeExpr:!0,startsExpr:!0}),parenR:new lp(")"),comma:new lp(",",ld),semi:new lp(";",ld),colon:new lp(":",ld),dot:new lp("."),question:new lp("?",ld),questionDot:new lp("?."),arrow:new lp("=>",ld),template:new lp("template"),invalidTemplate:new lp("invalidTemplate"),ellipsis:new lp("...",ld),backQuote:new lp("`",lm),dollarBraceL:new lp("${",{beforeExpr:!0,startsExpr:!0}),eq:new lp("=",{beforeExpr:!0,isAssign:!0}),assign:new lp("_=",{beforeExpr:!0,isAssign:!0}),incDec:new lp("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new lp("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:lu("||",1),logicalAND:lu("&&",2),bitwiseOR:lu("|",3),bitwiseXOR:lu("^",4),bitwiseAND:lu("&",5),equality:lu("==/!=/===/!==",6),relational:lu("</>/<=/>=",7),bitShift:lu("<</>>/>>>",8),plusMin:new lp("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:lu("%",10),star:lu("*",10),slash:lu("/",10),starstar:new lp("**",{beforeExpr:!0}),coalesce:lu("??",1),_break:ly("break"),_case:ly("case",ld),_catch:ly("catch"),_continue:ly("continue"),_debugger:ly("debugger"),_default:ly("default",ld),_do:ly("do",{isLoop:!0,beforeExpr:!0}),_else:ly("else",ld),_finally:ly("finally"),_for:ly("for",{isLoop:!0}),_function:ly("function",lm),_if:ly("if"),_return:ly("return",ld),_switch:ly("switch"),_throw:ly("throw",ld),_try:ly("try"),_var:ly("var"),_const:ly("const"),_while:ly("while",{isLoop:!0}),_with:ly("with"),_new:ly("new",{beforeExpr:!0,startsExpr:!0}),_this:ly("this",lm),_super:ly("super",lm),_class:ly("class",lm),_extends:ly("extends",ld),_export:ly("export"),_import:ly("import",lm),_null:ly("null",lm),_true:ly("true",lm),_false:ly("false",lm),_in:ly("in",{beforeExpr:!0,binop:7}),_instanceof:ly("instanceof",{beforeExpr:!0,binop:7}),_typeof:ly("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:ly("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:ly("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},lg=/\r\n?|\n|\u2028|\u2029/,lx=RegExp(lg.source,"g");function lb(e){return 10===e||13===e||8232===e||8233===e}function lv(e,t,i){void 0===i&&(i=e.length);for(var r=t;r<i;r++){var n=e.charCodeAt(r);if(lb(n))return r<i-1&&13===n&&10===e.charCodeAt(r+1)?r+2:r+1}return -1}var lw=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,lS=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,lE=Object.prototype,lN=lE.hasOwnProperty,lT=lE.toString,lk=Object.hasOwn||function(e,t){return lN.call(e,t)},lA=Array.isArray||function(e){return"[object Array]"===lT.call(e)},lI=Object.create(null);function lC(e){return lI[e]||(lI[e]=RegExp("^(?:"+e.replace(/ /g,"|")+")$"))}function lM(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(((e-=65536)>>10)+55296,(1023&e)+56320)}var lP=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,lD=function(e,t){this.line=e,this.column=t};lD.prototype.offset=function(e){return new lD(this.line,this.column+e)};var lR=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function lO(e,t){for(var i=1,r=0;;){var n=lv(e,r,t);if(n<0)return new lD(i,t-r);++i,r=n}}var lj={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},lV=!1;function l$(e,t){return 2|4*!!e|8*!!t}var lL=function(e,t,i){this.options=e=function(e){var t,i,r={};for(var n in lj)r[n]=e&&lk(e,n)?e[n]:lj[n];if("latest"===r.ecmaVersion?r.ecmaVersion=1e8:null==r.ecmaVersion?(!lV&&"object"==typeof console&&console.warn&&(lV=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
298
+ Defaulting to 2020, but this will stop working in the future.`)),r.ecmaVersion=11):r.ecmaVersion>=2015&&(r.ecmaVersion-=2009),null==r.allowReserved&&(r.allowReserved=r.ecmaVersion<5),e&&null!=e.allowHashBang||(r.allowHashBang=r.ecmaVersion>=14),lA(r.onToken)){var s=r.onToken;r.onToken=function(e){return s.push(e)}}if(lA(r.onComment)&&(t=r,i=r.onComment,r.onComment=function(e,r,n,s,a,o){var l={type:e?"Block":"Line",value:r,start:n,end:s};t.locations&&(l.loc=new lR(this,a,o)),t.ranges&&(l.range=[n,s]),i.push(l)}),"commonjs"===r.sourceType&&r.allowAwaitOutsideFunction)throw Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return r}(e),this.sourceFile=e.sourceFile,this.keywords=lC(ln[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=li[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=lC(r);var n=(r?r+" ":"")+li.strict;this.reservedWordsStrict=lC(n),this.reservedWordsStrictBind=lC(n+" "+li.strictBind),this.input=String(t),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf(`
299
+ `,i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(lg).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=l_.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope("commonjs"===this.options.sourceType?2:1),this.regexpState=null,this.privateNameStack=[]},lB={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};lL.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},lB.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},lB.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0},lB.inAsync.get=function(){return(4&this.currentVarScope().flags)>0},lB.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t)return!1;if(2&t)return(4&t)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},lB.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&1&this.currentVarScope().flags)},lB.allowSuper.get=function(){return(64&this.currentThisScope().flags)>0||this.options.allowSuperOutsideMethod},lB.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},lB.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},lB.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t||2&t&&!(16&t))return!0}return!1},lB.allowUsing.get=function(){var e=this.currentScope().flags;return!(1024&e||!this.inModule&&1&e)},lB.inClassStaticBlock.get=function(){return(256&this.currentVarScope().flags)>0},lL.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var i=this,r=0;r<e.length;r++)i=e[r](i);return i},lL.parse=function(e,t){return new this(t,e).parse()},lL.parseExpressionAt=function(e,t,i){var r=new this(i,e,t);return r.nextToken(),r.parseExpression()},lL.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(lL.prototype,lB);var lF=lL.prototype,lq=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;lF.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){lS.lastIndex=e,e+=lS.exec(this.input)[0].length;var t=lq.exec(this.input.slice(e));if(!t)return!1;if("use strict"===(t[1]||t[2])){lS.lastIndex=e+t[0].length;var i=lS.exec(this.input),r=i.index+i[0].length,n=this.input.charAt(r);return";"===n||"}"===n||lg.test(i[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}lS.lastIndex=e+=t[0].length,e+=lS.exec(this.input)[0].length,";"===this.input[e]&&e++}},lF.eat=function(e){return this.type===e&&(this.next(),!0)},lF.isContextual=function(e){return this.type===l_.name&&this.value===e&&!this.containsEsc},lF.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},lF.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},lF.canInsertSemicolon=function(){return this.type===l_.eof||this.type===l_.braceR||lg.test(this.input.slice(this.lastTokEnd,this.start))},lF.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},lF.semicolon=function(){this.eat(l_.semi)||this.insertSemicolon()||this.unexpected()},lF.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},lF.expect=function(e){this.eat(e)||this.unexpected()},lF.unexpected=function(e){this.raise(e??this.start,"Unexpected token")};var lz=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};lF.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var i=t?e.parenthesizedAssign:e.parenthesizedBind;i>-1&&this.raiseRecoverable(i,t?"Assigning to rvalue":"Parenthesized pattern")}},lF.checkExpressionErrors=function(e,t){if(!e)return!1;var i=e.shorthandAssign,r=e.doubleProto;if(!t)return i>=0||r>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},lF.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")},lF.isSimpleAssignTarget=function(e){return"ParenthesizedExpression"===e.type?this.isSimpleAssignTarget(e.expression):"Identifier"===e.type||"MemberExpression"===e.type};var lU=lL.prototype;lU.parseTopLevel=function(e){var t=Object.create(null);for(e.body||(e.body=[]);this.type!==l_.eof;){var i=this.parseStatement(null,!0,t);e.body.push(i)}if(this.inModule)for(var r=0,n=Object.keys(this.undefinedExports);r<n.length;r+=1){var s=n[r];this.raiseRecoverable(this.undefinedExports[s].start,"Export '"+s+"' is not defined")}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType="commonjs"===this.options.sourceType?"script":this.options.sourceType,this.finishNode(e,"Program")};var lW={kind:"loop"},lK={kind:"switch"};lU.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;lS.lastIndex=this.pos;var t=lS.exec(this.input),i=this.pos+t[0].length,r=this.fullCharCodeAt(i);if(91===r||92===r)return!0;if(e)return!1;if(123===r)return!0;if(lh(r)){var n=i;do i+=r<=65535?1:2;while(lc(r=this.fullCharCodeAt(i)));if(92===r)return!0;var s=this.input.slice(n,i);if(!ls.test(s))return!0}return!1},lU.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;lS.lastIndex=this.pos;var e,t=lS.exec(this.input),i=this.pos+t[0].length;return!lg.test(this.input.slice(this.pos,i))&&"function"===this.input.slice(i,i+8)&&(i+8===this.input.length||!(lc(e=this.fullCharCodeAt(i+8))||92===e))},lU.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?"await":"using"))return!1;lS.lastIndex=this.pos;var i=lS.exec(this.input),r=this.pos+i[0].length;if(lg.test(this.input.slice(this.pos,r)))return!1;if(e){var n,s=r+5;if("using"!==this.input.slice(r,s)||s===this.input.length||lc(n=this.fullCharCodeAt(s))||92===n)return!1;lS.lastIndex=s;var a=lS.exec(this.input);if(r=s+a[0].length,a&&lg.test(this.input.slice(s,r)))return!1}var o=this.fullCharCodeAt(r);if(!lh(o)&&92!==o)return!1;var l=r;do r+=o<=65535?1:2;while(lc(o=this.fullCharCodeAt(r)));if(92===o)return!0;var h=this.input.slice(l,r);return!(ls.test(h)||t&&"of"===h)},lU.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},lU.isUsing=function(e){return this.isUsingKeyword(!1,e)},lU.parseStatement=function(e,t,i){var r,n=this.type,s=this.startNode();switch(this.isLet(e)&&(n=l_._var,r="let"),n){case l_._break:case l_._continue:return this.parseBreakContinueStatement(s,n.keyword);case l_._debugger:return this.parseDebuggerStatement(s);case l_._do:return this.parseDoStatement(s);case l_._for:return this.parseForStatement(s);case l_._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(s,!1,!e);case l_._class:return e&&this.unexpected(),this.parseClass(s,!0);case l_._if:return this.parseIfStatement(s);case l_._return:return this.parseReturnStatement(s);case l_._switch:return this.parseSwitchStatement(s);case l_._throw:return this.parseThrowStatement(s);case l_._try:return this.parseTryStatement(s);case l_._const:case l_._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(s,r);case l_._while:return this.parseWhileStatement(s);case l_._with:return this.parseWithStatement(s);case l_.braceL:return this.parseBlock(!0,s);case l_.semi:return this.parseEmptyStatement(s);case l_._export:case l_._import:if(this.options.ecmaVersion>10&&n===l_._import){lS.lastIndex=this.pos;var a=lS.exec(this.input),o=this.pos+a[0].length,l=this.input.charCodeAt(o);if(40===l||46===l)return this.parseExpressionStatement(s,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===l_._import?this.parseImport(s):this.parseExport(s,i);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(s,!0,!e);var h=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(h)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),"await using"===h&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(s,!1,h),this.semicolon(),this.finishNode(s,"VariableDeclaration");var c=this.value,p=this.parseExpression();return n===l_.name&&"Identifier"===p.type&&this.eat(l_.colon)?this.parseLabeledStatement(s,c,p,e):this.parseExpressionStatement(s,p)}},lU.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(l_.semi)||this.insertSemicolon()?e.label=null:this.type!==l_.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r<this.labels.length;++r){var n=this.labels[r];if((null==e.label||n.name===e.label.name)&&(null!=n.kind&&(i||"loop"===n.kind)||e.label&&i))break}return r===this.labels.length&&this.raise(e.start,"Unsyntactic "+t),this.finishNode(e,i?"BreakStatement":"ContinueStatement")},lU.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")},lU.parseDoStatement=function(e){return this.next(),this.labels.push(lW),e.body=this.parseStatement("do"),this.labels.pop(),this.expect(l_._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(l_.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},lU.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(lW),this.enterScope(0),this.expect(l_.parenL),this.type===l_.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===l_._var||this.type===l_._const||i){var r=this.startNode(),n=i?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),this.parseForAfterInit(e,r,t)}var s=this.isContextual("let"),a=!1,o=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(o){var l=this.startNode();return this.next(),"await using"===o&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(l,!0,o),this.finishNode(l,"VariableDeclaration"),this.parseForAfterInit(e,l,t)}var h=this.containsEsc,c=new lz,p=this.start,u=t>-1?this.parseExprSubscripts(c,"await"):this.parseExpression(!0,c);return this.type===l_._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===l_._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(u.start!==p||h||"Identifier"!==u.type||"async"!==u.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),s&&a&&this.raise(u.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(u,!1,c),this.checkLValPattern(u),this.parseForIn(e,u)):(this.checkExpressionErrors(c,!0),t>-1&&this.unexpected(t),this.parseFor(e,u))},lU.parseForAfterInit=function(e,t,i){return(this.type===l_._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===t.declarations.length?(this.options.ecmaVersion>=9&&(this.type===l_._in?i>-1&&this.unexpected(i):e.await=i>-1),this.parseForIn(e,t)):(i>-1&&this.unexpected(i),this.parseFor(e,t))},lU.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,lH|(i?0:lY),!1,t)},lU.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(l_._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},lU.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(l_.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},lU.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(l_.braceL),this.labels.push(lK),this.enterScope(1024);for(var t,i=!1;this.type!==l_.braceR;)if(this.type===l_._case||this.type===l_._default){var r=this.type===l_._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(i&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),i=!0,t.test=null),this.expect(l_.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},lU.parseThrowStatement=function(e){return this.next(),lg.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var lG=[];lU.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(32*!!t),this.checkLValPattern(e,t?4:2),this.expect(l_.parenR),e},lU.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===l_._catch){var t=this.startNode();this.next(),this.eat(l_.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(l_._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},lU.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},lU.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(lW),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},lU.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},lU.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},lU.parseLabeledStatement=function(e,t,i,r){for(var n=0,s=this.labels;n<s.length;n+=1)s[n].name===t&&this.raise(i.start,"Label '"+t+"' is already declared");for(var a=this.type.isLoop?"loop":this.type===l_._switch?"switch":null,o=this.labels.length-1;o>=0;o--){var l=this.labels[o];if(l.statementStart===e.start)l.statementStart=this.start,l.kind=a;else break}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=i,this.finishNode(e,"LabeledStatement")},lU.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},lU.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(l_.braceL),e&&this.enterScope(0);this.type!==l_.braceR;){var r=this.parseStatement(null);t.body.push(r)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},lU.parseFor=function(e,t){return e.init=t,this.expect(l_.semi),e.test=this.type===l_.semi?null:this.parseExpression(),this.expect(l_.semi),e.update=this.type===l_.parenR?null:this.parseExpression(),this.expect(l_.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},lU.parseForIn=function(e,t){var i=this.type===l_._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!i||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(l_.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},lU.parseVar=function(e,t,i,r){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(l_.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==i||this.type===l_._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"using"!==i&&"await using"!==i||!(this.options.ecmaVersion>=17)||this.type===l_._in||this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===l_._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.raise(this.lastTokEnd,"Missing initializer in "+i+" declaration"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(l_.comma))break}return e},lU.parseVarId=function(e,t){e.id="using"===t||"await using"===t?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var lH=1,lY=2;function lZ(e,t){var i=e.computed,r=e.key;return!i&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}lU.parseFunction=function(e,t,i,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===l_.star&&t&lY&&this.unexpected(),e.generator=this.eat(l_.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&lH&&(e.id=4&t&&this.type!==l_.name?null:this.parseIdent(),e.id&&!(t&lY)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var s=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(l$(e.async,e.generator)),t&lH||(e.id=this.type===l_.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,i,!1,n),this.yieldPos=s,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&lH?"FunctionDeclaration":"FunctionExpression")},lU.parseFunctionParams=function(e){this.expect(l_.parenL),e.params=this.parseBindingList(l_.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},lU.parseClass=function(e,t){this.next();var i=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),s=!1;for(n.body=[],this.expect(l_.braceL);this.type!==l_.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(s&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),s=!0):a.key&&"PrivateIdentifier"===a.key.type&&function(e,t){var i=t.key.name,r=e[i],n="true";return"MethodDefinition"===t.type&&("get"===t.kind||"set"===t.kind)&&(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[i]="true",!1):!!r||(e[i]=n,!1)}(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=i,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},lU.parseClassElement=function(e){if(this.eat(l_.semi))return null;var t=this.options.ecmaVersion,i=this.startNode(),r="",n=!1,s=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(l_.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===l_.star?o=!0:r="static"}if(i.static=o,!r&&t>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===l_.star)&&!this.canInsertSemicolon()?s=!0:r="async"),!r&&(t>=9||!s)&&this.eat(l_.star)&&(n=!0),!r&&!s&&!n){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=l:r=l)}if(r?(i.computed=!1,i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),i.key.name=r,this.finishNode(i.key,"Identifier")):this.parseClassElementName(i),t<13||this.type===l_.parenL||"method"!==a||n||s){var h=!i.static&&lZ(i,"constructor");h&&"method"!==a&&this.raise(i.key.start,"Constructor can't have get/set modifier"),i.kind=h?"constructor":a,this.parseClassMethod(i,n,s,h&&e)}else this.parseClassField(i);return i},lU.isClassElementNameStart=function(){return this.type===l_.name||this.type===l_.privateId||this.type===l_.num||this.type===l_.string||this.type===l_.bracketL||this.type.keyword},lU.parseClassElementName=function(e){this.type===l_.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},lU.parseClassMethod=function(e,t,i,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method")):e.static&&lZ(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var s=e.value=this.parseMethod(t,i,r);return"get"===e.kind&&0!==s.params.length&&this.raiseRecoverable(s.start,"getter should have no params"),"set"===e.kind&&1!==s.params.length&&this.raiseRecoverable(s.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===s.params[0].type&&this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},lU.parseClassField=function(e){return lZ(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&lZ(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(l_.eq)?(this.enterScope(576),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")},lU.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==l_.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},lU.parseClassId=function(e,t){this.type===l_.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},lU.parseClassSuper=function(e){e.superClass=this.eat(l_._extends)?this.parseExprSubscripts(null,!1):null},lU.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},lU.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,i=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],s=0;s<i.length;++s){var a=i[s];lk(t,a.name)||(n?n.used.push(a):this.raiseRecoverable(a.start,"Private field '#"+a.name+"' must be declared in an enclosing class"))}},lU.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==l_.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},lU.parseExport=function(e,t){if(this.next(),this.eat(l_.star))return this.parseExportAllDeclaration(e,t);if(this.eat(l_._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==l_.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var i=0,r=e.specifiers;i<r.length;i+=1){var n=r[i];this.checkUnreserved(n.local),this.checkLocalExport(n.local),"Literal"===n.local.type&&this.raise(n.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")},lU.parseExportDeclaration=function(e){return this.parseStatement(null)},lU.parseExportDefaultDeclaration=function(){if(this.type===l_._function||(e=this.isAsyncFunction())){var e,t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,4|lH,!1,e)}if(this.type===l_._class){var i=this.startNode();return this.parseClass(i,"nullableID")}var r=this.parseMaybeAssign();return this.semicolon(),r},lU.checkExport=function(e,t,i){e&&("string"!=typeof t&&(t="Identifier"===t.type?t.name:t.value),lk(e,t)&&this.raiseRecoverable(i,"Duplicate export '"+t+"'"),e[t]=!0)},lU.checkPatternExport=function(e,t){var i=t.type;if("Identifier"===i)this.checkExport(e,t,t.start);else if("ObjectPattern"===i)for(var r=0,n=t.properties;r<n.length;r+=1){var s=n[r];this.checkPatternExport(e,s)}else if("ArrayPattern"===i)for(var a=0,o=t.elements;a<o.length;a+=1){var l=o[a];l&&this.checkPatternExport(e,l)}else"Property"===i?this.checkPatternExport(e,t.value):"AssignmentPattern"===i?this.checkPatternExport(e,t.left):"RestElement"===i&&this.checkPatternExport(e,t.argument)},lU.checkVariableExport=function(e,t){if(e)for(var i=0;i<t.length;i+=1){var r=t[i];this.checkPatternExport(e,r.id)}},lU.shouldParseExportStatement=function(){return"var"===this.type.keyword||"const"===this.type.keyword||"class"===this.type.keyword||"function"===this.type.keyword||this.isLet()||this.isAsyncFunction()},lU.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual("as")?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,"ExportSpecifier")},lU.parseExportSpecifiers=function(e){var t=[],i=!0;for(this.expect(l_.braceL);!this.eat(l_.braceR);){if(i)i=!1;else if(this.expect(l_.comma),this.afterTrailingComma(l_.braceR))break;t.push(this.parseExportSpecifier(e))}return t},lU.parseImport=function(e){return this.next(),this.type===l_.string?(e.specifiers=lG,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),e.source=this.type===l_.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},lU.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},lU.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},lU.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},lU.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===l_.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(l_.comma)))return e;if(this.type===l_.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(l_.braceL);!this.eat(l_.braceR);){if(t)t=!1;else if(this.expect(l_.comma),this.afterTrailingComma(l_.braceR))break;e.push(this.parseImportSpecifier())}return e},lU.parseWithClause=function(){var e=[];if(!this.eat(l_._with))return e;this.expect(l_.braceL);for(var t={},i=!0;!this.eat(l_.braceR);){if(i)i=!1;else if(this.expect(l_.comma),this.afterTrailingComma(l_.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;lk(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},lU.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===l_.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(l_.colon),this.type!==l_.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},lU.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===l_.string){var e=this.parseLiteral(this.value);return lP.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},lU.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},lU.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var lJ=lL.prototype;lJ.toAssignable=function(e,t,i){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var r=0,n=e.properties;r<n.length;r+=1){var s=n[r];this.toAssignable(s,t),"RestElement"===s.type&&("ArrayPattern"===s.argument.type||"ObjectPattern"===s.argument.type)&&this.raise(s.argument.start,"Unexpected token")}break;case"Property":"init"!==e.kind&&this.raise(e.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(e.value,t);break;case"ArrayExpression":e.type="ArrayPattern",i&&this.checkPatternErrors(i,!0),this.toAssignableList(e.elements,t);break;case"SpreadElement":e.type="RestElement",this.toAssignable(e.argument,t),"AssignmentPattern"===e.argument.type&&this.raise(e.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":"="!==e.operator&&this.raise(e.left.end,"Only '=' operator can be used for specifying default value."),e.type="AssignmentPattern",delete e.operator,this.toAssignable(e.left,t);break;case"ParenthesizedExpression":this.toAssignable(e.expression,t,i);break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!t)break;default:this.raise(e.start,"Assigning to rvalue")}else i&&this.checkPatternErrors(i,!0);return e},lJ.toAssignableList=function(e,t){for(var i=e.length,r=0;r<i;r++){var n=e[r];n&&this.toAssignable(n,t)}if(i){var s=e[i-1];6===this.options.ecmaVersion&&t&&s&&"RestElement"===s.type&&"Identifier"!==s.argument.type&&this.unexpected(s.argument.start)}return e},lJ.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,"SpreadElement")},lJ.parseRestBinding=function(){var e=this.startNode();return this.next(),6===this.options.ecmaVersion&&this.type!==l_.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,"RestElement")},lJ.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case l_.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(l_.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case l_.braceL:return this.parseObj(!0)}return this.parseIdent()},lJ.parseBindingList=function(e,t,i,r){for(var n=[],s=!0;!this.eat(e);)if(s?s=!1:this.expect(l_.comma),t&&this.type===l_.comma)n.push(null);else{if(i&&this.afterTrailingComma(e))break;if(this.type===l_.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),n.push(a),this.type===l_.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(e);break}n.push(this.parseAssignableListItem(r))}return n},lJ.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},lJ.parseBindingListItem=function(e){return e},lJ.parseMaybeDefault=function(e,t,i){if(i=i||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(l_.eq))return i;var r=this.startNodeAt(e,t);return r.left=i,r.right=this.parseMaybeAssign(),this.finishNode(r,"AssignmentPattern")},lJ.checkLValSimple=function(e,t,i){void 0===t&&(t=0);var r=0!==t;switch(e.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(r?"Binding ":"Assigning to ")+e.name+" in strict mode"),r&&(2===t&&"let"===e.name&&this.raiseRecoverable(e.start,"let is disallowed as a lexically bound name"),i&&(lk(i,e.name)&&this.raiseRecoverable(e.start,"Argument name clash"),i[e.name]=!0),5!==t&&this.declareName(e.name,t,e.start));break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":r&&this.raiseRecoverable(e.start,"Binding member expression");break;case"ParenthesizedExpression":return r&&this.raiseRecoverable(e.start,"Binding parenthesized expression"),this.checkLValSimple(e.expression,t,i);default:this.raise(e.start,(r?"Binding":"Assigning to")+" rvalue")}},lJ.checkLValPattern=function(e,t,i){switch(void 0===t&&(t=0),e.type){case"ObjectPattern":for(var r=0,n=e.properties;r<n.length;r+=1){var s=n[r];this.checkLValInnerPattern(s,t,i)}break;case"ArrayPattern":for(var a=0,o=e.elements;a<o.length;a+=1){var l=o[a];l&&this.checkLValInnerPattern(l,t,i)}break;default:this.checkLValSimple(e,t,i)}},lJ.checkLValInnerPattern=function(e,t,i){switch(void 0===t&&(t=0),e.type){case"Property":this.checkLValInnerPattern(e.value,t,i);break;case"AssignmentPattern":this.checkLValPattern(e.left,t,i);break;case"RestElement":this.checkLValPattern(e.argument,t,i);break;default:this.checkLValPattern(e,t,i)}};var lQ=function(e,t,i,r,n){this.token=e,this.isExpr=!!t,this.preserveSpace=!!i,this.override=r,this.generator=!!n},lX={b_stat:new lQ("{",!1),b_expr:new lQ("{",!0),b_tmpl:new lQ("${",!1),p_stat:new lQ("(",!1),p_expr:new lQ("(",!0),q_tmpl:new lQ("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new lQ("function",!1),f_expr:new lQ("function",!0),f_expr_gen:new lQ("function",!0,!1,null,!0),f_gen:new lQ("function",!1,!1,null,!0)},l0=lL.prototype;l0.initialContext=function(){return[lX.b_stat]},l0.curContext=function(){return this.context[this.context.length-1]},l0.braceIsBlock=function(e){var t=this.curContext();return t===lX.f_expr||t===lX.f_stat||(e===l_.colon&&(t===lX.b_stat||t===lX.b_expr)?!t.isExpr:e===l_._return||e===l_.name&&this.exprAllowed?lg.test(this.input.slice(this.lastTokEnd,this.start)):e===l_._else||e===l_.semi||e===l_.eof||e===l_.parenR||e===l_.arrow||(e===l_.braceL?t===lX.b_stat:e!==l_._var&&e!==l_._const&&e!==l_.name&&!this.exprAllowed))},l0.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},l0.updateContext=function(e){var t,i=this.type;i.keyword&&e===l_.dot?this.exprAllowed=!1:(t=i.updateContext)?t.call(this,e):this.exprAllowed=i.beforeExpr},l0.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},l_.parenR.updateContext=l_.braceR.updateContext=function(){if(1===this.context.length){this.exprAllowed=!0;return}var e=this.context.pop();e===lX.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},l_.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?lX.b_stat:lX.b_expr),this.exprAllowed=!0},l_.dollarBraceL.updateContext=function(){this.context.push(lX.b_tmpl),this.exprAllowed=!0},l_.parenL.updateContext=function(e){var t=e===l_._if||e===l_._for||e===l_._with||e===l_._while;this.context.push(t?lX.p_stat:lX.p_expr),this.exprAllowed=!0},l_.incDec.updateContext=function(){},l_._function.updateContext=l_._class.updateContext=function(e){e.beforeExpr&&e!==l_._else&&(e!==l_.semi||this.curContext()===lX.p_stat)&&!(e===l_._return&&lg.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==l_.colon&&e!==l_.braceL||this.curContext()!==lX.b_stat)?this.context.push(lX.f_expr):this.context.push(lX.f_stat),this.exprAllowed=!1},l_.colon.updateContext=function(){"function"===this.curContext().token&&this.context.pop(),this.exprAllowed=!0},l_.backQuote.updateContext=function(){this.curContext()===lX.q_tmpl?this.context.pop():this.context.push(lX.q_tmpl),this.exprAllowed=!1},l_.star.updateContext=function(e){if(e===l_._function){var t=this.context.length-1;this.context[t]===lX.f_expr?this.context[t]=lX.f_expr_gen:this.context[t]=lX.f_gen}this.exprAllowed=!0},l_.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==l_.dot&&("of"===this.value&&!this.exprAllowed||"yield"===this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var l1=lL.prototype;l1.checkPropClash=function(e,t,i){if(!(this.options.ecmaVersion>=9&&"SpreadElement"===e.type)&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var r,n=e.key;switch(n.type){case"Identifier":r=n.name;break;case"Literal":r=String(n.value);break;default:return}var s=e.kind;if(this.options.ecmaVersion>=6){"__proto__"===r&&"init"===s&&(t.proto&&(i?i.doubleProto<0&&(i.doubleProto=n.start):this.raiseRecoverable(n.start,"Redefinition of __proto__ property")),t.proto=!0);return}var a=t[r="$"+r];a?("init"===s?this.strict&&a.init||a.get||a.set:a.init||a[s])&&this.raiseRecoverable(n.start,"Redefinition of property"):a=t[r]={init:!1,get:!1,set:!1},a[s]=!0}},l1.parseExpression=function(e,t){var i=this.start,r=this.startLoc,n=this.parseMaybeAssign(e,t);if(this.type===l_.comma){var s=this.startNodeAt(i,r);for(s.expressions=[n];this.eat(l_.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(s,"SequenceExpression")}return n},l1.parseMaybeAssign=function(e,t,i){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var r=!1,n=-1,s=-1,a=-1;t?(n=t.parenthesizedAssign,s=t.trailingComma,a=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new lz,r=!0);var o=this.start,l=this.startLoc;(this.type===l_.parenL||this.type===l_.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait="await"===e);var h=this.parseMaybeConditional(e,t);if(i&&(h=i.call(this,h,o,l)),this.type.isAssign){var c=this.startNodeAt(o,l);return c.operator=this.value,this.type===l_.eq&&(h=this.toAssignable(h,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=h.start&&(t.shorthandAssign=-1),this.type===l_.eq?this.checkLValPattern(h):this.checkLValSimple(h),c.left=h,this.next(),c.right=this.parseMaybeAssign(e),a>-1&&(t.doubleProto=a),this.finishNode(c,"AssignmentExpression")}return r&&this.checkExpressionErrors(t,!0),n>-1&&(t.parenthesizedAssign=n),s>-1&&(t.trailingComma=s),h},l1.parseMaybeConditional=function(e,t){var i=this.start,r=this.startLoc,n=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return n;if(this.eat(l_.question)){var s=this.startNodeAt(i,r);return s.test=n,s.consequent=this.parseMaybeAssign(),this.expect(l_.colon),s.alternate=this.parseMaybeAssign(e),this.finishNode(s,"ConditionalExpression")}return n},l1.parseExprOps=function(e,t){var i=this.start,r=this.startLoc,n=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||n.start===i&&"ArrowFunctionExpression"===n.type?n:this.parseExprOp(n,i,r,-1,e)},l1.parseExprOp=function(e,t,i,r,n){var s=this.type.binop;if(null!=s&&(!n||this.type!==l_._in)&&s>r){var a=this.type===l_.logicalOR||this.type===l_.logicalAND,o=this.type===l_.coalesce;o&&(s=l_.logicalAND.binop);var l=this.value;this.next();var h=this.start,c=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,n),h,c,s,n),u=this.buildBinary(t,i,e,p,l,a||o);return(a&&this.type===l_.coalesce||o&&(this.type===l_.logicalOR||this.type===l_.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(u,t,i,r,n)}return e},l1.buildBinary=function(e,t,i,r,n,s){"PrivateIdentifier"===r.type&&this.raise(r.start,"Private identifier can only be left side of binary expression");var a=this.startNodeAt(e,t);return a.left=i,a.operator=n,a.right=r,this.finishNode(a,s?"LogicalExpression":"BinaryExpression")},l1.parseMaybeUnary=function(e,t,i,r){var n,s=this.start,a=this.startLoc;if(this.isContextual("await")&&this.canAwait)n=this.parseAwait(r),t=!0;else if(this.type.prefix){var o=this.startNode(),l=this.type===l_.incDec;o.operator=this.value,o.prefix=!0,this.next(),o.argument=this.parseMaybeUnary(null,!0,l,r),this.checkExpressionErrors(e,!0),l?this.checkLValSimple(o.argument):this.strict&&"delete"===o.operator&&function e(t){return"Identifier"===t.type||"ParenthesizedExpression"===t.type&&e(t.expression)}(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):"delete"===o.operator&&function e(t){return"MemberExpression"===t.type&&"PrivateIdentifier"===t.property.type||"ChainExpression"===t.type&&e(t.expression)||"ParenthesizedExpression"===t.type&&e(t.expression)}(o.argument)?this.raiseRecoverable(o.start,"Private fields can not be deleted"):t=!0,n=this.finishNode(o,l?"UpdateExpression":"UnaryExpression")}else if(t||this.type!==l_.privateId){if(n=this.parseExprSubscripts(e,r),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var h=this.startNodeAt(s,a);h.operator=this.value,h.prefix=!1,h.argument=n,this.checkLValSimple(n),this.next(),n=this.finishNode(h,"UpdateExpression")}}else(r||0===this.privateNameStack.length)&&this.options.checkPrivateFields&&this.unexpected(),n=this.parsePrivateIdent(),this.type!==l_._in&&this.unexpected();return!i&&this.eat(l_.starstar)?t?void this.unexpected(this.lastTokStart):this.buildBinary(s,a,n,this.parseMaybeUnary(null,!1,!1,r),"**",!1):n},l1.parseExprSubscripts=function(e,t){var i=this.start,r=this.startLoc,n=this.parseExprAtom(e,t);if("ArrowFunctionExpression"===n.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd))return n;var s=this.parseSubscripts(n,i,r,!1,t);return e&&"MemberExpression"===s.type&&(e.parenthesizedAssign>=s.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=s.start&&(e.parenthesizedBind=-1),e.trailingComma>=s.start&&(e.trailingComma=-1)),s},l1.parseSubscripts=function(e,t,i,r,n){for(var s=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.potentialArrowAt===e.start,a=!1;;){var o=this.parseSubscript(e,t,i,r,s,a,n);if(o.optional&&(a=!0),o===e||"ArrowFunctionExpression"===o.type){if(a){var l=this.startNodeAt(t,i);l.expression=o,o=this.finishNode(l,"ChainExpression")}return o}e=o}},l1.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(l_.arrow)},l1.parseSubscriptAsyncArrow=function(e,t,i,r){return this.parseArrowExpression(this.startNodeAt(e,t),i,!0,r)},l1.parseSubscript=function(e,t,i,r,n,s,a){var o=this.options.ecmaVersion>=11,l=o&&this.eat(l_.questionDot);r&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var h=this.eat(l_.bracketL);if(h||l&&this.type!==l_.parenL&&this.type!==l_.backQuote||this.eat(l_.dot)){var c=this.startNodeAt(t,i);c.object=e,h?(c.property=this.parseExpression(),this.expect(l_.bracketR)):this.type===l_.privateId&&"Super"!==e.type?c.property=this.parsePrivateIdent():c.property=this.parseIdent("never"!==this.options.allowReserved),c.computed=!!h,o&&(c.optional=l),e=this.finishNode(c,"MemberExpression")}else if(!r&&this.eat(l_.parenL)){var p=new lz,u=this.yieldPos,d=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var f=this.parseExprList(l_.parenR,this.options.ecmaVersion>=8,!1,p);if(n&&!l&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=u,this.awaitPos=d,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,i,f,a);this.checkExpressionErrors(p,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=d||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var y=this.startNodeAt(t,i);y.callee=e,y.arguments=f,o&&(y.optional=l),e=this.finishNode(y,"CallExpression")}else if(this.type===l_.backQuote){(l||s)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var _=this.startNodeAt(t,i);_.tag=e,_.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(_,"TaggedTemplateExpression")}return e},l1.parseExprAtom=function(e,t,i){this.type===l_.slash&&this.readRegexp();var r,n=this.potentialArrowAt===this.start;switch(this.type){case l_._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),r=this.startNode(),this.next(),this.type!==l_.parenL||this.allowDirectSuper||this.raise(r.start,"super() call outside constructor of a subclass"),this.type!==l_.dot&&this.type!==l_.bracketL&&this.type!==l_.parenL&&this.unexpected(),this.finishNode(r,"Super");case l_._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case l_.name:var s=this.start,a=this.startLoc,o=this.containsEsc,l=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!o&&"async"===l.name&&!this.canInsertSemicolon()&&this.eat(l_._function))return this.overrideContext(lX.f_expr),this.parseFunction(this.startNodeAt(s,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(l_.arrow))return this.parseArrowExpression(this.startNodeAt(s,a),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===l_.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(l_.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,a),[l],!0,t)}return l;case l_.regexp:var h=this.value;return(r=this.parseLiteral(h.value)).regex={pattern:h.pattern,flags:h.flags},r;case l_.num:case l_.string:return this.parseLiteral(this.value);case l_._null:case l_._true:case l_._false:return(r=this.startNode()).value=this.type===l_._null?null:this.type===l_._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case l_.parenL:var c=this.start,p=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=c),e.parenthesizedBind<0&&(e.parenthesizedBind=c)),p;case l_.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(l_.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case l_.braceL:return this.overrideContext(lX.b_expr),this.parseObj(!1,e);case l_._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case l_._class:return this.parseClass(this.startNode(),!1);case l_._new:return this.parseNew();case l_.backQuote:return this.parseTemplate();case l_._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},l1.parseExprAtomDefault=function(){this.unexpected()},l1.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===l_.parenL&&!e)return this.parseDynamicImport(t);if(this.type===l_.dot){var i=this.startNodeAt(t.start,t.loc&&t.loc.start);return i.name="import",t.meta=this.finishNode(i,"Identifier"),this.parseImportMeta(t)}this.unexpected()},l1.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(l_.parenR)?e.options=null:(this.expect(l_.comma),this.afterTrailingComma(l_.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(l_.parenR)||(this.expect(l_.comma),this.afterTrailingComma(l_.parenR)||this.unexpected())));else if(!this.eat(l_.parenR)){var t=this.start;this.eat(l_.comma)&&this.eat(l_.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},l1.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},l1.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=null!=t.value?t.value.toString():t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},l1.parseParenExpression=function(){this.expect(l_.parenL);var e=this.parseExpression();return this.expect(l_.parenR),e},l1.shouldParseArrow=function(e){return!this.canInsertSemicolon()},l1.parseParenAndDistinguishExpression=function(e,t){var i,r=this.start,n=this.startLoc,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,l=this.startLoc,h=[],c=!0,p=!1,u=new lz,d=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==l_.parenR;)if(c?c=!1:this.expect(l_.comma),s&&this.afterTrailingComma(l_.parenR,!0)){p=!0;break}else if(this.type===l_.ellipsis){a=this.start,h.push(this.parseParenItem(this.parseRestBinding())),this.type===l_.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else h.push(this.parseMaybeAssign(!1,u,this.parseParenItem));var f=this.lastTokEnd,y=this.lastTokEndLoc;if(this.expect(l_.parenR),e&&this.shouldParseArrow(h)&&this.eat(l_.arrow))return this.checkPatternErrors(u,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=m,this.parseParenArrowList(r,n,h,t);(!h.length||p)&&this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(u,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=m||this.awaitPos,h.length>1?((i=this.startNodeAt(o,l)).expressions=h,this.finishNodeAt(i,"SequenceExpression",f,y)):i=h[0]}else i=this.parseParenExpression();if(!this.options.preserveParens)return i;var _=this.startNodeAt(r,n);return _.expression=i,this.finishNode(_,"ParenthesizedExpression")},l1.parseParenItem=function(e){return e},l1.parseParenArrowList=function(e,t,i,r){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,r)};var l2=[];l1.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===l_.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var i=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),i&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(l_.parenL)?e.arguments=this.parseExprList(l_.parenR,this.options.ecmaVersion>=8,!1):e.arguments=l2,this.finishNode(e,"NewExpression")},l1.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===l_.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value.replace(/\r\n?/g,`
300
+ `),cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
301
+ `),cooked:this.value},this.next(),i.tail=this.type===l_.backQuote,this.finishNode(i,"TemplateElement")},l1.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var i=this.startNode();this.next(),i.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(i.quasis=[r];!r.tail;)this.type===l_.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(l_.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(l_.braceR),i.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},l1.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===l_.name||this.type===l_.num||this.type===l_.string||this.type===l_.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===l_.star)&&!lg.test(this.input.slice(this.lastTokEnd,this.start))},l1.parseObj=function(e,t){var i=this.startNode(),r=!0,n={};for(i.properties=[],this.next();!this.eat(l_.braceR);){if(r)r=!1;else if(this.expect(l_.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(l_.braceR))break;var s=this.parseProperty(e,t);e||this.checkPropClash(s,n,t),i.properties.push(s)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")},l1.parseProperty=function(e,t){var i,r,n,s,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(l_.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===l_.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===l_.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,s=this.startLoc),e||(i=this.eat(l_.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(a)?(r=!0,i=this.options.ecmaVersion>=9&&this.eat(l_.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,i,r,n,s,t,o),this.finishNode(a,"Property")},l1.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var i=+("get"!==e.kind);if(e.value.params.length!==i){var r=e.value.start;"get"===e.kind?this.raiseRecoverable(r,"getter should have no params"):this.raiseRecoverable(r,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},l1.parsePropertyValue=function(e,t,i,r,n,s,a,o){(i||r)&&this.type===l_.colon&&this.unexpected(),this.eat(l_.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===l_.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(i,r),e.kind="init"):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===l_.comma||this.type===l_.braceR||this.type===l_.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((i||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),t?e.value=this.parseMaybeDefault(n,s,this.copyNode(e.key)):this.type===l_.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,s,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected():((i||r)&&this.unexpected(),this.parseGetterSetter(e))},l1.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(l_.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(l_.bracketR),e.key;e.computed=!1}return e.key=this.type===l_.num||this.type===l_.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},l1.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},l1.parseMethod=function(e,t,i){var r=this.startNode(),n=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|l$(t,r.generator)|128*!!i),this.expect(l_.parenL),r.params=this.parseBindingList(l_.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},l1.parseArrowExpression=function(e,t,i,r){var n=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|l$(i,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!i),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},l1.parseFunctionBody=function(e,t,i,r){var n=t&&this.type!==l_.braceL,s=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!s||o)&&(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var l=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!s&&!a&&!t&&!i&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!s),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=l}this.exitScope()},l1.isSimpleParamList=function(e){for(var t=0;t<e.length;t+=1)if("Identifier"!==e[t].type)return!1;return!0},l1.checkParams=function(e,t){for(var i=Object.create(null),r=0,n=e.params;r<n.length;r+=1){var s=n[r];this.checkLValInnerPattern(s,1,t?null:i)}},l1.parseExprList=function(e,t,i,r){for(var n=[],s=!0;!this.eat(e);){if(s)s=!1;else if(this.expect(l_.comma),t&&this.afterTrailingComma(e))break;var a=void 0;i&&this.type===l_.comma?a=null:this.type===l_.ellipsis?(a=this.parseSpread(r),r&&this.type===l_.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):a=this.parseMaybeAssign(!1,r),n.push(a)}return n},l1.checkUnreserved=function(e){var t=e.start,i=e.end,r=e.name;this.inGenerator&&"yield"===r&&this.raiseRecoverable(t,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&"await"===r&&this.raiseRecoverable(t,"Cannot use 'await' as identifier inside an async function"),259&this.currentThisScope().flags||"arguments"!==r||this.raiseRecoverable(t,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&("arguments"===r||"await"===r)&&this.raise(t,"Cannot use "+r+" in class static initialization block"),this.keywords.test(r)&&this.raise(t,"Unexpected keyword '"+r+"'"),!(this.options.ecmaVersion<6&&-1!==this.input.slice(t,i).indexOf("\\"))&&(this.strict?this.reservedWordsStrict:this.reservedWords).test(r)&&(this.inAsync||"await"!==r||this.raiseRecoverable(t,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(t,"The keyword '"+r+"' is reserved"))},l1.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,"Identifier"),e||(this.checkUnreserved(t),"await"!==t.name||this.awaitIdentPos||(this.awaitIdentPos=t.start)),t},l1.parseIdentNode=function(){var e=this.startNode();return this.type===l_.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,("class"===e.name||"function"===e.name)&&(this.lastTokEnd!==this.lastTokStart+1||46!==this.input.charCodeAt(this.lastTokStart))&&this.context.pop(),this.type=l_.name):this.unexpected(),e},l1.parsePrivateIdent=function(){var e=this.startNode();return this.type===l_.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,"PrivateIdentifier"),this.options.checkPrivateFields&&(0===this.privateNameStack.length?this.raise(e.start,"Private field '#"+e.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e},l1.parseYield=function(e){this.yieldPos||(this.yieldPos=this.start);var t=this.startNode();return this.next(),this.type===l_.semi||this.canInsertSemicolon()||this.type!==l_.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(l_.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,"YieldExpression")},l1.parseAwait=function(e){this.awaitPos||(this.awaitPos=this.start);var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,"AwaitExpression")};var l3=lL.prototype;l3.raise=function(e,t){var i=lO(this.input,e);t+=" ("+i.line+":"+i.column+")",this.sourceFile&&(t+=" in "+this.sourceFile);var r=SyntaxError(t);throw r.pos=e,r.loc=i,r.raisedAt=this.pos,r},l3.raiseRecoverable=l3.raise,l3.curPosition=function(){if(this.options.locations)return new lD(this.curLine,this.pos-this.lineStart)};var l4=lL.prototype,l6=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};l4.enterScope=function(e){this.scopeStack.push(new l6(e))},l4.exitScope=function(){this.scopeStack.pop()},l4.treatFunctionsAsVarInScope=function(e){return 2&e.flags||!this.inModule&&1&e.flags},l4.declareName=function(e,t,i){var r=!1;if(2===t){var n=this.currentScope();r=n.lexical.indexOf(e)>-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var s=this.currentScope();r=this.treatFunctionsAsVar?s.lexical.indexOf(e)>-1:s.lexical.indexOf(e)>-1||s.var.indexOf(e)>-1,s.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")},l4.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},l4.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},l4.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags)return t}},l4.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags&&!(16&t.flags))return t}};var l5=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new lR(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},l9=lL.prototype;function l8(e,t,i,r){return e.type=t,e.end=i,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=i),e}l9.startNode=function(){return new l5(this,this.start,this.startLoc)},l9.startNodeAt=function(e,t){return new l5(this,e,t)},l9.finishNode=function(e,t){return l8.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},l9.finishNodeAt=function(e,t,i,r){return l8.call(this,e,t,i,r)},l9.copyNode=function(e){var t=new l5(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};for(var l7="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",he=l7+" Extended_Pictographic",ht=he+" EBase EComp EMod EPres ExtPict",hi={9:l7,10:he,11:he,12:ht,13:ht,14:ht},hr={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},hn="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",hs="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",ha=hs+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",ho=ha+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",hl=ho+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",hh=hl+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",hc={9:hs,10:ha,11:ho,12:hl,13:hh,14:hh+" Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz"},hp={},hu=0,hd=[9,10,11,12,13,14];hu<hd.length;hu+=1)!function(e){var t=hp[e]={binary:lC(hi[e]+" "+hn),binaryOfStrings:lC(hr[e]),nonBinary:{General_Category:lC(hn),Script:lC(hc[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}(hd[hu]);var hm=lL.prototype,hf=function(e,t){this.parent=e,this.base=t||this};hf.prototype.separatedFrom=function(e){for(var t=this;t;t=t.parent)for(var i=e;i;i=i.parent)if(t.base===i.base&&t!==i)return!0;return!1},hf.prototype.sibling=function(){return new hf(this.parent,this.base)};var hy=function(e){this.parser=e,this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=hp[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function h_(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function hg(e){return e>=65&&e<=90||e>=97&&e<=122}function hx(e){return hg(e)||95===e}function hb(e){return e>=48&&e<=57}function hv(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hw(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}function hS(e){return e>=48&&e<=55}hy.prototype.reset=function(e,t,i){var r=-1!==i.indexOf("v"),n=-1!==i.indexOf("u");this.start=0|e,this.source=t+"",this.flags=i,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},hy.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},hy.prototype.at=function(e,t){void 0===t&&(t=!1);var i=this.source,r=i.length;if(e>=r)return -1;var n=i.charCodeAt(e);if(!(t||this.switchU)||n<=55295||n>=57344||e+1>=r)return n;var s=i.charCodeAt(e+1);return s>=56320&&s<=57343?(n<<10)+s-0x35fdc00:n},hy.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var i=this.source,r=i.length;if(e>=r)return r;var n,s=i.charCodeAt(e);return!(t||this.switchU)||s<=55295||s>=57344||e+1>=r||(n=i.charCodeAt(e+1))<56320||n>57343?e+1:e+2},hy.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},hy.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},hy.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},hy.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},hy.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var i=this.pos,r=0;r<e.length;r+=1){var n=e[r],s=this.at(i,t);if(-1===s||s!==n)return!1;i=this.nextIndex(i,t)}return this.pos=i,!0},hm.validateRegExpFlags=function(e){for(var t=e.validFlags,i=e.flags,r=!1,n=!1,s=0;s<i.length;s++){var a=i.charAt(s);-1===t.indexOf(a)&&this.raise(e.start,"Invalid regular expression flag"),i.indexOf(a,s+1)>-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},hm.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},hm.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,i=e.backReferenceNames;t<i.length;t+=1){var r=i[t];e.groupNames[r]||e.raise("Invalid named capture referenced")}},hm.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new hf(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},hm.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},hm.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise("Invalid quantifier"),!0):(e.switchU?!!this.regexp_eatAtom(e):!!this.regexp_eatExtendedAtom(e))&&(this.regexp_eatQuantifier(e),!0)},hm.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var i=!1;if(this.options.ecmaVersion>=9&&(i=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!i,!0}return e.pos=t,!1},hm.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},hm.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},hm.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return -1!==n&&n<r&&!t&&e.raise("numbers out of order in {} quantifier"),!0;e.switchU&&!t&&e.raise("Incomplete quantifier"),e.pos=i}return!1},hm.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)},hm.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},hm.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var i=this.regexp_eatModifiers(e),r=e.eat(45);if(i||r){for(var n=0;n<i.length;n++){var s=i.charAt(n);i.indexOf(s,n+1)>-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);i||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o<a.length;o++){var l=a.charAt(o);(a.indexOf(l,o+1)>-1||i.indexOf(l)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},hm.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},hm.regexp_eatModifiers=function(e){for(var t,i="",r=0;-1!==(r=e.current())&&(105===(t=r)||109===t||115===t);)i+=lM(r),e.advance();return i},hm.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},hm.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},hm.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!h_(t)&&(e.lastIntValue=t,e.advance(),!0)},hm.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!h_(i);)e.advance();return e.pos!==t},hm.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return -1!==t&&36!==t&&(!(t>=40)||!(t<=43))&&46!==t&&63!==t&&91!==t&&94!==t&&124!==t&&(e.advance(),!0)},hm.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,i=e.groupNames[e.lastStringValue];if(i)if(t)for(var r=0;r<i.length;r+=1)i[r].separatedFrom(e.branchID)||e.raise("Duplicate capture group name");else e.raise("Duplicate capture group name");t?(i||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}},hm.regexp_eatGroupName=function(e){if(e.lastStringValue="",e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise("Invalid capture group name")}return!1},hm.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue="",this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=lM(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=lM(e.lastIntValue);return!0}return!1},hm.regexp_eatRegExpIdentifierStart=function(e){var t,i=e.pos,r=this.options.ecmaVersion>=11,n=e.current(r);return e.advance(r),92===n&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),lh(t=n,!0)||36===t||95===t?(e.lastIntValue=n,!0):(e.pos=i,!1)},hm.regexp_eatRegExpIdentifierPart=function(e){var t,i=e.pos,r=this.options.ecmaVersion>=11,n=e.current(r);return e.advance(r),92===n&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),lc(t=n,!0)||36===t||95===t||8204===t||8205===t?(e.lastIntValue=n,!0):(e.pos=i,!1)},hm.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},hm.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU)return i>e.maxBackReference&&(e.maxBackReference=i),!0;if(i<=e.numCapturingParens)return!0;e.pos=t}return!1},hm.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},hm.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},hm.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},hm.regexp_eatZero=function(e){return!(48!==e.current()||hb(e.lookahead()))&&(e.lastIntValue=0,e.advance(),!0)},hm.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},hm.regexp_eatControlLetter=function(e){var t=e.current();return!!hg(t)&&(e.lastIntValue=t%32,e.advance(),!0)},hm.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var i=e.pos,r=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var n,s=e.lastIntValue;if(r&&s>=55296&&s<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(s-55296)*1024+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=s}return!0}if(r&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(n=e.lastIntValue)>=0&&n<=1114111)return!0;r&&e.raise("Invalid unicode escape"),e.pos=i}return!1},hm.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return 99!==t&&(!e.switchN||107!==t)&&(e.lastIntValue=t,e.advance(),!0)},hm.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1},hm.regexp_eatCharacterClassEscape=function(e){var t,i,r=e.current();if(100===(t=r)||68===t||115===t||83===t||119===t||87===t)return e.lastIntValue=-1,e.advance(),1;var n=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((n=80===r)||112===r)){if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(i=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return n&&2===i&&e.raise("Invalid property name"),i;e.raise("Invalid property name")}return 0},hm.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,i,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},hm.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){lk(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},hm.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},hm.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";hx(t=e.current());)e.lastStringValue+=lM(t),e.advance();return""!==e.lastStringValue},hm.regexp_eatUnicodePropertyValue=function(e){var t,i=0;for(e.lastStringValue="";hx(t=i=e.current())||hb(t);)e.lastStringValue+=lM(i),e.advance();return""!==e.lastStringValue},hm.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},hm.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),i=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===i&&e.raise("Negated character class may contain strings"),!0}return!1},hm.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},hm.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;e.switchU&&(-1===t||-1===i)&&e.raise("Invalid character class"),-1!==t&&-1!==i&&t>i&&e.raise("Range out of order in character class")}}},hm.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var i=e.current();(99===i||hS(i))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},hm.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},hm.regexp_classSetExpression=function(e){var t,i=1;if(!this.regexp_eatClassSetRange(e))if(t=this.regexp_eatClassSetOperand(e)){2===t&&(i=2);for(var r=e.pos;e.eatChars([38,38]);){if(38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))){2!==t&&(i=1);continue}e.raise("Invalid character in character class")}if(r!==e.pos)return i;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return i}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return i;2===t&&(i=2)}},hm.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return -1!==i&&-1!==r&&i>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},hm.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},hm.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var i=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return i&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},hm.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var i=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return i}else e.raise("Invalid escape");e.pos=t}return null},hm.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},hm.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},hm.regexp_eatClassSetCharacter=function(e){var t,i,r=e.pos;if(e.eat(92))return!!(this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=r,!1));var n=e.current();return!(n<0||n===e.lookahead()&&(33===(t=n)||t>=35&&t<=38||t>=42&&t<=44||46===t||t>=58&&t<=64||94===t||96===t||126===t)||40===(i=n)||41===i||45===i||47===i||i>=91&&i<=93||i>=123&&i<=125)&&(e.advance(),e.lastIntValue=n,!0)},hm.regexp_eatClassSetReservedPunctuator=function(e){var t,i=e.current();return!!(33===(t=i)||35===t||37===t||38===t||44===t||45===t||t>=58&&t<=62||64===t||96===t||126===t)&&(e.lastIntValue=i,e.advance(),!0)},hm.regexp_eatClassControlLetter=function(e){var t=e.current();return(!!hb(t)||95===t)&&(e.lastIntValue=t%32,e.advance(),!0)},hm.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},hm.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;hb(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},hm.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;hv(i=e.current());)e.lastIntValue=16*e.lastIntValue+hw(i),e.advance();return e.pos!==t},hm.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*i+e.lastIntValue:e.lastIntValue=8*t+i}else e.lastIntValue=t;return!0}return!1},hm.regexp_eatOctalDigit=function(e){var t=e.current();return hS(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},hm.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var r=0;r<t;++r){var n=e.current();if(!hv(n))return e.pos=i,!1;e.lastIntValue=16*e.lastIntValue+hw(n),e.advance()}return!0};var hE=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new lR(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},hN=lL.prototype;function hT(e){return"function"!=typeof BigInt?null:BigInt(e.replace(/_/g,""))}hN.next=function(e){!e&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new hE(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},hN.getToken=function(){return this.next(),new hE(this)},"u">typeof Symbol&&(hN[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===l_.eof,value:t}}}}),hN.nextToken=function(){var e=this.curContext();return(e&&e.preserveSpace||this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)?this.finishToken(l_.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},hN.readToken=function(e){return lh(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},hN.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var i=this.input.charCodeAt(e+1);return i<=56319||i>=57344?t:(t<<10)+i-0x35fdc00},hN.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},hN.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(-1===i&&this.raise(this.pos-2,"Unterminated comment"),this.pos=i+2,this.options.locations)for(var r=void 0,n=t;(r=lv(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,i),t,this.pos,e,this.curPosition())},hN.skipLineComment=function(e){for(var t=this.pos,i=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!lb(r);)r=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,i,this.curPosition())},hN.skipSpace=function(){e:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:10===this.input.charCodeAt(this.pos+1)&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break e}break;default:if(e>8&&e<14||e>=5760&&lw.test(String.fromCharCode(e)))++this.pos;else break e}}},hN.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var i=this.type;this.type=e,this.value=t,this.updateContext(i)},hN.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(l_.ellipsis)):(++this.pos,this.finishToken(l_.dot))},hN.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(l_.assign,2):this.finishOp(l_.slash,1)},hN.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,r=42===e?l_.star:l_.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,r=l_.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(l_.assign,i+1):this.finishOp(r,i)},hN.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e)return this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(l_.assign,3):this.finishOp(124===e?l_.logicalOR:l_.logicalAND,2);return 61===t?this.finishOp(l_.assign,2):this.finishOp(124===e?l_.bitwiseOR:l_.bitwiseAND,1)},hN.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(l_.assign,2):this.finishOp(l_.bitwiseXOR,1)},hN.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45===t&&!this.inModule&&62===this.input.charCodeAt(this.pos+2)&&(0===this.lastTokEnd||lg.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(l_.incDec,2):61===t?this.finishOp(l_.assign,2):this.finishOp(l_.plusMin,1)},hN.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),i=1;return t===e?(i=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+i)?this.finishOp(l_.assign,i+1):this.finishOp(l_.bitShift,i)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(i=2),this.finishOp(l_.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},hN.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(l_.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(l_.arrow)):this.finishOp(61===e?l_.eq:l_.prefix,1)},hN.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57)return this.finishOp(l_.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(l_.assign,3):this.finishOp(l_.coalesce,2)}return this.finishOp(l_.question,1)},hN.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,lh(t=this.fullCharCodeAtPos(),!0)||92===t))return this.finishToken(l_.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+lM(t)+"'")},hN.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(l_.parenL);case 41:return++this.pos,this.finishToken(l_.parenR);case 59:return++this.pos,this.finishToken(l_.semi);case 44:return++this.pos,this.finishToken(l_.comma);case 91:return++this.pos,this.finishToken(l_.bracketL);case 93:return++this.pos,this.finishToken(l_.bracketR);case 123:return++this.pos,this.finishToken(l_.braceL);case 125:return++this.pos,this.finishToken(l_.braceR);case 58:return++this.pos,this.finishToken(l_.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(l_.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(l_.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+lM(e)+"'")},hN.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},hN.readRegexp=function(){for(var e,t,i=this.pos;;){this.pos>=this.input.length&&this.raise(i,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(lg.test(r)&&this.raise(i,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(i,this.pos);++this.pos;var s=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(s);var o=this.regexpState||(this.regexpState=new hy(this));o.reset(i,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var l=null;try{l=new RegExp(n,a)}catch{}return this.finishToken(l_.regexp,{pattern:n,flags:a,value:l})},hN.readInt=function(e,t,i){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=i&&48===this.input.charCodeAt(this.pos),s=this.pos,a=0,o=0,l=0,h=t??1/0;l<h;++l,++this.pos){var c=this.input.charCodeAt(this.pos),p=void 0;if(r&&95===c){n&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),95===o&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),0===l&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),o=c;continue}if((p=c>=97?c-97+10:c>=65?c-65+10:c>=48&&c<=57?c-48:1/0)>=e)break;o=c,a=a*e+p}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===s||null!=t&&this.pos-s!==t?null:a},hN.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);return null==i&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(i=hT(this.input.slice(t,this.pos)),++this.pos):lh(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(l_.num,i)},hN.readNumber=function(e){var t,i=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(i,"Invalid number");var r=this.pos-i>=2&&48===this.input.charCodeAt(i);r&&this.strict&&this.raise(i,"Invalid number");var n=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&110===n){var s=hT(this.input.slice(i,this.pos));return++this.pos,lh(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(l_.num,s)}r&&/[89]/.test(this.input.slice(i,this.pos))&&(r=!1),46!==n||r||(++this.pos,this.readInt(10),n=this.input.charCodeAt(this.pos)),69!==n&&101!==n||r||((43===(n=this.input.charCodeAt(++this.pos))||45===n)&&++this.pos,null===this.readInt(10)&&this.raise(i,"Invalid number")),lh(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var a=(t=this.input.slice(i,this.pos),r?parseInt(t,8):parseFloat(t.replace(/_/g,"")));return this.finishToken(l_.num,a)},hN.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},hN.readString=function(e){for(var t="",i=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(i,this.pos),t+=this.readEscapedChar(!1),i=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(lb(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(l_.string,t)};var hk={};function hA(e,t){return lL.parse(e,t)}hN.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===hk)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},hN.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw hk;this.raise(e,t)},hN.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var i=this.input.charCodeAt(this.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.pos+1))return this.pos===this.start&&(this.type===l_.template||this.type===l_.invalidTemplate)?36===i?(this.pos+=2,this.finishToken(l_.dollarBraceL)):(++this.pos,this.finishToken(l_.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(l_.template,e));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(lb(i)){switch(e+=this.input.slice(t,this.pos),++this.pos,i){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+=`
302
+ `;break;default:e+=String.fromCharCode(i)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},hN.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if("{"!==this.input[this.pos+1])break;case"`":return this.finishToken(l_.invalidTemplate,this.input.slice(this.start,this.pos));case"\r":this.input[this.pos+1]===`
303
+ `&&++this.pos;case`
304
+ `:case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,"Unterminated template")},hN.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
305
+ `;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return lM(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),e){var i=this.pos-1;this.invalidStringToken(i,"Invalid escape sequence in template string")}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(n=parseInt(r=r.slice(0,-1),8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),("0"!==r||56===t||57===t)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return lb(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},hN.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},hN.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var n=this.fullCharCodeAtPos();if(lc(n,r))this.pos+=n<=65535?1:2;else if(92===n){this.containsEsc=!0,e+=this.input.slice(i,this.pos);var s=this.pos;117!==this.input.charCodeAt(++this.pos)&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var a=this.readCodePoint();(t?lh:lc)(a,r)||this.invalidStringToken(s,"Invalid Unicode escape"),e+=lM(a),i=this.pos}else break;t=!1}return e+this.input.slice(i,this.pos)},hN.readWord=function(){var e=this.readWord1(),t=l_.name;return this.keywords.test(e)&&(t=lf[e]),this.finishToken(t,e)},lL.acorn={Parser:lL,version:"8.16.0",defaultOptions:lj,Position:lD,SourceLocation:lR,getLineInfo:lO,Node:l5,TokenType:lp,tokTypes:l_,keywordTypes:lf,TokContext:lQ,tokContexts:lX,isIdentifierChar:lc,isIdentifierStart:lh,Token:hE,isNewLine:lb,lineBreak:lg,lineBreakG:lx,nonASCIIwhitespace:lw};let{stringify:hI}=JSON;if(!String.prototype.repeat)throw Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");let hC={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},hM={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:17,ClassExpression:17,FunctionExpression:17,ObjectExpression:17,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function hP(e,t){let{generator:i}=e;if(e.write("("),null!=t&&t.length>0){i[t[0].type](t[0],e);let{length:r}=t;for(let n=1;n<r;n++){let r=t[n];e.write(", "),i[r.type](r,e)}}e.write(")")}function hD(e,t,i,r){let n=e.expressionsPrecedence[t.type];if(17===n)return!0;let s=e.expressionsPrecedence[i.type];return n!==s?!r&&15===n&&14===s&&"**"===i.operator||n<s:(13===n||14===n)&&("**"===t.operator&&"**"===i.operator?!r:13===n&&13===s&&("??"===t.operator||"??"===i.operator)||(r?hC[t.operator]<=hC[i.operator]:hC[t.operator]<hC[i.operator]))}function hR(e,t,i,r){let{generator:n}=e;hD(e,t,i,r)?(e.write("("),n[t.type](t,e),e.write(")")):n[t.type](t,e)}function hO(e,t,i,r){let{length:n}=t;for(let s=0;s<n;s++){let n=t[s];e.write(i),"L"===n.type[0]?e.write("// "+n.value.trim()+`
306
+ `,n):(e.write("/*"),function(e,t,i,r){let n=t.split(`
307
+ `),s=n.length-1;if(e.write(n[0].trim()),s>0){e.write(r);for(let t=1;t<s;t++)e.write(i+n[t].trim()+r);e.write(i+n[s].trim())}}(e,n.value,i,r),e.write("*/"+r))}}function hj(e,t){let{generator:i}=e,{declarations:r}=t;e.write(t.kind+" ");let{length:n}=r;if(n>0){i.VariableDeclarator(r[0],e);for(let t=1;t<n;t++)e.write(", "),i.VariableDeclarator(r[t],e)}}let hV={Program(e,t){let i=t.indent.repeat(t.indentLevel),{lineEnd:r,writeComments:n}=t;n&&null!=e.comments&&hO(t,e.comments,i,r);let s=e.body,{length:a}=s;for(let e=0;e<a;e++){let a=s[e];n&&null!=a.comments&&hO(t,a.comments,i,r),t.write(i),this[a.type](a,t),t.write(r)}n&&null!=e.trailingComments&&hO(t,e.trailingComments,i,r)},BlockStatement:l=function(e,t){let i=t.indent.repeat(t.indentLevel++),{lineEnd:r,writeComments:n}=t,s=i+t.indent;t.write("{");let a=e.body;if(null!=a&&a.length>0){t.write(r),n&&null!=e.comments&&hO(t,e.comments,s,r);let{length:o}=a;for(let e=0;e<o;e++){let i=a[e];n&&null!=i.comments&&hO(t,i.comments,s,r),t.write(s),this[i.type](i,t),t.write(r)}t.write(i)}else n&&null!=e.comments&&(t.write(r),hO(t,e.comments,s,r),t.write(i));n&&null!=e.trailingComments&&hO(t,e.trailingComments,s,r),t.write("}"),t.indentLevel--},ClassBody:l,StaticBlock(e,t){t.write("static "),this.BlockStatement(e,t)},EmptyStatement(e,t){t.write(";")},ExpressionStatement(e,t){let i=t.expressionsPrecedence[e.expression.type];17===i||3===i&&"O"===e.expression.left.type[0]?(t.write("("),this[e.expression.type](e.expression,t),t.write(")")):this[e.expression.type](e.expression,t),t.write(";")},IfStatement(e,t){t.write("if ("),this[e.test.type](e.test,t),t.write(") "),this[e.consequent.type](e.consequent,t),null!=e.alternate&&(t.write(" else "),this[e.alternate.type](e.alternate,t))},LabeledStatement(e,t){this[e.label.type](e.label,t),t.write(": "),this[e.body.type](e.body,t)},BreakStatement(e,t){t.write("break"),null!=e.label&&(t.write(" "),this[e.label.type](e.label,t)),t.write(";")},ContinueStatement(e,t){t.write("continue"),null!=e.label&&(t.write(" "),this[e.label.type](e.label,t)),t.write(";")},WithStatement(e,t){t.write("with ("),this[e.object.type](e.object,t),t.write(") "),this[e.body.type](e.body,t)},SwitchStatement(e,t){let i=t.indent.repeat(t.indentLevel++),{lineEnd:r,writeComments:n}=t;t.indentLevel++;let s=i+t.indent,a=s+t.indent;t.write("switch ("),this[e.discriminant.type](e.discriminant,t),t.write(") {"+r);let{cases:o}=e,{length:l}=o;for(let e=0;e<l;e++){let i=o[e];n&&null!=i.comments&&hO(t,i.comments,s,r),i.test?(t.write(s+"case "),this[i.test.type](i.test,t),t.write(":"+r)):t.write(s+"default:"+r);let{consequent:l}=i,{length:h}=l;for(let e=0;e<h;e++){let i=l[e];n&&null!=i.comments&&hO(t,i.comments,a,r),t.write(a),this[i.type](i,t),t.write(r)}}t.indentLevel-=2,t.write(i+"}")},ReturnStatement(e,t){t.write("return"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t)),t.write(";")},ThrowStatement(e,t){t.write("throw "),this[e.argument.type](e.argument,t),t.write(";")},TryStatement(e,t){if(t.write("try "),this[e.block.type](e.block,t),e.handler){let{handler:i}=e;null==i.param?t.write(" catch "):(t.write(" catch ("),this[i.param.type](i.param,t),t.write(") ")),this[i.body.type](i.body,t)}e.finalizer&&(t.write(" finally "),this[e.finalizer.type](e.finalizer,t))},WhileStatement(e,t){t.write("while ("),this[e.test.type](e.test,t),t.write(") "),this[e.body.type](e.body,t)},DoWhileStatement(e,t){t.write("do "),this[e.body.type](e.body,t),t.write(" while ("),this[e.test.type](e.test,t),t.write(");")},ForStatement(e,t){if(t.write("for ("),null!=e.init){let{init:i}=e;"V"===i.type[0]?hj(t,i):this[i.type](i,t)}t.write("; "),e.test&&this[e.test.type](e.test,t),t.write("; "),e.update&&this[e.update.type](e.update,t),t.write(") "),this[e.body.type](e.body,t)},ForInStatement:r=function(e,t){t.write(`for ${e.await?"await ":""}(`);let{left:i}=e;"V"===i.type[0]?hj(t,i):this[i.type](i,t),t.write("I"===e.type[3]?" in ":" of "),this[e.right.type](e.right,t),t.write(") "),this[e.body.type](e.body,t)},ForOfStatement:r,DebuggerStatement(e,t){t.write("debugger;",e)},FunctionDeclaration:n=function(e,t){t.write((e.async?"async ":"")+(e.generator?"function* ":"function ")+(e.id?e.id.name:""),e),hP(t,e.params),t.write(" "),this[e.body.type](e.body,t)},FunctionExpression:n,VariableDeclaration(e,t){hj(t,e),t.write(";")},VariableDeclarator(e,t){this[e.id.type](e.id,t),null!=e.init&&(t.write(" = "),this[e.init.type](e.init,t))},ClassDeclaration(e,t){if(t.write("class "+(e.id?`${e.id.name} `:""),e),e.superClass){t.write("extends ");let{superClass:i}=e,{type:r}=i,n=t.expressionsPrecedence[r];("C"!==r[0]||"l"!==r[1]||"E"!==r[5])&&(17===n||n<t.expressionsPrecedence.ClassExpression)?(t.write("("),this[e.superClass.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ")}this.ClassBody(e.body,t)},ImportDeclaration(e,t){t.write("import ");let{specifiers:i,attributes:r}=e,{length:n}=i,s=0;if(n>0){for(;s<n;){s>0&&t.write(", ");let e=i[s],r=e.type[6];if("D"===r)t.write(e.local.name,e),s++;else if("N"===r)t.write("* as "+e.local.name,e),s++;else break}if(s<n){for(t.write("{");;){let e=i[s],{name:r}=e.imported;if(t.write(r,e),r!==e.local.name&&t.write(" as "+e.local.name),++s<n)t.write(", ");else break}t.write("}")}t.write(" from ")}if(this.Literal(e.source,t),r&&r.length>0){t.write(" with { ");for(let e=0;e<r.length;e++)this.ImportAttribute(r[e],t),e<r.length-1&&t.write(", ");t.write(" }")}t.write(";")},ImportAttribute(e,t){this.Identifier(e.key,t),t.write(": "),this.Literal(e.value,t)},ImportExpression(e,t){t.write("import("),this[e.source.type](e.source,t),t.write(")")},ExportDefaultDeclaration(e,t){t.write("export default "),this[e.declaration.type](e.declaration,t),null!=t.expressionsPrecedence[e.declaration.type]&&"F"!==e.declaration.type[0]&&t.write(";")},ExportNamedDeclaration(e,t){if(t.write("export "),e.declaration)this[e.declaration.type](e.declaration,t);else{t.write("{");let{specifiers:i}=e,{length:r}=i;if(r>0)for(let e=0;;){let n=i[e],{name:s}=n.local;if(t.write(s,n),s!==n.exported.name&&t.write(" as "+n.exported.name),++e<r)t.write(", ");else break}if(t.write("}"),e.source&&(t.write(" from "),this.Literal(e.source,t)),e.attributes&&e.attributes.length>0){t.write(" with { ");for(let i=0;i<e.attributes.length;i++)this.ImportAttribute(e.attributes[i],t),i<e.attributes.length-1&&t.write(", ");t.write(" }")}t.write(";")}},ExportAllDeclaration(e,t){if(null!=e.exported?t.write("export * as "+e.exported.name+" from "):t.write("export * from "),this.Literal(e.source,t),e.attributes&&e.attributes.length>0){t.write(" with { ");for(let i=0;i<e.attributes.length;i++)this.ImportAttribute(e.attributes[i],t),i<e.attributes.length-1&&t.write(", ");t.write(" }")}t.write(";")},MethodDefinition(e,t){e.static&&t.write("static ");let i=e.kind[0];("g"===i||"s"===i)&&t.write(e.kind+" "),e.value.async&&t.write("async "),e.value.generator&&t.write("*"),e.computed?(t.write("["),this[e.key.type](e.key,t),t.write("]")):this[e.key.type](e.key,t),hP(t,e.value.params),t.write(" "),this[e.value.body.type](e.value.body,t)},ClassExpression(e,t){this.ClassDeclaration(e,t)},ArrowFunctionExpression(e,t){t.write(e.async?"async ":"",e);let{params:i}=e;null!=i&&(1===i.length&&"I"===i[0].type[0]?t.write(i[0].name,i[0]):hP(t,e.params)),t.write(" => "),"O"===e.body.type[0]?(t.write("("),this.ObjectExpression(e.body,t),t.write(")")):this[e.body.type](e.body,t)},ThisExpression(e,t){t.write("this",e)},Super(e,t){t.write("super",e)},RestElement:s=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:s,YieldExpression(e,t){t.write(e.delegate?"yield*":"yield"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t))},AwaitExpression(e,t){t.write("await ",e),hR(t,e.argument,e)},TemplateLiteral(e,t){let{quasis:i,expressions:r}=e;t.write("`");let{length:n}=r;for(let e=0;e<n;e++){let n=r[e],s=i[e];t.write(s.value.raw,s),t.write("${"),this[n.type](n,t),t.write("}")}let s=i[i.length-1];t.write(s.value.raw,s),t.write("`")},TemplateElement(e,t){t.write(e.value.raw,e)},TaggedTemplateExpression(e,t){hR(t,e.tag,e),this[e.quasi.type](e.quasi,t)},ArrayExpression:o=function(e,t){if(t.write("["),e.elements.length>0){let{elements:i}=e,{length:r}=i;for(let e=0;;){let n=i[e];if(null!=n&&this[n.type](n,t),++e<r)t.write(", ");else{null==n&&t.write(", ");break}}}t.write("]")},ArrayPattern:o,ObjectExpression(e,t){let i=t.indent.repeat(t.indentLevel++),{lineEnd:r,writeComments:n}=t,s=i+t.indent;if(t.write("{"),e.properties.length>0){t.write(r),n&&null!=e.comments&&hO(t,e.comments,s,r);let a=","+r,{properties:o}=e,{length:l}=o;for(let e=0;;){let i=o[e];if(n&&null!=i.comments&&hO(t,i.comments,s,r),t.write(s),this[i.type](i,t),++e<l)t.write(a);else break}t.write(r),n&&null!=e.trailingComments&&hO(t,e.trailingComments,s,r),t.write(i+"}")}else n?null!=e.comments?(t.write(r),hO(t,e.comments,s,r),null!=e.trailingComments&&hO(t,e.trailingComments,s,r),t.write(i+"}")):null!=e.trailingComments?(t.write(r),hO(t,e.trailingComments,s,r),t.write(i+"}")):t.write("}"):t.write("}");t.indentLevel--},Property(e,t){e.method||"i"!==e.kind[0]?this.MethodDefinition(e,t):(e.shorthand||(e.computed?(t.write("["),this[e.key.type](e.key,t),t.write("]")):this[e.key.type](e.key,t),t.write(": ")),this[e.value.type](e.value,t))},PropertyDefinition(e,t){if(e.static&&t.write("static "),e.computed&&t.write("["),this[e.key.type](e.key,t),e.computed&&t.write("]"),null==e.value){"F"!==e.key.type[0]&&t.write(";");return}t.write(" = "),this[e.value.type](e.value,t),t.write(";")},ObjectPattern(e,t){if(t.write("{"),e.properties.length>0){let{properties:i}=e,{length:r}=i;for(let e=0;this[i[e].type](i[e],t),++e<r;)t.write(", ")}t.write("}")},SequenceExpression(e,t){hP(t,e.expressions)},UnaryExpression(e,t){if(e.prefix){let{operator:i,argument:r,argument:{type:n}}=e;t.write(i);let s=hD(t,r,e);!s&&(i.length>1||"U"===n[0]&&("n"===n[1]||"p"===n[1])&&r.prefix&&r.operator[0]===i&&("+"===i||"-"===i))&&t.write(" "),s?(t.write(i.length>1?" (":"("),this[n](r,t),t.write(")")):this[n](r,t)}else this[e.argument.type](e.argument,t),t.write(e.operator)},UpdateExpression(e,t){e.prefix?(t.write(e.operator),this[e.argument.type](e.argument,t)):(this[e.argument.type](e.argument,t),t.write(e.operator))},AssignmentExpression(e,t){this[e.left.type](e.left,t),t.write(" "+e.operator+" "),this[e.right.type](e.right,t)},AssignmentPattern(e,t){this[e.left.type](e.left,t),t.write(" = "),this[e.right.type](e.right,t)},BinaryExpression:a=function(e,t){let i="in"===e.operator;i&&t.write("("),hR(t,e.left,e,!1),t.write(" "+e.operator+" "),hR(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:a,ConditionalExpression(e,t){let{test:i}=e,r=t.expressionsPrecedence[i.type];17===r||r<=t.expressionsPrecedence.ConditionalExpression?(t.write("("),this[i.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ? "),this[e.consequent.type](e.consequent,t),t.write(" : "),this[e.alternate.type](e.alternate,t)},NewExpression(e,t){t.write("new ");let i=t.expressionsPrecedence[e.callee.type];17===i||i<t.expressionsPrecedence.CallExpression||function(e){let t=e;for(;null!=t;){let{type:e}=t;if("C"===e[0]&&"a"===e[1])return!0;if("M"!==e[0]||"e"!==e[1]||"m"!==e[2])return!1;t=t.object}}(e.callee)?(t.write("("),this[e.callee.type](e.callee,t),t.write(")")):this[e.callee.type](e.callee,t),hP(t,e.arguments)},CallExpression(e,t){let i=t.expressionsPrecedence[e.callee.type];17===i||i<t.expressionsPrecedence.CallExpression?(t.write("("),this[e.callee.type](e.callee,t),t.write(")")):this[e.callee.type](e.callee,t),e.optional&&t.write("?."),hP(t,e.arguments)},ChainExpression(e,t){this[e.expression.type](e.expression,t)},MemberExpression(e,t){let i=t.expressionsPrecedence[e.object.type];17===i||i<t.expressionsPrecedence.MemberExpression?(t.write("("),this[e.object.type](e.object,t),t.write(")")):this[e.object.type](e.object,t),e.computed?(e.optional&&t.write("?."),t.write("["),this[e.property.type](e.property,t),t.write("]")):(e.optional?t.write("?."):t.write("."),this[e.property.type](e.property,t))},MetaProperty(e,t){t.write(e.meta.name+"."+e.property.name,e)},Identifier(e,t){t.write(e.name,e)},PrivateIdentifier(e,t){t.write(`#${e.name}`,e)},Literal(e,t){null!=e.raw?t.write(e.raw,e):null!=e.regex?this.RegExpLiteral(e,t):null!=e.bigint?t.write(e.bigint+"n",e):t.write(hI(e.value),e)},RegExpLiteral(e,t){let{regex:i}=e;t.write(`/${i.pattern}/${i.flags}`,e)}},h$={};class hL{constructor(e){let t=e??h$;this.output="",null!=t.output?(this.output=t.output,this.write=this.writeToStream):this.output="",this.generator=null!=t.generator?t.generator:hV,this.expressionsPrecedence=null!=t.expressionsPrecedence?t.expressionsPrecedence:hM,this.indent=null!=t.indent?t.indent:" ",this.lineEnd=null!=t.lineEnd?t.lineEnd:`
308
+ `,this.indentLevel=null!=t.startingIndentLevel?t.startingIndentLevel:0,this.writeComments=!!t.comments&&t.comments,null!=t.sourceMap&&(this.write=null==t.output?this.writeAndMap:this.writeToStreamAndMap,this.sourceMap=t.sourceMap,this.line=1,this.column=0,this.lineEndSize=this.lineEnd.split(`
309
+ `).length-1,this.mapping={original:null,generated:this,name:void 0,source:t.sourceMap.file||t.sourceMap._file})}write(e){this.output+=e}writeToStream(e){this.output.write(e)}writeAndMap(e,t){this.output+=e,this.map(e,t)}writeToStreamAndMap(e,t){this.output.write(e),this.map(e,t)}map(e,t){if(null!=t){let{type:i}=t;if("L"===i[0]&&"n"===i[2]){this.column=0,this.line++;return}if(null!=t.loc){let{mapping:e}=this;e.original=t.loc.start,e.name=t.name,this.sourceMap.addMapping(e)}if("T"===i[0]&&"E"===i[8]||"L"===i[0]&&"i"===i[1]&&"string"==typeof t.value){let{length:t}=e,{column:i,line:r}=this;for(let n=0;n<t;n++)e[n]===`
310
+ `?(i=0,r++):i++;this.column=i,this.line=r;return}}let{length:i}=e,{lineEnd:r}=this;i>0&&(this.lineEndSize>0&&(1===r.length?e[i-1]===r:e.endsWith(r))?(this.line+=this.lineEndSize,this.column=0):this.column+=i)}toString(){return this.output}}function hB(e,t){let i=new hL(t);return i.generator[e.type](e,i),i.output}var hF=Object.defineProperty,hq=(e,t,i)=>((e,t,i)=>t in e?hF(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let hz=new Set(["Infinity","NaN","undefined","null","true","false"]),hU=new Set(["Math","Array","Object","String","Number","Boolean","Date","RegExp","Error","JSON","Promise","Set","Map","WeakSet","WeakMap","Symbol","BigInt","Proxy","Reflect","console","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]);function hW(e){if(!e||"string"!=typeof e)return;let t=e.trim();if(t.endsWith("[]"))return"array";let i=t.indexOf("<");i>=0&&(t=t.slice(0,i));let r=t.split(/\s+/).filter(Boolean);return r.length>0?r[r.length-1]:void 0}class hK{constructor(){hq(this,"scopes",[]),hq(this,"scopeTypes",[]),hq(this,"scopeCounts",new Map),hq(this,"contextBoundVars",new Set),hq(this,"arrayPatternElements",new Set),hq(this,"rootParams",new Set),hq(this,"localSeriesVars",new Set),hq(this,"functionParams",new Set),hq(this,"varKinds",new Map),hq(this,"loopVars",new Set),hq(this,"loopVarNames",new Map),hq(this,"paramIdCounter",0),hq(this,"cacheIdCounter",0),hq(this,"tempVarCounter",0),hq(this,"taCallIdCounter",0),hq(this,"userCallIdCounter",0),hq(this,"plotCallIdCounter",0),hq(this,"bareCallIdCounters",new Map),hq(this,"alertCallIdCounter",0),hq(this,"loopGuardCounter",0),hq(this,"hoistingStack",[]),hq(this,"hoistingRoots",[]),hq(this,"suppressHoisting",!1),hq(this,"inLoopTest",!1),hq(this,"chainHoist",null),hq(this,"historyRecordDepth",0),hq(this,"reservedNames",new Set),hq(this,"userFunctions",new Set),hq(this,"userMethods",new Set),hq(this,"regularUserFunctions",new Set),hq(this,"udtTypeNames",new Map),hq(this,"udtInstances",new Map),hq(this,"functionReturnTypes",new Map),hq(this,"functionReturnTupleTypes",new Map),hq(this,"functionParamUdtTypes",new Map),hq(this,"varStaticTypes",new Map),hq(this,"methodReceiverTypes",new Map),hq(this,"functionParamStaticTypes",new Map),hq(this,"methodCandidates",new Map),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`'p${this.paramIdCounter++}'`}}get nextCacheIdArg(){return{type:"Identifier",name:`'cache_${this.cacheIdCounter++}'`}}getNextTACallId(){return{type:"Literal",value:`_ta${this.taCallIdCounter++}`}}getNextUserCallId(){return{type:"Literal",value:`_fn${this.userCallIdCounter++}`}}getNextPlotCallId(){return{type:"Literal",value:`#${this.plotCallIdCounter++}`}}getNextBareCallsiteId(e){let t=this.bareCallIdCounters.get(e)??0;return this.bareCallIdCounters.set(e,t+1),{type:"Literal",value:`${e}#${t}`}}getNextAlertCallId(){return{type:"Literal",value:`alert_${this.alertCallIdCounter++}`}}getNextLoopGuardName(){return`__lg${this.loopGuardCounter++}`}pushScope(e){this.scopes.push(new Map),this.scopeTypes.push(e),this.scopeCounts.set(e,(this.scopeCounts.get(e)||0)+1)}popScope(){this.scopes.pop(),this.scopeTypes.pop()}getCurrentScopeType(){return this.scopeTypes[this.scopeTypes.length-1]}isInsideFunctionScope(){for(let e=this.scopeTypes.length-1;e>=0;e--)if("fn"===this.scopeTypes[e])return!0;return!1}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addLocalSeriesVar(e){this.localSeriesVars.add(e)}removeLocalSeriesVar(e){this.localSeriesVars.delete(e)}isLocalSeriesVar(e){return this.localSeriesVars.has(e)}addFunctionParam(e){this.functionParams.add(e),this.localSeriesVars.add(e)}removeFunctionParam(e){this.functionParams.delete(e),this.localSeriesVars.delete(e)}isFunctionParam(e){return this.functionParams.has(e)}addUdtTypeName(e,t={}){this.udtTypeNames.set(e,t)}isUdtTypeName(e){return this.udtTypeNames.has(e)}getUdtTypeFields(e){return this.udtTypeNames.get(e)}markVariableAsUdtInstance(e,t){this.udtInstances.set(e,t)}getVariableUdtType(e){return this.udtInstances.get(e)}isUdtInstance(e){return this.udtInstances.has(e)}setFunctionReturnType(e,t){let i=this.functionReturnTypes.get(e);if(i&&i!==t)return void this.functionReturnTypes.delete(e);this.functionReturnTypes.set(e,t)}getFunctionReturnType(e){return this.functionReturnTypes.get(e)}setFunctionReturnTupleType(e,t){let i=this.functionReturnTupleTypes.get(e);if(i&&(i.length!==t.length||i.some((e,i)=>e!==t[i])))return void this.functionReturnTupleTypes.delete(e);this.functionReturnTupleTypes.set(e,t)}getFunctionReturnTupleType(e){return this.functionReturnTupleTypes.get(e)}setFunctionParamUdtTypes(e,t){this.functionParamUdtTypes.set(e,t)}getFunctionParamUdtTypes(e){return this.functionParamUdtTypes.get(e)}unmarkVariableAsUdtInstance(e){this.udtInstances.delete(e)}setVarStaticType(e,t){let i=hW(t);i&&this.varStaticTypes.set(e,i)}getVarStaticType(e){return this.varStaticTypes.get(e)}unsetVarStaticType(e){this.varStaticTypes.delete(e)}addMethodCandidate(e,t){let i=this.methodCandidates.get(e)??[];i.includes(t)||i.push(t),this.methodCandidates.set(e,i)}getMethodCandidates(e){return this.methodCandidates.get(e)??[]}setMethodReceiverType(e,t){let i=hW(t);i&&this.methodReceiverTypes.set(e,i)}isMethodReceiverTypeName(e){for(let t of this.methodReceiverTypes.values())if(t===e)return!0;return!1}getMethodReceiverType(e){return this.methodReceiverTypes.get(e)}setFunctionParamStaticTypes(e,t){this.functionParamStaticTypes.set(e,t)}getFunctionParamStaticTypes(e){return this.functionParamStaticTypes.get(e)}addContextBoundVar(e,t=!1){this.contextBoundVars.add(e),t&&this.rootParams.add(e)}removeContextBoundVar(e){this.contextBoundVars.has(e)&&(this.contextBoundVars.delete(e),this.rootParams.has(e)&&this.rootParams.delete(e))}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return!(hz.has(e)||hU.has(e))&&this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,t){this.loopVars.add(e),this.loopVarNames.set(e,t)}removeLoopVariable(e){this.loopVars.delete(e),this.loopVarNames.delete(e)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addReservedName(e){this.reservedNames.add(e)}addUserFunction(e){this.userFunctions.add(e)}isUserFunction(e){return this.userFunctions.has(e)}addUserMethod(e){this.userMethods.add(e)}isUserMethod(e){return this.userMethods.has(e)}addRegularUserFunction(e){this.regularUserFunctions.add(e)}isRegularUserFunction(e){return this.regularUserFunctions.has(e)}addVariable(e,t){if(this.isContextBound(e))return e;let i=this.scopes[this.scopes.length-1],r=this.scopeTypes[this.scopeTypes.length-1],n=this.scopeCounts.get(r)||1,s=`${r}${n}_${e}`;return i.set(e,s),this.varKinds.set(s,t),s}hideCurrentScopeVariable(e){let t=this.scopes[this.scopes.length-1],i=t?.get(e);return void 0===i?()=>{}:(t.delete(e),()=>t.set(e,i))}getVariable(e){if(this.loopVars.has(e)){let t=this.loopVarNames.get(e);if(t)return[t,"let"]}if(this.isContextBound(e))return[e,"let"];for(let t=this.scopes.length-1;t>=0;t--){let i=this.scopes[t];if(i.has(e)){let t=i.get(e),r=this.varKinds.get(t)||"let";return[t,r]}}return[e,"let"]}isVariableInFunctionScope(e){for(let t=this.scopes.length-1;t>=0;t--)if(this.scopes[t].has(e)){for(let e=0;e<=t;e++)if("fn"===this.scopeTypes[e])return!0;break}return!1}generateTempVar(){return`temp_${++this.tempVarCounter}`}enterHoistingScope(){this.hoistingStack.push([])}exitHoistingScope(){return this.hoistingStack.pop()||[]}addHoistedStatement(e){this.hoistingStack.length>0&&!this.suppressHoisting&&((this.historyRecordDepth>0?this.activeChainFrame():null)??this.hoistingStack[this.hoistingStack.length-1]).push(e)}setChainHoistFrame(e){let t=this.chainHoist;return this.chainHoist=e?{frame:e,depth:this.hoistingStack.length}:null,t}restoreChainHoistFrame(e){this.chainHoist=e}enterHistoryRecord(){this.historyRecordDepth++}exitHistoryRecord(){this.historyRecordDepth--}activeChainFrame(){return this.chainHoist&&this.chainHoist.depth===this.hoistingStack.length?this.chainHoist.frame:null}addOuterHoistedStatement(e){if(this.hoistingStack.length>0){let t=Math.min(1,this.hoistingStack.length-1);this.hoistingStack[t].push(e)}}enterFunctionHoistingRoot(){this.hoistingRoots.push(this.hoistingStack.length)}exitFunctionHoistingRoot(){this.hoistingRoots.pop()}addScopeRootHoistedStatement(e){if(0===this.hoistingStack.length)return!1;let t=this.hoistingRoots.length>0?this.hoistingRoots[this.hoistingRoots.length-1]:1;return this.hoistingStack[Math.min(t,this.hoistingStack.length-1)].push(e),!0}getCurrentHoistingScope(){return 0===this.hoistingStack.length?null:this.hoistingStack[this.hoistingStack.length-1]}setSuppressHoisting(e){this.suppressHoisting=e}setInLoopTest(e){this.inLoopTest=e}addEagerHoistedStatement(e){return 0!==this.hoistingStack.length&&!this.inLoopTest&&((this.activeChainFrame()??this.hoistingStack[this.hoistingStack.length-1]).push(e),!0)}shouldSuppressHoisting(){return this.suppressHoisting}hasVariableInScope(e){if(this.reservedNames.has(e))return!0;for(let t=this.scopes.length-1;t>=0;t--)if(this.scopes[t].has(e))return!0;return!!(this.contextBoundVars.has(e)||this.loopVars.has(e)||this.localSeriesVars.has(e))}generateParamId(){let e=`p${this.paramIdCounter++}`;for(;this.hasVariableInScope(e);)e=`p${this.paramIdCounter++}`;let t=this.scopes[this.scopes.length-1];return t&&t.set(e,e),e}}function hG(e,t,i,r,n){i||(i=hX),function e(r,n,s){var a=s||r.type;hQ(i,a,r,n,e),t[a]&&t[a](r,n)}(e,r,n)}function hH(e,t,i,r,n){var s=[];i||(i=hX),function e(r,n,a){var o=a||r.type,l=r!==s[s.length-1];l&&s.push(r),hQ(i,o,r,n,e),t[o]&&t[o](r,n||s,s),l&&s.pop()}(e,r,n)}function hY(e,t,i,r,n){var s=i?function(e,t){var i=Object.create(t||hX);for(var r in e)i[r]=e[r];return i}(i,r||void 0):r;!function e(t,i,r){s[r||t.type](t,i,e)}(e,t,n)}function hZ(e,t,i){i(e,t)}function hJ(e,t,i){}function hQ(e,t,i,r,n){if(null==e[t])throw Error("No walker function defined for node type "+t);e[t](i,r,n)}var hX={};hX.Program=hX.BlockStatement=hX.StaticBlock=function(e,t,i){for(var r=0,n=e.body;r<n.length;r+=1)i(n[r],t,"Statement")},hX.Statement=hZ,hX.EmptyStatement=hJ,hX.ExpressionStatement=hX.ParenthesizedExpression=hX.ChainExpression=function(e,t,i){return i(e.expression,t,"Expression")},hX.IfStatement=function(e,t,i){i(e.test,t,"Expression"),i(e.consequent,t,"Statement"),e.alternate&&i(e.alternate,t,"Statement")},hX.LabeledStatement=function(e,t,i){return i(e.body,t,"Statement")},hX.BreakStatement=hX.ContinueStatement=hJ,hX.WithStatement=function(e,t,i){i(e.object,t,"Expression"),i(e.body,t,"Statement")},hX.SwitchStatement=function(e,t,i){i(e.discriminant,t,"Expression");for(var r=0,n=e.cases;r<n.length;r+=1)i(n[r],t)},hX.SwitchCase=function(e,t,i){e.test&&i(e.test,t,"Expression");for(var r=0,n=e.consequent;r<n.length;r+=1)i(n[r],t,"Statement")},hX.ReturnStatement=hX.YieldExpression=hX.AwaitExpression=function(e,t,i){e.argument&&i(e.argument,t,"Expression")},hX.ThrowStatement=hX.SpreadElement=function(e,t,i){return i(e.argument,t,"Expression")},hX.TryStatement=function(e,t,i){i(e.block,t,"Statement"),e.handler&&i(e.handler,t),e.finalizer&&i(e.finalizer,t,"Statement")},hX.CatchClause=function(e,t,i){e.param&&i(e.param,t,"Pattern"),i(e.body,t,"Statement")},hX.WhileStatement=hX.DoWhileStatement=function(e,t,i){i(e.test,t,"Expression"),i(e.body,t,"Statement")},hX.ForStatement=function(e,t,i){e.init&&i(e.init,t,"ForInit"),e.test&&i(e.test,t,"Expression"),e.update&&i(e.update,t,"Expression"),i(e.body,t,"Statement")},hX.ForInStatement=hX.ForOfStatement=function(e,t,i){i(e.left,t,"ForInit"),i(e.right,t,"Expression"),i(e.body,t,"Statement")},hX.ForInit=function(e,t,i){"VariableDeclaration"===e.type?i(e,t):i(e,t,"Expression")},hX.DebuggerStatement=hJ,hX.FunctionDeclaration=function(e,t,i){return i(e,t,"Function")},hX.VariableDeclaration=function(e,t,i){for(var r=0,n=e.declarations;r<n.length;r+=1)i(n[r],t)},hX.VariableDeclarator=function(e,t,i){i(e.id,t,"Pattern"),e.init&&i(e.init,t,"Expression")},hX.Function=function(e,t,i){e.id&&i(e.id,t,"Pattern");for(var r=0,n=e.params;r<n.length;r+=1)i(n[r],t,"Pattern");i(e.body,t,e.expression?"Expression":"Statement")},hX.Pattern=function(e,t,i){"Identifier"===e.type?i(e,t,"VariablePattern"):"MemberExpression"===e.type?i(e,t,"MemberPattern"):i(e,t)},hX.VariablePattern=hJ,hX.MemberPattern=hZ,hX.RestElement=function(e,t,i){return i(e.argument,t,"Pattern")},hX.ArrayPattern=function(e,t,i){for(var r=0,n=e.elements;r<n.length;r+=1){var s=n[r];s&&i(s,t,"Pattern")}},hX.ObjectPattern=function(e,t,i){for(var r=0,n=e.properties;r<n.length;r+=1){var s=n[r];"Property"===s.type?(s.computed&&i(s.key,t,"Expression"),i(s.value,t,"Pattern")):"RestElement"===s.type&&i(s.argument,t,"Pattern")}},hX.Expression=hZ,hX.ThisExpression=hX.Super=hX.MetaProperty=hJ,hX.ArrayExpression=function(e,t,i){for(var r=0,n=e.elements;r<n.length;r+=1){var s=n[r];s&&i(s,t,"Expression")}},hX.ObjectExpression=function(e,t,i){for(var r=0,n=e.properties;r<n.length;r+=1)i(n[r],t)},hX.FunctionExpression=hX.ArrowFunctionExpression=hX.FunctionDeclaration,hX.SequenceExpression=function(e,t,i){for(var r=0,n=e.expressions;r<n.length;r+=1)i(n[r],t,"Expression")},hX.TemplateLiteral=function(e,t,i){for(var r=0,n=e.quasis;r<n.length;r+=1)i(n[r],t);for(var s=0,a=e.expressions;s<a.length;s+=1)i(a[s],t,"Expression")},hX.TemplateElement=hJ,hX.UnaryExpression=hX.UpdateExpression=function(e,t,i){i(e.argument,t,"Expression")},hX.BinaryExpression=hX.LogicalExpression=function(e,t,i){i(e.left,t,"Expression"),i(e.right,t,"Expression")},hX.AssignmentExpression=hX.AssignmentPattern=function(e,t,i){i(e.left,t,"Pattern"),i(e.right,t,"Expression")},hX.ConditionalExpression=function(e,t,i){i(e.test,t,"Expression"),i(e.consequent,t,"Expression"),i(e.alternate,t,"Expression")},hX.NewExpression=hX.CallExpression=function(e,t,i){if(i(e.callee,t,"Expression"),e.arguments)for(var r=0,n=e.arguments;r<n.length;r+=1)i(n[r],t,"Expression")},hX.MemberExpression=function(e,t,i){i(e.object,t,"Expression"),e.computed&&i(e.property,t,"Expression")},hX.ExportNamedDeclaration=hX.ExportDefaultDeclaration=function(e,t,i){if(e.declaration&&i(e.declaration,t,"ExportNamedDeclaration"===e.type||e.declaration.id?"Statement":"Expression"),e.source&&i(e.source,t,"Expression"),e.attributes)for(var r=0,n=e.attributes;r<n.length;r+=1)i(n[r],t)},hX.ExportAllDeclaration=function(e,t,i){if(e.exported&&i(e.exported,t),i(e.source,t,"Expression"),e.attributes)for(var r=0,n=e.attributes;r<n.length;r+=1)i(n[r],t)},hX.ImportAttribute=function(e,t,i){i(e.value,t,"Expression")},hX.ImportDeclaration=function(e,t,i){for(var r=0,n=e.specifiers;r<n.length;r+=1)i(n[r],t);if(i(e.source,t,"Expression"),e.attributes)for(var s=0,a=e.attributes;s<a.length;s+=1)i(a[s],t)},hX.ImportExpression=function(e,t,i){i(e.source,t,"Expression"),e.options&&i(e.options,t,"Expression")},hX.ImportSpecifier=hX.ImportDefaultSpecifier=hX.ImportNamespaceSpecifier=hX.Identifier=hX.PrivateIdentifier=hX.Literal=hJ,hX.TaggedTemplateExpression=function(e,t,i){i(e.tag,t,"Expression"),i(e.quasi,t,"Expression")},hX.ClassDeclaration=hX.ClassExpression=function(e,t,i){return i(e,t,"Class")},hX.Class=function(e,t,i){e.id&&i(e.id,t,"Pattern"),e.superClass&&i(e.superClass,t,"Expression"),i(e.body,t)},hX.ClassBody=function(e,t,i){for(var r=0,n=e.body;r<n.length;r+=1)i(n[r],t)},hX.MethodDefinition=hX.PropertyDefinition=hX.Property=function(e,t,i){e.computed&&i(e.key,t,"Expression"),e.value&&i(e.value,t,"Expression")};let h0={createIdentifier:e=>({type:"Identifier",name:e}),createLiteral:e=>({type:"Literal",value:e}),createMemberExpression:(e,t,i=!1)=>({type:"MemberExpression",object:e,property:t,computed:i}),createContextIdentifier(){return this.createIdentifier("$")},createLocalContextIdentifier(){return this.createIdentifier("$$")},createContextVariableReference(e,t){let i=this.createContextIdentifier(),r=this.createIdentifier(e),n=this.createIdentifier(t);return this.createMemberExpression(this.createMemberExpression(i,r,!1),n,!1)},createLocalContextVariableReference(e,t){let i=this.createLocalContextIdentifier(),r=this.createIdentifier(e),n=this.createIdentifier(t);return this.createMemberExpression(this.createMemberExpression(i,r,!1),n,!1)},createDynamicContextVariableReference(e,t){let i=this.createContextIdentifier(),r=this.createIdentifier(e);return this.createMemberExpression(this.createMemberExpression(i,r,!1),t,!0)},createContextVariableAccess0(e,t){let i=this.createContextVariableReference(e,t);return this.createGetCall(i,0)},createDynamicContextVariableAccess0(e,t){let i=this.createDynamicContextVariableReference(e,t);return this.createGetCall(i,0)},createArrayAccess(e,t){let i="number"==typeof t?this.createLiteral(t):t;return this.createMemberExpression(e,i,!0)},createCallExpression:(e,t)=>({type:"CallExpression",callee:e,arguments:t}),createAssignmentExpression:(e,t,i="=")=>({type:"AssignmentExpression",operator:i,left:e,right:t}),createExpressionStatement:e=>({type:"ExpressionStatement",expression:e}),createInitCall(e,t,i){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("init"),!1),n=[e,t];return i&&n.push(i),this.createCallExpression(r,n)},createInitVarCall(e,t,i=!1){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("initVar"),!1),n=[e,t];return i&&n.push(this.createLiteral(!0)),this.createCallExpression(r,n)},createGetCall(e,t){let i=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("get"),!1),r="number"==typeof t?this.createLiteral(t):t;return this.createCallExpression(i,[e,r])},createSetCall(e,t){let i=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("set"),!1);return this.createCallExpression(i,[e,t])},createMathEqCall(e,t){let i=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(i,this.createIdentifier("math"),!1),n=this.createMemberExpression(r,this.createIdentifier("__eq"),!1);return this.createCallExpression(n,[e,t])},createMathNeqCall(e,t){let i=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(i,this.createIdentifier("math"),!1),n=this.createMemberExpression(r,this.createIdentifier("__neq"),!1);return this.createCallExpression(n,[e,t])},createMathCompareCall(e,t,i){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),n=this.createMemberExpression(r,this.createIdentifier("math"),!1),s=this.createMemberExpression(n,this.createIdentifier(e),!1);return this.createCallExpression(s,[t,i])},createMathIntDivCall(e,t){let i=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(i,this.createIdentifier("math"),!1),n=this.createMemberExpression(r,this.createIdentifier("__idiv"),!1);return this.createCallExpression(n,[e,t])},createWrapperFunction(e){return{type:"FunctionDeclaration",id:null,params:[this.createIdentifier("context")],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:e}]}}},createVariableDeclaration(e,t){return{type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:this.createIdentifier(e),init:t}]}},createAwaitExpression:e=>({type:"AwaitExpression",argument:e})},h1=new Set(["table","line","label","box","linefill","polyline","array","matrix","map"]),h2={"request.footprint":"footprint","footprint.poc":"volume_row","footprint.vah":"volume_row","footprint.val":"volume_row","footprint.get_row_by_price":"volume_row"};function h3(e,t){if(e){if("CallExpression"===e.type&&e.callee?.type==="MemberExpression"&&!e.callee.computed&&e.callee.object?.type==="Identifier"&&e.callee.property?.type==="Identifier"&&("new"===e.callee.property.name||"copy"===e.callee.property.name)&&t.isUdtTypeName(e.callee.object.name))return e.callee.object.name;if("CallExpression"===e.type&&e.callee?.type==="Identifier"){let i=t.getFunctionReturnType(e.callee.name);if(i)return i}if("ConditionalExpression"===e.type){let i=h3(e.consequent,t),r=h3(e.alternate,t);if(i&&i===r)return i}}}var h4=Object.defineProperty;let h6=new Set(["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]),h5=new Set(["input.int","math.floor","math.ceil","array.size","matrix.rows","matrix.columns","str.length","timestamp","ta.barssince","ta.highestbars","ta.lowestbars"]);function h9(e,t){return"notint"!==e&&"notint"!==t?"int":"notint"}class h8{constructor(){((e,t,i)=>((e,t,i)=>t in e?h4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"stack",[new Map])}push(){this.stack.push(new Map)}pop(){this.stack.length>1&&this.stack.pop()}set(e,t){this.stack[this.stack.length-1].set(e,t)}get(e){for(let t=this.stack.length-1;t>=0;t--){let i=this.stack[t].get(e);if(void 0!==i)return i}}assign(e,t){for(let i=this.stack.length-1;i>=0;i--)if(this.stack[i].has(e))return void this.stack[i].set(e,h9(this.stack[i].get(e),t));this.stack[this.stack.length-1].set(e,h9(t,t))}}let h7=new Set(["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"]),ce=new Set(["&&","||","??"]);function ct(e){return null!==e&&"object"==typeof e&&"string"==typeof e.type}let ci={open:"float",high:"float",low:"float",close:"float",volume:"float",hl2:"float",hlc3:"float",ohlc4:"float",hlcc4:"float",bar_index:"int",last_bar_index:"int",time:"int",time_close:"int"},cr=()=>({type:"Identifier",name:"undefined"});function cn(e,t){let i={type:"Identifier",name:`'${t}'`};if(!e.isInsideFunctionScope())return i;let[r]=e.getVariable("$$");return r?{type:"BinaryExpression",operator:"+",left:h0.createMemberExpression(h0.createLocalContextIdentifier(),h0.createIdentifier("id")),right:i}:i}function cs(e,t){let[i,r]=t.getVariable(e);if((i.match(/^fn\d+_/)||t.isVariableInFunctionScope(e))&&"$$"!==e){let[e]=t.getVariable("$$");if(e)return h0.createLocalContextVariableReference(r,i)}return h0.createContextVariableReference(r,i)}function ca(e,t){let i=cs(e,t);return h0.createGetCall(i,0)}let co=["BinaryExpression","UnaryExpression","LogicalExpression","ConditionalExpression"];function cl(e,t){if(e.computed&&"Identifier"===e.property.type){if(t.isLoopVariable(e.property.name)){if("Identifier"===e.object.type&&!t.isLoopVariable(e.object.name)){if(t.isLocalSeriesVar(e.object.name)){let t=h0.createIdentifier(e.object.name);t._skipTransformation=!0;let i=h0.createGetCall(t,e.property);Object.assign(e,i),e._indexTransformed=!0;return}if(!t.isContextBound(e.object.name)){let i=cs(e.object.name,t),r=h0.createGetCall(i,e.property);Object.assign(e,r),e._indexTransformed=!0}}return}if(!t.isContextBound(e.property.name))if(t.isLocalSeriesVar(e.property.name)){let t=h0.createIdentifier(e.property.name);t._skipTransformation=!0,e.property=h0.createGetCall(t,0)}else e.property=cs(e.property.name,t),e.property=h0.createGetCall(e.property,0)}if(e.computed&&"Identifier"===e.object.type){if(t.isLoopVariable(e.object.name))return;if(t.isLocalSeriesVar(e.object.name)){let i=h0.createIdentifier(e.object.name);i._skipTransformation=!0;let r=co.includes(e.property.type)?cy(e.property,t):e.property;Object.assign(e,h0.createGetCall(i,r)),e._indexTransformed=!0;return}if(t.isContextBound(e.object.name)||(e.object=cs(e.object.name,t)),"MemberExpression"===e.property.type){let i=e.property;i._indexTransformed||(cl(i,t),i._indexTransformed=!0)}}e.computed&&"Identifier"!==e.property.type&&"MemberExpression"!==e.property.type&&!e._indexTransformed&&("BinaryExpression"===e.property.type||"UnaryExpression"===e.property.type||"LogicalExpression"===e.property.type||"ConditionalExpression"===e.property.type)&&(e.property=cb(e.property,t))}function ch(e,t,i){return"Identifier"!==e.type||t.isContextBound(e.name)||t.isLoopVariable(e.name)?"BinaryExpression"===e.type||"UnaryExpression"===e.type||"LogicalExpression"===e.type||"ConditionalExpression"===e.type?cb(e,t,i):e:h0.createGetCall(cx(e,t),0)}function cc(e,t,i,r,n){let s=e;for(;s.object&&"MemberExpression"===s.object.type;)s=s.object;let a=n.isLocalSeriesVar(t),[o,l]=n.getVariable(t);if(!a&&"var"!==l&&"varip"!==l)return s.object=h0.createGetCall(i,r),e;s.object=h0.createGetCall(i,0);let h=n.generateParamId(),c={type:"CallExpression",callee:h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("param")),arguments:[e,cr(),cn(n,h)],_transformed:!0,_isParamCall:!0},p=h0.createVariableDeclaration(h,c),u=a||/^(glb|fn)\d+_/.test(o),d=c;return(u?n.addScopeRootHoistedStatement(p):n.addEagerHoistedStatement(p))&&((d=h0.createIdentifier(h))._skipTransformation=!0,d._arrayAccessed=!0),h0.createGetCall(d,r)}function cp(e,t){let i=h0.createGetCall(h0.createIdentifier(e.name),0);void 0!==e.start&&(i.start=e.start),void 0!==e.end&&(i.end=e.end),i._indexTransformed=!0,Object.assign(e,i)}function cu(e,t){if(!e._skipTransformation&&"$"!==e.name){let i;if(oD.includes(e.name)&&t.isContextBound(e.name)){let t=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e,i=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&!e.parent.computed;if(!t&&!i){let t={type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Identifier",name:"__value"},computed:!1};Object.assign(e,h0.createGetCall(t,0)),delete e.name;return}}if("Math"===e.name||"NaN"===e.name||"undefined"===e.name||"Infinity"===e.name||"null"===e.name||e.name.startsWith("'")&&e.name.endsWith("'")||e.name.startsWith('"')&&e.name.endsWith('"')||e.name.startsWith("`")&&e.name.endsWith("`")||t.isLoopVariable(e.name))return;let r=!1;if(e.parent&&"CallExpression"===e.parent.type&&e.parent.arguments.includes(e)){let t=e.parent.callee;if("MemberExpression"===t.type&&t.object&&"$"===t.object.name&&["get","set","init","param","call"].includes(t.property.name)){let i=e.parent.arguments.indexOf(e);"call"===t.property.name?i>=2&&(r=!0):0===i&&(r=!0)}else{let e="MemberExpression"===t.type&&t.object&&"Identifier"===t.object.type&&oP.includes(t.object.name);r="MemberExpression"!==t.type||!!e}}let n=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&t.isContextBound(e.name),s=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&"param"===e.parent.callee.property.name;e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left;let a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e,o=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,l=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.property===e&&e.parent.parent&&"CallExpression"===e.parent.parent.type&&e.parent.parent.callee&&"MemberExpression"===e.parent.parent.callee.type&&t.isContextBound(e.parent.parent.callee.object.name);if(n||s||r||l||a){if(a||e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&e.parent.callee.object&&"$"===e.parent.callee.object.name&&"call"===e.parent.callee.property.name&&e.parent.arguments[0]===e||t.isLocalSeriesVar(e.name)||t.isContextBound(e.name)&&!t.isRootParam(e.name))return;let i=cs(e.name,t);Object.assign(e,i);return}let h=t.isContextBound(e.name)&&!t.isRootParam(e.name);if(h){let t=e.parent&&"CallExpression"===e.parent.type&&e.parent.arguments.includes(e),i=e.parent&&"SwitchStatement"===e.parent.type&&e.parent.discriminant===e,r=e.parent&&"SwitchCase"===e.parent.type&&e.parent.test===e;if(!t&&!i&&!r)return}if(t.isLocalSeriesVar(e.name)){if(!o){let t=h0.createIdentifier(e.name);Object.assign(e,h0.createGetCall(t,0))}return}let[c,p]=t.getVariable(e.name);if(h)i=h0.createIdentifier(e.name);else{if(c===e.name&&!t.isContextBound(e.name))return;i=cs(e.name,t)}o?Object.assign(e,i):Object.assign(e,h0.createGetCall(i,0))}}let cd=["CallExpression","BinaryExpression","LogicalExpression","ConditionalExpression","UnaryExpression"];function cm(e,t){return e?.type==="MemberExpression"&&!e.computed&&e.object?.type==="Identifier"&&oP.includes(e.object.name)&&t.isContextBound(e.object.name)}function cf(e,t){return"CallExpression"===e.type?(e._transformed||cC(e,t),e):cb(e,t)}function cy(e,t){if("Literal"===e.type||"CallExpression"===e.type&&e.callee?.object?.name==="$")return e;if("MemberExpression"===e.type&&e.computed){cl(e,t);let i=e=>{"MemberExpression"===e.type&&(e.computed&&i(e.property),cg(e,"",t))};return i(e),e}return"CallExpression"===e.type?(e._transformed||cC(e,t),e):cb(e,t)}function c_(e,t){if("Identifier"!==e.type)return cy(e,t);if(t.isLoopVariable(e.name))return e;if(t.isLocalSeriesVar(e.name)){let t=h0.createIdentifier(e.name);return t._skipTransformation=!0,h0.createGetCall(t,0)}return h0.createGetCall(cx(e,t),0)}function cg(e,t,i){if(e.object&&"Identifier"===e.object.type&&"Math"===e.object.name)return;if(e.computed&&cm(e.object,i)){let t=function(e,t,i){let r=e.object.name,n={type:"CallExpression",callee:h0.createMemberExpression(h0.createIdentifier(r),h0.createIdentifier(e.property.name)),arguments:"ta"===r?[i.getNextTACallId()]:[],_transformed:!0},s=i.generateParamId(),a={type:"CallExpression",callee:h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("param")),arguments:[n,cr(),{type:"Identifier",name:`'${s}'`}],_transformed:!0,_isParamCall:!0};i.addOuterHoistedStatement(h0.createVariableDeclaration(s,a));let o=h0.createIdentifier(s);o._skipTransformation=!0,o._arrayAccessed=!0;let l=h0.createGetCall(o,t);return l._transformed=!0,l._historyTransformed=!0,l}(e.object,c_(e.property,i),i);Object.assign(e,t),delete e.object,delete e.property,delete e.computed;return}if(e.computed&&e.object&&cd.includes(e.object.type)&&!e._historyTransformed){i.enterHistoryRecord();try{e.object=cf(e.object,i)}finally{i.exitHistoryRecord()}e.property=c_(e.property,i);let t=i.generateParamId(),r={type:"CallExpression",callee:h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("param")),arguments:[e.object,cr(),cn(i,t)],_transformed:!0,_isParamCall:!0},n=r;i.addEagerHoistedStatement(h0.createVariableDeclaration(t,r))&&((n=h0.createIdentifier(t))._skipTransformation=!0,n._arrayAccessed=!0);let s=h0.createGetCall(n,e.property);s._transformed=!0,s._historyTransformed=!0,Object.assign(e,s),delete e.object,delete e.property,delete e.computed;return}if(e.object&&"Identifier"===e.object.type&&oP.includes(e.object.name)&&i.isContextBound(e.object.name)&&!e.computed){let t=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e,i=e.parent&&("VariableDeclarator"===e.parent.type&&("ArrayPattern"===e.parent.id.type||"ObjectPattern"===e.parent.id.type)||"AssignmentExpression"===e.parent.type&&("ArrayPattern"===e.parent.left.type||"ObjectPattern"===e.parent.left.type)||"Property"===e.parent.type);if(!t&&!i){let t={type:"CallExpression",callee:{type:"MemberExpression",object:e.object,property:e.property,computed:!1},arguments:[],_transformed:!1};void 0!==e.start&&(t.start=e.start),void 0!==e.end&&(t.end=e.end),Object.assign(e,t);return}}if(!e.computed&&e.object&&"Identifier"===e.object.type&&i.isLocalSeriesVar(e.object.name)){let t=h0.createIdentifier(e.object.name);t._skipTransformation=!0,e.object=h0.createGetCall(t,0);return}let r="if"==i.getCurrentScopeType(),n="els"==i.getCurrentScopeType(),s="for"==i.getCurrentScopeType();if(!r&&!n&&!s&&e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)&&!e.computed)return;e._indexTransformed||(cl(e,i),e._indexTransformed=!0);let a=e.object&&"MemberExpression"===e.object.type&&e.object.object&&"MemberExpression"===e.object.object.type&&e.object.object.object&&("$"===e.object.object.object.name||"$$"===e.object.object.object.name),o=e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name);if(e.computed&&(a||o)){if(e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left===e)return;"Identifier"===e.object.type&&oD.includes(e.object.name)&&i.isContextBound(e.object.name)&&(e.object={type:"MemberExpression",object:{type:"Identifier",name:e.object.name},property:{type:"Identifier",name:"__value"},computed:!1});let t=h0.createGetCall(e.object,e.property);e.start&&(t.start=e.start),e.end&&(t.end=e.end),Object.assign(e,t),delete e.object,delete e.property,delete e.computed;return}if(e.computed&&e.object&&"MemberExpression"===e.object.type){let t=e.object;for(;t.object&&"MemberExpression"===t.object.type;)t=t.object;if(t.object&&"Identifier"===t.object.type&&i.isUdtInstance(t.object.name)){let r=t.object.name,n=i.isLocalSeriesVar(r)?(()=>{let e=h0.createIdentifier(r);return e._skipTransformation=!0,e})():cs(r,i),s=e._indexTransformed?e.property:ch(e.property,i);Object.assign(e,cc(e.object,r,n,s,i)),delete e.computed;return}}}function cx(e,t){if("Identifier"===e.type){if(oD.includes(e.name)&&t.isContextBound(e.name)){let t=e.name;return Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"__value"},computed:!1}),delete e.name,e}if(t.isLoopVariable(e.name))return e;if(t.isRootParam(e.name)){let[i,r]=t.getVariable(e.name);return h0.createContextVariableReference(r,i)}if(t.isContextBound(e.name))return e;let[i,r]=t.getVariable(e.name),n=i!==e.name,s=t.isFunctionParam(e.name)&&!t.isVariableInFunctionScope(e.name);return t.isLocalSeriesVar(e.name)&&(!n||s)?e:n||i!==e.name||t.isContextBound(e.name)?cs(e.name,t):e}return e}function cb(e,t,i=""){switch(e.type){case"BinaryExpression":return cv(e,t,i);case"LogicalExpression":return cw(e,t,i);case"MemberExpression":{let r=!e.computed&&"Identifier"===e.object.type&&oD.includes(e.object.name)&&t.isContextBound(e.object.name);if(e.computed&&"Identifier"===e.object.type&&oD.includes(e.object.name)&&t.isContextBound(e.object.name)){let i={type:"MemberExpression",object:{type:"Identifier",name:e.object.name},property:{type:"Identifier",name:"__value"},computed:!1};return h0.createGetCall(i,c_(e.property,t))}if(e.computed&&cm(e.object,t))return cg(e,"",t),e;e.computed||"CallExpression"!==e.object.type||e.object._transformed?e.computed||"MemberExpression"!==e.object.type||e.object.computed||(e.object=cb(e.object,t,i),e.object.parent=e,cg(e.object,"",t)):cC(e.object,t);let n="Identifier"!==e.object.type||r?e.object:cx(e.object,t),s=n;if(!e.computed&&"Identifier"===e.object.type&&!r){let[i]=t.getVariable(e.object.name);i===e.object.name||t.isLoopVariable(e.object.name)||(s=h0.createGetCall(n,0))}return{type:"MemberExpression",object:s,property:e.property,computed:e.computed}}case"Identifier":{if(t.isLoopVariable(e.name)||e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e)return e;let i=cx(e,t);return"Identifier"===i.type&&("NaN"===i.name||"undefined"===i.name||"Infinity"===i.name||"null"===i.name||"Math"===i.name)?i:h0.createGetCall(i,0)}case"UnaryExpression":return cE(e,t,i);case"ConditionalExpression":{let r=cb(e.test,t,i);return{type:"ConditionalExpression",test:r,consequent:cb(e.consequent,t,i),alternate:cb(e.alternate,t,i),start:e.start,end:e.end}}}return e}function cv(e,t,i){let r=cb(e.left,t,i),n=cb(e.right,t,i),s={type:"BinaryExpression",operator:e.operator,left:r,right:n,start:e.start,end:e.end};return hY(s,t,{CallExpression(e,t){e._transformed||cC(e,t)},MemberExpression(e){cg(e,"",t)}}),s}function cw(e,t,i){let r=cb(e.left,t,i),n=cb(e.right,t,i),s={type:"LogicalExpression",operator:e.operator,left:r,right:n,start:e.start,end:e.end};return hY(s,t,{CallExpression(e,t){e._transformed||cC(e,t)}}),s}function cS(e,t){hY(e,{parent:e,inNamespaceCall:!1},{Identifier(e,i,r){if("NaN"==e.name)return;if(oD.includes(e.name)&&t.isContextBound(e.name)){if(i.parent&&"MemberExpression"===i.parent.type&&i.parent.object===e&&!i.parent.computed)return;let t={type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Identifier",name:"__value"},computed:!1};Object.assign(e,h0.createGetCall(t,0)),delete e.name;return}e.parent=i.parent,cu(e,t);let n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?cl(e,t):"Identifier"===e.type&&(e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&e.parent.callee.object&&"$"===e.parent.callee.object.name&&"get"===e.parent.callee.property.name||cp(e)))},MemberExpression(e,i,r){cg(e,"",t),e.object&&r(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},ConditionalExpression(e,t,i){let r={...t,parent:e};e.test&&i(e.test,r),e.consequent&&i(e.consequent,r),e.alternate&&i(e.alternate,r)},BinaryExpression(e,t,i){let r={...t,parent:e};i(e.left,r),i(e.right,r)},LogicalExpression(e,t,i){let r={...t,parent:e};i(e.left,r),i(e.right,r)},UnaryExpression(e,t,i){let r={...t,parent:e};i(e.argument,r)},CallExpression(e,i,r){let n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);cC(e,t),"CallExpression"!==e.type||cI(e)||e.arguments.forEach(t=>r(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall}))}})}function cE(e,t,i){let r=cb(e.argument,t,i),n={type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:r,start:e.start,end:e.end};return hY(n,t,{CallExpression(e,t){e._transformed||cC(e,t)},MemberExpression(e){cg(e,"",t)}}),n}function cN(e,t){let i=e;for(;i&&"MemberExpression"===i.type&&i.object;){if("Identifier"===i.object.type){let e=i.object,[r]=t.getVariable(e.name);r===e.name||t.isContextBound(e.name)||t.isRootParam(e.name)||t.isLoopVariable(e.name)||t.isLocalSeriesVar(e.name)||oD.includes(e.name)||oP.includes(e.name)||(i.object=ca(e.name,t));break}i=i.object}}let cT=e=>e?.type==="Identifier"&&"undefined"===e.name;function ck(e,t,i){switch(e?.type){case"BinaryExpression":e=cv(e,i,t);break;case"LogicalExpression":e=cw(e,i,t);break;case"ConditionalExpression":var r=e;cS(r,i);let n=h0.createMemberExpression(h0.createIdentifier(t),h0.createIdentifier("param")),s=i.generateParamId(),a={type:"CallExpression",callee:n,arguments:[r,cr(),cn(i,s)],_transformed:!0,_isParamCall:!0};if(!i.shouldSuppressHoisting()){i.addLocalSeriesVar(s);let e=h0.createVariableDeclaration(s,a);return i.addHoistedStatement(e),h0.createIdentifier(s)}return a;case"UnaryExpression":e=cE(e,i,t);break;case"ArrayExpression":e.elements=e.elements.map(e=>{if("Identifier"===e.type){if(i.isContextBound(e.name)&&!i.isRootParam(e.name))return oD.includes(e.name)&&"na"!==e.name?h0.createMemberExpression(h0.createIdentifier(e.name),h0.createIdentifier("__value")):e;if(i.isLocalSeriesVar(e.name)){let t=h0.createIdentifier(e.name);return h0.createGetCall(t,0)}return ca(e.name,i)}return"CallExpression"===e.type?(cC(e,i),e):"BinaryExpression"===e.type?cv(e,i,t):"LogicalExpression"===e.type?cw(e,i,t):"ConditionalExpression"===e.type?(cS(e,i),e):"UnaryExpression"===e.type?cE(e,i,t):("MemberExpression"===e.type&&(cg(e,t,i),e.computed||cN(e,i)),e)})}e?.type==="MemberExpression"&&e.computed&&cm(e.object,i)&&cg(e,"",i);let o="MemberExpression"===e.type&&e.computed&&e.property,l="MemberExpression"===e.type&&!e.computed;if(o){let r;if(e.object&&"MemberExpression"===e.object.type){let r=e.object;for(;r.object&&"MemberExpression"===r.object.type;)r=r.object;if(r.object?.type==="Identifier"&&i.isUdtInstance(r.object.name)){let n=r.object.name,s=i.isLocalSeriesVar(n)?(()=>{let e=h0.createIdentifier(n);return e._skipTransformation=!0,e})():cs(n,i);return e._udtIndexTransformed||(e.property=ch(e.property,i,t),e._udtIndexTransformed=!0),cc(e.object,n,s,e.property,i)}}let n=cd.includes(e.object.type);if(n){i.enterHistoryRecord();try{e.object=cf(e.object,i)}finally{i.exitHistoryRecord()}}else"MemberExpression"===e.object.type&&(cg(e.object,"",i),cN(e.object,i),n="CallExpression"===e.object.type);let s="Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)?oD.includes(e.object.name)?h0.createMemberExpression(h0.createIdentifier(e.object.name),h0.createIdentifier("__value")):e.object:cx(e.object,i);if("Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name))if("Identifier"===e.property.type&&i.isContextBound(e.property.name)&&!i.isLoopVariable(e.property.name)){let t=e.property.name,i=oD.includes(t)?h0.createMemberExpression(h0.createIdentifier(t),h0.createIdentifier("__value")):h0.createIdentifier(t);r=h0.createGetCall(i,0)}else if("BinaryExpression"===e.property.type||"UnaryExpression"===e.property.type||"LogicalExpression"===e.property.type||"ConditionalExpression"===e.property.type)r=cb(e.property,i,t);else if("MemberExpression"===e.property.type){cl(e.property,i);let t=e=>{"MemberExpression"===e.type&&(e.computed&&t(e.property),cg(e,"",i))};t(e.property),r=e.property}else"CallExpression"===e.property.type&&(e.property._transformed||cC(e.property,i)),r=e.property;else r=h0.createGetCall(cx(e.property,i),0);let a=s,o=r;if(n){let t=i.generateParamId(),n={type:"CallExpression",callee:h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("param")),arguments:[e.object,cr(),cn(i,t)],_transformed:!0,_isParamCall:!0},s=n;i.addEagerHoistedStatement(h0.createVariableDeclaration(t,n))&&((s=h0.createIdentifier(t))._skipTransformation=!0,s._arrayAccessed=!0),(a=h0.createGetCall(s,r))._transformed=!0,a._historyTransformed=!0,o=cr()}let l=h0.createMemberExpression(h0.createIdentifier(t),h0.createIdentifier("param")),h=i.generateParamId(),c={type:"CallExpression",callee:l,arguments:[a,o,cn(i,h)],_transformed:!0,_isParamCall:!0};if(!i.shouldSuppressHoisting()){i.addLocalSeriesVar(h);let e=h0.createVariableDeclaration(h,c);return i.addHoistedStatement(e),h0.createIdentifier(h)}return c}if(l){if("Identifier"===e.object.type&&oP.includes(e.object.name)&&i.isContextBound(e.object.name)&&!e.computed){let t=e.object.name,r={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:e.property.name},computed:!1},arguments:[],_transformed:!0};"ta"===t&&r.arguments.push(i.getNextTACallId());let n=i.generateTempVar();i.addLocalSeriesVar(n);let s=h0.createVariableDeclaration(n,r);return i.addOuterHoistedStatement(s),Object.assign(e,h0.createIdentifier(n)),e}if("Identifier"===e.object.type){let t=e.object.name,[r,n]=i.getVariable(t);if(r===t||i.isLoopVariable(t)){if(i.isLocalSeriesVar(t)){let i=h0.createIdentifier(t);i._skipTransformation=!0,e.object=h0.createGetCall(i,0)}}else{let r=cs(t,i),n=h0.createGetCall(r,0);e.object=n}}else"MemberExpression"===e.object.type?ck(e.object,t,i):"CallExpression"===e.object.type&&(e.object._transformed||cC(e.object,i))}if("ObjectExpression"===e.type&&(e.properties=e.properties.map(e=>{if(e.value.name){if(oD.includes(e.value.name)&&"na"!==e.value.name&&i.isContextBound(e.value.name)){let t=h0.createMemberExpression(h0.createIdentifier(e.value.name),h0.createIdentifier("__value"));return{...e,shorthand:!1,value:h0.createGetCall(t,0)}}return i.isContextBound(e.value.name)||i.isLocalSeriesVar(e.value.name)||i.isLoopVariable(e.value.name)?{type:"Property",key:{type:"Identifier",name:e.key.name},value:h0.createIdentifier(e.value.name),kind:"init",method:!1,shorthand:!1,computed:!1}:{type:"Property",key:{type:"Identifier",name:e.key.name},value:cs(e.value.name,i),kind:"init",method:!1,shorthand:!1,computed:!1}}return"Literal"!==e.value.type&&(e.value=ck(e.value,t,i)),e})),"Identifier"===e.type){if(oD.includes(e.name)&&i.isContextBound(e.name)){let t=e.name;Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"__value"},computed:!1}),delete e.name}else if(i.isContextBound(e.name)&&!i.isRootParam(e.name)){let r=h0.createMemberExpression(h0.createIdentifier(t),h0.createIdentifier("param")),n=i.generateParamId(),s={type:"CallExpression",callee:r,arguments:[e,cr(),cn(i,n)],_transformed:!0,_isParamCall:!0};if(!i.shouldSuppressHoisting()){i.addLocalSeriesVar(n);let e=h0.createVariableDeclaration(n,s);return i.addHoistedStatement(e),h0.createIdentifier(n)}return s}}e?.type==="CallExpression"&&cC(e,i,t);let h=h0.createMemberExpression(h0.createIdentifier(t),h0.createIdentifier("param")),c="Identifier"===e.type?cx(e,i):e,p=i.generateParamId(),u={type:"CallExpression",callee:h,arguments:[c,cr(),cn(i,p)],_transformed:!0,_isParamCall:!0};if(!i.shouldSuppressHoisting()){i.addLocalSeriesVar(p);let e=h0.createVariableDeclaration(p,u);return i.addHoistedStatement(e),h0.createIdentifier(p)}return u}function cA(e){return e?.type==="CallExpression"&&e.callee?.type==="MemberExpression"&&e.callee.object?.name==="$"&&e.callee.property?.name==="get"}function cI(e){return!!e&&"CallExpression"===e.type&&!0===e._transformed&&!0===e._lazyOperand}function cC(e,t,i){if(!e._transformed){if(!0===e._lazyOperand&&!t.shouldSuppressHoisting()){t.setSuppressHoisting(!0);try{cM(e,t,i)}finally{t.setSuppressHoisting(!1)}return}cM(e,t)}}function cM(e,t,i){let r;e.callee&&e.callee.name,e.callee&&"Identifier"===e.callee.type&&(oP.includes(e.callee.name)||oD.includes(e.callee.name))&&t.isContextBound(e.callee.name)&&(e.callee=h0.createMemberExpression(e.callee,h0.createIdentifier("any")));let n=e.callee?.type==="MemberExpression"&&!e.callee.computed&&e.callee.object?.type==="Identifier"&&e.callee.object.name in ci&&e.callee.property?.type==="Identifier"&&t.isUserMethod(e.callee.property.name),s=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&!n&&(t.isContextBound(e.callee.object.name)||"math"===e.callee.object.name||"ta"===e.callee.object.name),a=!s&&e.callee?.type==="MemberExpression";if(s){if("$"===e.callee.object.name&&["get","init","param"].includes(e.callee.property.name))return;let i=e.callee.object.name;"syminfo"===i&&!e.callee.computed&&["ticker","prefix"].includes(e.callee.property?.name)&&(e.callee.property=h0.createIdentifier(`__${e.callee.property.name}`));let r=[];e.arguments.forEach(e=>{if(e._isParamCall||cT(e))return void r.push(e);r.push(ck(e,i,t))}),e.arguments=r;let n=e.callee.property.name,s=`${i}.${n}`;if(oj.includes(i)||oj.includes(s)){let i=t.getNextPlotCallId();e.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:i,kind:"init",computed:!1,shorthand:!1}]})}if("input"===i&&void 0!==e._varId&&e.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__varId"},value:{type:"Literal",value:e._varId},kind:"init",computed:!1,shorthand:!1}]}),"alert"===i){let i=t.getNextAlertCallId();e.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:i,kind:"init",computed:!1,shorthand:!1}]})}if("ta"===i||"math.random"===s||"math.sum"===s)if(t.isInsideFunctionScope()){let i=t.getNextTACallId(),[r]=t.getVariable("$$"),n={type:"BinaryExpression",operator:"+",left:r?h0.createMemberExpression(h0.createLocalContextIdentifier(),h0.createIdentifier("id")):h0.createLiteral(""),right:i};e.arguments.push(n)}else e.arguments.push(t.getNextTACallId());let a=e.callee.property.name,o=`${i}.${a}`,l=oR.includes(o),h=!0===e._insideAwait;if(l&&!h){let t=Object.assign({},e);Object.assign(e,h0.createAwaitExpression(t))}if(!t.shouldSuppressHoisting()){let i=t.generateTempVar();t.addLocalSeriesVar(i);let r=!0===e._insideAwait,n=Object.assign({},e);r&&(n=h0.createAwaitExpression(n));let s=h0.createVariableDeclaration(i,n);t.addHoistedStatement(s),Object.assign(e,h0.createIdentifier(i)),e._wasHoisted=!0,e._wasInsideAwait=r;return}e._transformed=!0}else if(e.callee&&"Identifier"===e.callee.type){if(e.arguments=e.arguments.map(e=>e._isParamCall||cT(e)?e:ck(e,"$",t)),"Type"===e.callee.name&&e._udtName&&t.isMethodReceiverTypeName(e._udtName)&&e.arguments.push({type:"Literal",value:e._udtName,raw:JSON.stringify(e._udtName)}),oV.includes(e.callee.name)&&t.isContextBound(e.callee.name)&&e.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:t.getNextBareCallsiteId(e.callee.name),kind:"init",computed:!1,shorthand:!1}]}),!t.isContextBound(e.callee.name)){let i=t.getNextUserCallId(),r=h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("call")),n=e.callee.name,s=e.callee;t.isUserMethod(n)&&!t.isRegularUserFunction(n)&&((s=h0.createIdentifier(`$M_${n}`))._skipTransformation=!0);let a=[s,i,...e.arguments];e.callee=r,e.arguments=a}e._transformed=!0}if(!s&&e.callee&&"MemberExpression"===e.callee.type){let i,n=e.callee.property.name,s=t.isUserFunction(n),a=e.callee.object,o=t.isUserMethod(n);if(a.name)i=t.getVariableUdtType(a.name)??t.getVarStaticType(a.name);else if("MemberExpression"===a.type&&!a.computed&&a.property?.type==="Identifier"&&a.object?.name){let e=t.getVariableUdtType(a.object.name);e&&(i=hW(t.getUdtTypeFields(e)?.[a.property.name]))}let l="Literal"===a.type?"string"==typeof a.value?"string":"boolean"==typeof a.value?"bool":void 0:"Identifier"===a.type&&a.name in ci&&t.isContextBound(a.name)?ci[a.name]:void 0,h=i??l,c=t.getMethodCandidates(n),p=e=>t.getMethodReceiverType(e.slice(3)),u=c.find(e=>{var t;return t=p(e),!!h&&!!t&&(h===t||"int"===h&&"float"===t)}),d=void 0!==u,m=i??function(e,t){if(e?._orderflowType)return e._orderflowType;if(e?.type!=="CallExpression"||e.callee?.type!=="MemberExpression"||e.callee.computed||!oz.has(e.callee.property?.name))return;let i=e.callee.object;return i?.name&&!t.getVariableUdtType(i.name)&&"footprint"===t.getVarStaticType(i.name)?"volume_row":void 0}(a,t);m&&oq[m]?.has(n)&&(r=m);let f=!!a.name&&t.isUdtInstance(a.name),y=void 0===i&&!oF.has(n),_=void 0===h&&!f&&(oF.has(n)||c.length>1);if(s&&o&&(!t.isContextBound(n)||d)&&(d||f||y||_)){let i=e.callee.object;e.callee.property;let r=e.arguments.map(e=>e._isParamCall||cT(e)?e:ck(e,"$",t));"CallExpression"===i.type&&cC(i,t);let s=ck(i,"$",t),a=h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("call")),o=t.getNextUserCallId();if(_){let i=(c.length?c:[`$M_${n}`]).map(e=>{let i=h0.createIdentifier(e);i._skipTransformation=!0;let r=p(e);return{type:"ArrayExpression",elements:[i,r&&t.isUdtTypeName(r)?{type:"Literal",value:r,raw:JSON.stringify(r)}:{type:"Literal",value:null,raw:"null"}]}});e.callee=h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("callMethod")),e.arguments=[{type:"Literal",value:n,raw:JSON.stringify(n)},o,{type:"ArrayExpression",elements:i},s,...r],e._transformed=!0;return}let l=h0.createIdentifier(u??c[0]??`$M_${n}`);l._skipTransformation=!0;let h=[l,o,s,...r];e.callee=a,e.arguments=h,e._transformed=!0;return}"Identifier"===e.callee.object.type?cu(e.callee.object,t):function e(t,i,r){t&&("Identifier"===t.type?(t.parent=i,cu(t,r)):"MemberExpression"===t.type?(e(t.object,t,r),t.parent=i,cg(t,"",r),"CallExpression"!==t.type||t._transformed||cC(t,r)):"CallExpression"===t.type&&(t.callee&&"MemberExpression"===t.callee.type&&e(t.callee.object,t.callee,r),t._transformed||cC(t,r)))}(e.callee.object,e.callee,t)}if(e.arguments.forEach(i=>{hY(i,{parent:e},{Identifier(e,i,r){e.parent=i.parent,cu(e,t);let n=e.parent&&"BinaryExpression"===e.parent.type,s=e.parent&&"ConditionalExpression"===e.parent.type,o=a&&e.parent?.type==="Property"&&e.parent.value===e;(s||n||o)&&("MemberExpression"===e.type?cl(e,t):"Identifier"===e.type&&(e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&e.parent.callee.object&&"$"===e.parent.callee.object.name&&"get"===e.parent.callee.property.name||cp(e)))},BinaryExpression(e,t,i){let r={...t,parent:e};i(e.left,r),i(e.right,r)},LogicalExpression(e,t,i){let r={...t,parent:e};i(e.left,r),i(e.right,r)},UnaryExpression(e,t,i){let r={...t,parent:e};i(e.argument,r)},ConditionalExpression(e,t,i){let r=a?{...t,parent:e}:t;i(e.test,r),i(e.consequent,r),i(e.alternate,r)},ObjectExpression(e,t,i){for(let r of e.properties)i(r.value,a?{...t,parent:r}:t)},CallExpression(e,i,r){e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&(e.callee.object.parent=e.callee,r(e.callee.object,{parent:e.callee})),e._transformed||cC(e,t)},MemberExpression(e,i,r){cg(e,"",t),e.object&&r(e.object,{parent:e})}})}),r&&!e._transformed){let t=e.callee.property.name,i=h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("pine")),n=h0.createMemberExpression(i,h0.createIdentifier(r));e.arguments=[e.callee.object,...e.arguments],e.callee=h0.createMemberExpression(n,h0.createIdentifier(t)),"footprint"===r&&oz.has(t)&&(e._orderflowType="volume_row"),e._transformed=!0;return}if(e.callee&&"MemberExpression"===e.callee.type){let t=e.callee.object,i=cA(t),r=t?.type==="MemberExpression"&&function e(t){if(!t)return!1;if(cA(t))return!0;if("MemberExpression"===t.type)return e(t.object);if("ChainExpression"===t.type)return e(t.expression);if("CallExpression"===t.type){let i=t.callee;if(i?.type==="MemberExpression")return e(i.object);if(i?.type==="ChainExpression")return e(i.expression)}return!1}(t),n=t?.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&t.callee.object?.name==="$"&&["call","callMethod"].includes(t.callee.property?.name),s=t?.type==="MemberExpression"&&!t.computed&&t.property?.type==="Identifier"||n,a=!e.callee.computed&&e.callee.property?.name==="delete"&&s;if(!e.callee.computed&&/^(get|set)_\w+$/.test(e.callee.property?.name??"")&&(i||r||s)&&(e.callee.object={type:"CallExpression",callee:h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("drawingOrNa")),arguments:[t],_transformed:!0}),i||r||a){let t=Object.assign({},e.callee,{optional:!0});e.callee={type:"ChainExpression",expression:t},e.optional=!0}}}function cP(e){let t={type:"IfStatement",test:{type:"BinaryExpression",operator:">",_skipCompare:!0,left:{type:"UpdateExpression",operator:"++",prefix:!0,argument:{type:"Identifier",name:e}},right:{type:"Identifier",name:"__maxLoops"}},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"$"},property:{type:"Identifier",name:"loopError"},computed:!1},arguments:[{type:"Literal",value:`Loop exceeded maximum iterations (${e})`}]}},alternate:null};return{counterDecl:{type:"VariableDeclaration",kind:"let",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:e},init:{type:"Literal",value:0}}]},guardCheck:t}}function cD(e,t){let i=null;if("Identifier"===e.left.type)i=cs(e.left.name,t);else if("MemberExpression"===e.left.type&&e.left.computed){if("Identifier"===e.left.object.type){let r=e.left.object.name,[n,s]=t.getVariable(r),a=n!==r,o=t.isContextBound(r);(a||o)&&!t.isLoopVariable(r)&&"Literal"===e.left.property.type&&0===e.left.property.value&&(i=cs(r,t))}}else if("MemberExpression"===e.left.type&&!e.left.computed){let i=null,r=e.left;for(;"MemberExpression"===r.type&&!r.computed;){if("Identifier"===r.object.type){i=r;break}r=r.object}if(i){let e=i.object.name,[r,n]=t.getVariable(e);if(r===e||t.isLoopVariable(e)){if(t.isLocalSeriesVar(e)){let t=h0.createIdentifier(e);t._skipTransformation=!0,i.object=h0.createGetCall(t,0)}}else{let r=cs(e,t),n=h0.createGetCall(r,0);i.object=n}}}let r=e=>{if(e){if("CallExpression"===e.type&&(e.callee?.type==="ArrowFunctionExpression"||e.callee?.type==="FunctionExpression")){(e.callee.body?.type==="BlockStatement"?e.callee.body.body:[]).some(e=>/^(For|ForOf|ForIn|While|DoWhile)Statement$/.test(e.type))||(cR(e,t),e._iifeTransformed=!0);return}"BinaryExpression"===e.type||"LogicalExpression"===e.type?(r(e.left),r(e.right)):"ConditionalExpression"===e.type?(r(e.test),r(e.consequent),r(e.alternate)):"UnaryExpression"===e.type&&r(e.argument)}};if(r(e.right),hY(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,r){let n=i.parent&&"MemberExpression"===i.parent.type&&!i.parent.computed&&i.parent.object===e;if(oD.includes(e.name)&&t.isContextBound(e.name)&&!n){let t={type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Identifier",name:"__value"},computed:!1};Object.assign(e,h0.createGetCall(t,0)),delete e.name;return}e.parent=i.parent,cu(e,t);let s=e.parent&&"BinaryExpression"===e.parent.type,a=e.parent&&"ConditionalExpression"===e.parent.type,o=t.isContextBound(e.name)&&!t.isRootParam(e.name),l=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,h=e.parent&&e.parent._isParamCall,c=e.parent&&"MemberExpression"===e.parent.type,p="NaN"===e.name,u=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&e.parent.callee.object&&"$"===e.parent.callee.object.name&&"get"===e.parent.callee.property.name;(o||a||s)&&("MemberExpression"===e.type?cl(e,t):"Identifier"!==e.type||c||l||h||p||u||cp(e))},MemberExpression(e,i,r){cg(e,"",t),"CallExpression"===e.type?e.arguments.forEach(t=>r(t,{parent:e,inNamespaceCall:i.inNamespaceCall})):e.object&&r(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,r){if(e._iifeTransformed)return;let n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);cC(e,t),"CallExpression"!==e.type||cI(e)||("MemberExpression"===e.callee.type&&r(e.callee,{parent:e,inNamespaceCall:n||i.inNamespaceCall}),e.arguments.forEach(t=>r(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}}),i){let t=e.right;"="!==e.operator&&(t={type:"BinaryExpression",operator:e.operator.replace("=",""),left:h0.createGetCall(i,0),right:e.right,start:e.start,end:e.end});let r=h0.createSetCall(i,t);e.start&&(r.start=e.start),e.end&&(r.end=e.end),Object.assign(e,r)}}function cR(e,t){hY(e,{parent:e},{Identifier(e,i){e.parent=i.parent,cu(e,t);let r=e.parent&&"BinaryExpression"===e.parent.type,n=e.parent&&"UnaryExpression"===e.parent.type,s=e.parent&&"ConditionalExpression"===e.parent.type,a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&e.parent.callee.object&&"$"===e.parent.callee.object.name&&"get"===e.parent.callee.property.name;"Identifier"===e.type&&(r||n||s)&&!a&&cp(e)},CallExpression(e,i,r){"Identifier"===e.callee.type&&(e.callee.parent=e),e.arguments.forEach(t=>{"Identifier"===t.type&&(t.parent=e)}),("ArrowFunctionExpression"===e.callee.type||"FunctionExpression"===e.callee.type)&&r(e.callee,{parent:e}),cC(e,t),"CallExpression"!==e.type||cI(e)||("MemberExpression"===e.callee.type&&r(e.callee,{parent:e}),e.arguments.forEach(t=>r(t,{parent:e})))},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},LogicalExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},UnaryExpression(e,t,i){"Identifier"===e.argument.type&&(e.argument.parent=e),i(e.argument,{parent:e})},MemberExpression(e,i,r){e.object&&"Identifier"===e.object.type&&(e.object.parent=e),e.property&&"Identifier"===e.property.type&&(e.property.parent=e),cg(e,"",t),"CallExpression"===e.type?e.arguments.forEach(t=>r(t,{parent:e})):e.object&&r(e.object,{parent:e})},AwaitExpression(e,t,i){e.argument&&(e.argument._insideAwait=!0,i(e.argument,{parent:e}),"Identifier"===e.argument.type&&e.argument._wasInsideAwait&&Object.assign(e,e.argument))},ArrowFunctionExpression(e,i,r){if(e.body)if("BlockStatement"===e.body.type){let i=[];e.body.body.forEach(n=>{t.enterHoistingScope(),r(n,{parent:e.body,insideIIFE:!0});let s=t.exitHoistingScope();i.push(...s),i.push(n)}),e.body.body=i}else r(e.body,{parent:e,insideIIFE:!0})},FunctionExpression(e,i,r){if(e.body&&"BlockStatement"===e.body.type){let i=[];e.body.body.forEach(n=>{t.enterHoistingScope(),r(n,{parent:e.body,insideIIFE:!0});let s=t.exitHoistingScope();i.push(...s),i.push(n)}),e.body.body=i}},BlockStatement(e,i,r){let n=[];e.body.forEach(s=>{t.enterHoistingScope(),r(s,{...i,parent:e});let a=t.exitHoistingScope();n.push(...a),n.push(s)}),e.body=n},SwitchStatement(e,t,i){e.discriminant&&(e.discriminant.parent=e,i(e.discriminant,{parent:e})),e.cases&&e.cases.forEach(r=>{r.parent=e,i(r,{parent:e,insideIIFE:t.insideIIFE})})},SwitchCase(e,i,r){if(e.test&&(e.test.parent=e,r(e.test,{parent:e,insideIIFE:i.insideIIFE})),e.consequent){let n=[];e.consequent.forEach(s=>{t.enterHoistingScope(),s.parent=e,r(s,{parent:e,insideIIFE:i.insideIIFE});let a=t.exitHoistingScope();n.push(...a),n.push(s)}),e.consequent=n}},AssignmentExpression(e,i,r){if(i.insideIIFE){if("Identifier"===e.left.type){let[i]=t.getVariable(e.left.name);if(i===e.left.name&&!t.isContextBound(e.left.name))return void r(e.right,{parent:e})}cD(e,t)}}})}function cO(e,t,i){if(t.setSuppressHoisting(!0),t.setInLoopTest(!0),e.init&&"VariableDeclaration"===e.init.type){let i=e.init.declarations.map(e=>(t.addLoopVariable(e.id.name,e.id.name),{type:"VariableDeclarator",id:{type:"Identifier",name:e.id.name},init:e.init}));for(let r of(e.init={type:"VariableDeclaration",kind:e.init.kind,declarations:i},i))r.init&&hY(r.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||e.computed||(t.pushScope("for"),cu(e,i),"Identifier"===e.type&&(t.isContextBound(e.name)&&e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e||(e.computed=!0,cp(e))),t.popScope())},MemberExpression(e,i,r){t.pushScope("for"),cg(e,"",t),t.popScope(),"MemberExpression"===e.type&&e.object&&("Identifier"!==e.object.type||!t.isContextBound(e.object.name))&&r(e.object,i)},CallExpression(e,t,i){for(let r of(e.callee.parent=e,i(e.callee,t),e.arguments))i(r,t)}})}e.test&&hY(e.test,t,{Identifier(e,i){t.isLoopVariable(e.name)||e.computed||(t.pushScope("for"),cu(e,i),"Identifier"===e.type&&(t.isContextBound(e.name)&&e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e||(e.computed=!0,cp(e))),t.popScope())},MemberExpression(e,i,r){t.pushScope("for"),cg(e,"",t),t.popScope(),"MemberExpression"===e.type&&e.object&&("Identifier"!==e.object.type||!t.isContextBound(e.object.name))&&r(e.object,i)},CallExpression(e,t,i){for(let r of(e.callee.parent=e,i(e.callee,t),e.arguments))i(r,t)}}),e.update&&hY(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||e.computed||(t.pushScope("for"),cu(e,i),"Identifier"===e.type&&(t.isContextBound(e.name)&&e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e||(e.computed=!0,cp(e))),t.popScope())},MemberExpression(e,i,r){t.pushScope("for"),cg(e,"",t),t.popScope(),"MemberExpression"===e.type&&e.object&&("Identifier"!==e.object.type||!t.isContextBound(e.object.name))&&r(e.object,i)},CallExpression(e,t,i){for(let r of(e.callee.parent=e,i(e.callee,t),e.arguments))i(r,t)}}),t.setSuppressHoisting(!1),t.setInLoopTest(!1);let r=cP(t.getNextLoopGuardName());if(t.addHoistedStatement(r.counterDecl),t.pushScope("for"),i(e.body,t),t.popScope(),"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[e.body]}),e.body.body.unshift(r.guardCheck),e.init&&"VariableDeclaration"===e.init.type)for(let i of e.init.declarations)t.removeLoopVariable(i.id.name)}function cj(e,t,i){t.setSuppressHoisting(!0),t.setInLoopTest(!0),e.test&&cV(e.test,t),t.setSuppressHoisting(!1),t.setInLoopTest(!1);let r=cP(t.getNextLoopGuardName());t.addHoistedStatement(r.counterDecl),t.pushScope("whl"),i(e.body,t),t.popScope(),"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[e.body]}),e.body.body.unshift(r.guardCheck)}function cV(e,t){hY(e,t,{MemberExpression(e,i,r){(!e.object||"Identifier"!==e.object.type||t.isContextBound(e.object.name)||e.computed)&&(!e.object||e.computed||"CallExpression"!==e.object.type&&"MemberExpression"!==e.object.type)||(e.object.parent=e,r(e.object,i)),cg(e,"",t)},CallExpression(e,t){cC(e,t)},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,t),i(e.right,t)},LogicalExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,t),i(e.right,t)},UnaryExpression(e,t,i){"Identifier"===e.argument.type&&(e.argument.parent=e),i(e.argument,t)},Identifier(e,i){let r=e.parent,n=r&&"UnaryExpression"===r.type,s=r&&"BinaryExpression"===r.type,a=r&&"LogicalExpression"===r.type,o=r&&"ConditionalExpression"===r.type;cu(e,i),"Identifier"===e.type&&(n||s||a||o)&&(r&&"CallExpression"===r.type&&r.callee&&r.callee.object&&"$"===r.callee.object.name&&r.callee.property?.name==="get"||cp(e));let l="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&l&&cp(e)}})}function c$(e,t,i){let r=e.object;if(!(!r||e.computed))if("Identifier"===r.type){if(t.isContextBound(r.name))return;r.parent=e,cu(r,t)}else{var n;"MemberExpression"!==r.type&&("CallExpression"!==r.type||(n=r,n.callee?.type==="MemberExpression"&&n.callee.object?.type==="Identifier"&&"$"===n.callee.object.name))||(r.parent=e,i(r,t))}}let cL={"==":"__eq","===":"__eq","!=":"__neq","!==":"__neq","<":"__lt","<=":"__le",">":"__gt",">=":"__ge"},cB=new Set(["<","<=",">",">="]),cF={"&&":"__and","||":"__or"},cq={"+":"__union","-":"__minus"};function cz(e){return e?.type==="MemberExpression"&&!e.computed&&e.object?.type==="Identifier"&&"display"===e.object.name||e?.type==="CallExpression"&&!0===e._displaySetOp}var cU=Object.defineProperty,cW=(e,t,i)=>((e,t,i)=>t in e?cU(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let cK={NUMBER:"NUMBER",STRING:"STRING",BOOLEAN:"BOOLEAN",IDENTIFIER:"IDENTIFIER",KEYWORD:"KEYWORD",OPERATOR:"OPERATOR",LPAREN:"LPAREN",RPAREN:"RPAREN",LBRACKET:"LBRACKET",RBRACKET:"RBRACKET",LBRACE:"LBRACE",RBRACE:"RBRACE",COMMA:"COMMA",DOT:"DOT",COLON:"COLON",SEMICOLON:"SEMICOLON",INDENT:"INDENT",DEDENT:"DEDENT",NEWLINE:"NEWLINE",COMMENT:"COMMENT",EOF:"EOF"},cG=new Set(["if","else","for","while","switch","break","continue","var","varip","type","and","or","not","to","by","in","as","import","export","method","enum"]),cH=new Set(["type","method","enum"]),cY=new Set(["catch","class","do","ellipse","is","polygon","range","return","struct","text","throw","try"]),cZ=["==","!=","<=",">=",":=","+=","-=","*=","/=","%=","=>","//","and","or","not"];class cJ{constructor(e,t,i,r,n=0,s=null){this.type=e,this.value=t,this.line=i,this.column=r,this.indent=n,this.raw=s,cW(this,"wrapped",null),cW(this,"grouped",!1),cW(this,"startColumn")}}var cQ=Object.defineProperty,cX=(e,t,i)=>((e,t,i)=>t in e?cQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let c0=class e{constructor(e){cX(this,"source"),cX(this,"pos"),cX(this,"line"),cX(this,"column"),cX(this,"tokens"),cX(this,"indentStack"),cX(this,"atLineStart"),cX(this,"parenDepth"),cX(this,"bracketDepth"),cX(this,"braceDepth"),cX(this,"pendingWrap",null),this.source=e,this.pos=0,this.line=1,this.column=1,this.tokens=[],this.indentStack=[0],this.atLineStart=!0,this.parenDepth=0,this.bracketDepth=0,this.braceDepth=0}tokenize(){for(;this.pos<this.source.length;){let e=this.peek();if("\r"===e){this.advance();continue}if(e===`
311
+ `){this.handleNewline();continue}if(this.atLineStart&&e!==`
312
+ `){this.handleIndentation(),this.atLineStart=!1;continue}if(" "===e||" "===e){this.advance();continue}if(this.pos>=this.source.length)break;if("/"===e&&"/"===this.peek(1)){this.readComment();continue}if('"'===e||"'"===e){this.readString();continue}if("#"===e){this.readColorLiteral();continue}if(this.isDigit(e)){this.readNumber();continue}if(this.isIdentifierStart(e)){this.readIdentifier();continue}if(!this.readOperatorOrPunctuation())throw Error(`Unexpected character '${e}' at ${this.line}:${this.column}`)}for(;this.indentStack.length>1;)this.indentStack.pop(),this.addToken(cK.DEDENT,"",this.getCurrentIndent());return this.addToken(cK.EOF,""),this.resolveContextualKeywords(),this.tokens}resolveContextualKeywords(){let e=e=>e.type===cK.NEWLINE||e.type===cK.INDENT||e.type===cK.DEDENT||e.type===cK.COMMENT,t=e=>!!e&&(e.type===cK.IDENTIFIER||e.type===cK.KEYWORD);for(let i=0;i<this.tokens.length;i++){let r=this.tokens[i];if(r.type!==cK.KEYWORD||!cH.has(r.value))continue;let n=i-1;for(;n>=0&&this.tokens[n].type===cK.COMMENT;)n--;let s=n>=0?this.tokens[n]:null;!r.wrapped&&(null===s||e(s)||s.type===cK.KEYWORD&&"export"===s.value)&&t(this.tokens[i+1])||(r.type=cK.IDENTIFIER)}}handleNewline(){0===this.parenDepth&&0===this.bracketDepth&&0===this.braceDepth&&(this.addToken(cK.NEWLINE,`
313
+ `),this.atLineStart=!0),this.advance(),this.line++,this.column=1}handleIndentation(){let t=0;for(;this.pos<this.source.length;){let i=this.peek();if(" "===i)t+=1,this.advance();else if(" "===i)t+=e.TAB_WIDTH,this.advance();else break}if(this.peek()===`
314
+ `||"\r"===this.peek()||"\0"===this.peek()||"/"===this.peek()&&"/"===this.peek(1))return;if(t%e.TAB_WIDTH!=0||this.isContinuationFromPrevToken())return void this.joinWithPreviousLine(t);let i=t/e.TAB_WIDTH,r=this.indentStack[this.indentStack.length-1];if(i>r){if(i>r+1){let i=(r+1)*e.TAB_WIDTH;throw Error(`Indentation error at ${this.line}:${this.column} - line is indented by ${t} columns, but a local block must be indented by exactly one level (${i} columns: four spaces or one tab) deeper than the enclosing block`)}this.indentStack.push(i),this.addToken(cK.INDENT,"",i)}else if(i<r){for(;this.indentStack.length>1&&this.indentStack[this.indentStack.length-1]>i;)this.indentStack.pop(),this.addToken(cK.DEDENT,"",this.indentStack[this.indentStack.length-1]);if(this.indentStack[this.indentStack.length-1]!==i)throw Error(`Indentation error at ${this.line}:${this.column} - misaligned dedent`)}}joinWithPreviousLine(e){let t=null;for(;this.tokens.length>0;){let e=this.tokens[this.tokens.length-1];if(e.type!==cK.NEWLINE&&e.type!==cK.COMMENT)break;this.tokens.pop()}0!==this.tokens.length&&(t=this.tokens[this.tokens.length-1].line,this.pendingWrap={width:e,fromLine:t,column:this.column})}isContinuationFromPrevToken(){for(let e=this.tokens.length-1;e>=0;e--){let t=this.tokens[e];if(t.type!==cK.NEWLINE&&t.type!==cK.COMMENT)return t.type===cK.OPERATOR?"=>"!==t.value:t.type===cK.COMMA||t.type===cK.COLON||t.type===cK.KEYWORD&&("and"===t.value||"or"===t.value)}return!1}readComment(){this.column;let e="";for(this.advance(),this.advance();this.pos<this.source.length&&this.peek()!==`
315
+ `;)e+=this.advance();this.parenDepth>0||this.bracketDepth>0||this.braceDepth>0||this.addToken(cK.COMMENT,e.trim())}readString(){if(this.peek(1)===this.peek()&&this.peek(2)===this.peek())return void this.readMultilineString();let e=this.advance(),t=this.column-1,i="";for(;this.pos<this.source.length&&this.peek()!==e;)"\\"===this.peek()?i+=this.readEscape(e):i+=this.advance();if(this.peek()!==e)throw Error(`Unterminated string at ${this.line}:${t}`);this.advance(),this.addToken(cK.STRING,i),this.tokens[this.tokens.length-1].startColumn=t}readEscape(e){this.advance();let t=this.advance();switch(t){case"n":return`
316
+ `;case"t":return" ";case"r":return"\r";case"\\":return"\\";case e:return e;default:return t}}readMultilineString(){let e=this.peek(),t=this.line,i=this.column;this.advance(),this.advance(),this.advance();let r="";for(;this.pos<this.source.length;){let t=this.peek();if(t===e&&this.peek(1)===e&&this.peek(2)===e){this.advance(),this.advance(),this.advance(),this.addToken(cK.STRING,r);return}if("\r"===t){this.advance();continue}if(t===`
317
+ `){this.advance(),this.line++,this.column=1,r+=`
318
+ `;continue}if("\\"===t){r+=this.readEscape(e);continue}r+=this.advance()}throw Error(`Unterminated multiline string at ${t}:${i}`)}readColorLiteral(){let e=this.column,t="#";for(this.advance();this.pos<this.source.length&&t.length<9;){let e=this.peek();if(e>="0"&&e<="9"||e>="A"&&e<="F"||e>="a"&&e<="f")t+=this.advance();else break}if(7!==t.length&&9!==t.length)throw Error(`Invalid color literal '${t}' at ${this.line}:${e}`);this.addToken(cK.STRING,t)}readNumber(){this.column;let e="",t=!1;for("."===this.peek()&&this.isDigit(this.peek(1))&&(t=!0,e+=this.advance());this.pos<this.source.length;){let i=this.peek();if(this.isDigit(i))e+=this.advance();else if("."!==i||t)break;else{let i=this.peek(1);if(this.isDigit(i)||!this.isIdentifierStart(i)){if(t=!0,e+=this.advance(),!this.isDigit(this.peek()))break}else break}}if(this.pos<this.source.length){let t=this.peek();if("e"===t||"E"===t){let t=this.peek(1);if(this.isDigit(t))for(e+=this.advance();this.pos<this.source.length&&this.isDigit(this.peek());)e+=this.advance();else if("+"===t||"-"===t){let t=this.peek(2);if(this.isDigit(t))for(e+=this.advance(),e+=this.advance();this.pos<this.source.length&&this.isDigit(this.peek());)e+=this.advance()}}}this.addToken(cK.NUMBER,parseFloat(e),null,e)}readIdentifier(){this.column;let e="";for(;this.pos<this.source.length&&this.isIdentifierChar(this.peek());)e+=this.advance();cG.has(e)?this.addToken(cK.KEYWORD,e):"true"===e||"false"===e?this.addToken(cK.BOOLEAN,"true"===e):this.addToken(cK.IDENTIFIER,e)}readOperatorOrPunctuation(){let e=this.peek(),t=e+this.peek(1);if(cZ.includes(t))return this.advance(),this.advance(),this.addToken(cK.OPERATOR,t),!0;if("+-*/%<>=!?".includes(e))return this.advance(),this.addToken(cK.OPERATOR,e),!0;switch(e){case"(":return this.parenDepth++,this.advance(),this.addToken(cK.LPAREN,e),!0;case")":return this.parenDepth--,this.advance(),this.addToken(cK.RPAREN,e),!0;case"[":{let t=this.parenDepth>0||this.bracketDepth>0||this.braceDepth>0;return this.bracketDepth++,this.advance(),this.addToken(cK.LBRACKET,e),this.tokens[this.tokens.length-1].grouped=t,!0}case"]":return this.bracketDepth--,this.advance(),this.addToken(cK.RBRACKET,e),!0;case"{":return this.braceDepth++,this.advance(),this.addToken(cK.LBRACE,e),!0;case"}":return this.braceDepth--,this.advance(),this.addToken(cK.RBRACE,e),!0;case",":return this.advance(),this.addToken(cK.COMMA,e),!0;case".":return this.isDigit(this.peek(1))?this.readNumber():(this.advance(),this.addToken(cK.DOT,e)),!0;case":":return this.advance(),this.addToken(cK.COLON,e),!0;case";":return this.advance(),this.addToken(cK.SEMICOLON,e),!0}return!1}peek(e=0){let t=this.pos+e;return t<this.source.length?this.source[t]:"\0"}advance(){let e=this.source[this.pos++];return this.column++,e}skipWhitespaceInline(){if(!this.atLineStart)for(;this.pos<this.source.length&&(" "===this.peek()||" "===this.peek());)this.advance()}isDigit(e){return e>="0"&&e<="9"}isIdentifierStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentifierChar(e){return this.isIdentifierStart(e)||this.isDigit(e)}getCurrentIndent(){return this.indentStack[this.indentStack.length-1]}addToken(e,t,i=null,r=null){let n=new cJ(e,t,this.line,this.column,null!==i?i:this.getCurrentIndent(),r);this.pendingWrap&&(n.wrapped=this.pendingWrap,this.pendingWrap=null),this.tokens.push(n)}};cX(c0,"TAB_WIDTH",4);var c1=Object.defineProperty,c2=(e,t,i)=>((e,t,i)=>t in e?c1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class c3{constructor(e){this.type=e}}class c4 extends c3{constructor(e){super("Program"),this.body=e}}class c6 extends c3{constructor(e){super("ExpressionStatement"),this.expression=e}}var c5=(e=>(e.VAR="var",e.LET="let",e.CONST="const",e))(c5||{});class c9 extends c3{constructor(e,t="let"){super("VariableDeclaration"),this.declarations=e,this.kind=t}}class c8 extends c3{constructor(e,t,i=null){super("VariableDeclarator"),this.id=e,this.init=t,this.varType=i}}class c7 extends c3{constructor(e,t,i,r=null){super("FunctionDeclaration"),this.id=e,this.params=t,this.body=i,this.returnType=r}}class pe extends c3{constructor(e,t){super("TypeDefinition"),this.name=e,this.fields=t}}class pt extends c3{constructor(e,t,i,r,n){super("ImportDeclaration"),this.path=e,this.user=t,this.name=i,this.version=r,this.alias=n}}class pi extends c3{constructor(e,t,i=null){super("IfStatement"),this.test=e,this.consequent=t,this.alternate=i,c2(this,"_line")}}class pr extends c3{constructor(e,t,i,r){super("ForStatement"),this.init=e,this.test=t,this.update=i,this.body=r,c2(this,"isForIn")}}class pn extends c3{constructor(e,t){super("WhileStatement"),this.test=e,this.body=t}}class ps extends c3{constructor(e){super("BlockStatement"),this.body=e}}class pa extends c3{constructor(e){super("ReturnStatement"),this.argument=e}}class po extends c3{constructor(e){super("Identifier"),this.name=e,c2(this,"varType"),c2(this,"returnType"),c2(this,"isMethod")}}class pl extends c3{constructor(e,t=null){super("Literal"),this.value=e,this.raw=t}}class ph extends c3{constructor(e,t,i){super("BinaryExpression"),this.operator=e,this.left=t,this.right=i}}class pc extends c3{constructor(e,t,i=!0){super("UnaryExpression"),this.operator=e,this.argument=t,this.prefix=i}}class pp extends c3{constructor(e,t,i){super("AssignmentExpression"),this.operator=e,this.left=t,this.right=i}}class pu extends c3{constructor(e,t,i=!1){super("UpdateExpression"),this.operator=e,this.argument=t,this.prefix=i}}class pd extends c3{constructor(e,t){super("CallExpression"),this.callee=e,this.args=t,c2(this,"arguments"),this.callee=e,this.arguments=t}}class pm extends c3{constructor(e,t,i=!1){super("MemberExpression"),this.object=e,this.property=t,this.computed=i}}class pf extends c3{constructor(e,t,i){super("ConditionalExpression"),this.test=e,this.consequent=t,this.alternate=i,c2(this,"needsIIFE"),c2(this,"consequentStmts"),c2(this,"alternateStmts")}}class py extends c3{constructor(e){super("ArrayExpression"),this.elements=e}}class p_ extends c3{constructor(e){super("ObjectExpression"),this.properties=e}}class pg extends c3{constructor(e,t){super("Property"),this.key=e,this.value=t,c2(this,"kind"),c2(this,"method"),c2(this,"shorthand"),c2(this,"computed"),this.kind="init",this.method=!1,this.shorthand=!1,this.computed=!1}}class px extends c3{constructor(e){super("ArrayPattern"),this.elements=e}}class pb extends c3{constructor(e,t){super("AssignmentPattern"),this.left=e,this.right=t}}class pv extends c3{constructor(e,t){super("SwitchExpression"),this.discriminant=e,this.cases=t}}class pw extends c3{constructor(e,t,i){super("SwitchCase"),this.test=e,this.consequent=t,this.statements=i,this.statements=i}}let pS=new Set([cK.NEWLINE,cK.COMMENT,cK.EOF,cK.INDENT,cK.DEDENT]);function pE(e,t){let i,r=e[t],n=`${r.line}:${r.column-6}`,s=t+1,a="";for(;s<e.length&&!pS.has(e[s].type)&&(e[s].type!==cK.KEYWORD||"as"!==e[s].value);){let t=e[s++];a+=t.raw??String(t.value)}if(!a)throw Error(`Missing library path after "import" at ${n}`);try{i=function(e){let t=e.split("/"),i=Number(t[2]);if(3!==t.length||!t[0]||!t[1]||!/^\d+$/.test(t[2]??"")||!Number.isSafeInteger(i))throw Error(`Invalid import path "${e}". Expected <user>/<library>/<version>, e.g. "TradingView/ta/7"`);return{user:t[0],name:t[1],version:i}}(a)}catch(e){throw Error(`${e.message} at ${n}`)}let o=i.name;if(e[s]?.type===cK.KEYWORD&&"as"===e[s].value){let t=e[s+1];if(t?.type!==cK.IDENTIFIER)throw Error(`Expected an alias after "as" at ${n}`);o=t.value,s+=2}if(s<e.length&&!pS.has(e[s].type))throw Error(`Unexpected token '${e[s].value}' in import statement at ${n}`);return{spec:{path:a,...i,alias:o},next:s}}function pN(e){let t=new c0(e).tokenize(),i=[],r=0;for(let e=0;e<t.length;e++){let n=t[e];if(n.type===cK.INDENT?r++:n.type===cK.DEDENT&&r--,0!==r||n.type!==cK.KEYWORD||"import"!==n.value)continue;let s=t[e-1];if(s&&s.type!==cK.NEWLINE&&s.type!==cK.DEDENT&&s.type!==cK.COMMENT)continue;let a=t[e+1]?.type;a!==cK.IDENTIFIER&&a!==cK.NUMBER||i.push(pE(t,e).spec)}return i}var pT=Object.defineProperty,pk=(e,t,i)=>((e,t,i)=>t in e?pT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let pA=["const","simple","series"],pI=class e{constructor(e){pk(this,"tokens"),pk(this,"pos"),pk(this,"functionNames",new Set),pk(this,"typeNames",new Set),pk(this,"typeVariableNames",new Set),pk(this,"paramScopes",[]),pk(this,"loopValueCounter",0),pk(this,"onceCounter",0),pk(this,"functionTupleArity",new Map),pk(this,"functionParamNames",new Map),pk(this,"tupleLiteralStart",new WeakMap),pk(this,"forLoopCount",0),this.tokens=e,this.pos=0}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}isCurrentFunctionParam(e){for(let t of this.paramScopes)if(t.has(e))return!0;return!1}advance(){return this.tokens[this.pos++]}match(e,t=null){let i=this.peek();return i.type===e&&(null===t||i.value===t)}expect(e,t=null){let i=this.peek();if(i.type!==e)throw Error(`Expected ${e} but got ${i.type} at ${i.line}:${i.column}${this.layoutHint(i)}`);if(null!==t&&i.value!==t)throw Error(`Expected '${t}' but got '${i.value}' at ${i.line}:${i.column}${this.layoutHint(i)}`);return this.advance()}unexpected(e){if(e.type===cK.INDENT){let t=this.tokens[this.tokens.indexOf(e)+1]??e;return Error(`Unexpected indentation at ${e.line}:${e.column} - '${t.value}' is indented as a local block, but the previous statement does not open one. A line indented by a multiple of four columns starts a new statement; to wrap a long line, indent the continuation by a number of columns that is not a multiple of four`)}let t=e.type===cK.NEWLINE?"end of line":e.value,i=e.wrapped?e.wrapped.column:e.column;return Error(`Unexpected token ${e.type} '${t}' at ${e.line}:${i}${this.layoutHint(e)}`)}layoutHint(e){let t=e.wrapped;if(!t)return"";let i=t.width%4!=0?`is indented by ${t.width} columns, which is not a multiple of four, so it continues line ${t.fromLine} (Pine line wrapping)`:`continues line ${t.fromLine}, which ends with an operator`;return` - line ${e.line} ${i}. A statement inside a local block must be indented by four spaces or one tab per level`}rejectDanglingWrappedLine(){let e=this.peek();if(e.wrapped&&e.type!==cK.COMMA)throw this.unexpected(e)}startsNewLine(){let e=this.peek();if(e.wrapped||e.grouped)return!1;let t=this.pos-1;for(;t>=0&&this.tokens[t].type===cK.DEDENT;)t--;if(t<0)return!0;let i=this.tokens[t];return i.type===cK.NEWLINE||i.line!==e.line}reservedNameError(e){let t=e.column-String(e.value).length;return Error(`"${e.value}" cannot be used as a variable or function name. at ${e.line}:${t}`)}isReservedName(e){return e.type===cK.KEYWORD||e.type===cK.IDENTIFIER&&cY.has(e.value)}expectName(){let e=this.peek();if(this.isReservedName(e))throw this.reservedNameError(e);if(e.type!==cK.IDENTIFIER)throw Error(`Expected ${cK.IDENTIFIER} but got ${e.type} at ${e.line}:${e.column}`);return this.advance()}assertDeclarableName(e,t){if(e?.type==="Identifier"&&cY.has(e.name))throw this.reservedNameError(t)}assertParamDefault(e,t){if(e?.type==="CallExpression")throw Error(`The default value cannot be a function, variable or calculation. at ${this.startOf(t)}`);if(e?.type==="BinaryExpression"||e?.type==="LogicalExpression"||e?.type==="ConditionalExpression")throw Error(`The default value assigned to a parameter must be either a literal value (e.g., "5") or a built-in variable (e.g., "close"). at ${this.startOf(t)}`)}startOf(e){return`${e.line}:${e.column-String(e.value).length}`}dottedName(e){if(e?.type==="Identifier")return e.name;if(e?.type==="MemberExpression"&&!e.computed&&e.property?.type==="Identifier"){let t=this.dottedName(e.object);return null===t?null:`${t}.${e.property.name}`}return null}tupleArityOf(e){if(e?.type==="CallExpression"&&e.callee?.type==="Identifier")return this.functionTupleArity.get(e.callee.name)??void 0}assertNotTupleLiteral(e){if(e?.type==="ArrayExpression"){let t=this.tupleLiteralStart.get(e);throw Error(`Syntax error at input "["${t?` at ${this.startOf(t)}`:""}`)}}assertNotTupleAssignment(e,t,i){if(this.assertNotTupleLiteral(t),e?.type==="Identifier"&&void 0!==this.tupleArityOf(t))throw Error(`Invalid assignment. Cannot assign a tuple to a variable "${e.name}". at ${this.startOf(i)}`)}rejectReservedAssignmentTarget(){let e=this.peek(),t=this.peek(1);if(this.isReservedName(e)&&t.type===cK.OPERATOR&&"="===t.value)throw this.reservedNameError(e)}isNameSlot(t){return t.type===cK.IDENTIFIER||t.type===cK.KEYWORD&&!e.STATEMENT_KEYWORDS.has(t.value)}peekOperatorEx(e){let t=this.peek();return t.type===cK.OPERATOR&&e.includes(t.value)?t.value:null}isLayoutToken(){return this.match(cK.NEWLINE)||this.match(cK.COMMENT)}skipNewlines(e=!1){for(;this.isLayoutToken();)this.advance();e&&this.match(cK.INDENT)&&this.advance()}parse(){let e=[];for(this.collectTopLevelFunctionNames();!this.match(cK.EOF);){if(this.skipNewlines(),this.match(cK.DEDENT)){this.advance();continue}if(this.match(cK.EOF))break;let t=this.parseTopLevelStatement();t&&e.push(t),this.skipNewlines()}return new c4(e)}parseTopLevelStatement(){if(this.isImportStatement()){let e=this.peek().line,{spec:t,next:i}=pE(this.tokens,this.pos);this.pos=i;let r=new pt(t.path,t.user,t.name,t.version,t.alias);return r._line=e,r}if(this.isExportStatement()){let e=this.advance(),t=this.parseStatement(!1);if(t?.type!=="FunctionDeclaration"&&t?.type!=="TypeDefinition"&&!t?._enum)throw Error(`Only functions, methods, types and enums can be exported at ${this.startOf(e)}`);return t.exported=!0,t}return this.parseStatement()}isImportStatement(){let e=this.peek(1).type;return this.match(cK.KEYWORD,"import")&&(e===cK.IDENTIFIER||e===cK.NUMBER)}isExportStatement(){let e=this.peek(1).type;return this.match(cK.KEYWORD,"export")&&(e===cK.IDENTIFIER||e===cK.KEYWORD)}collectTopLevelFunctionNames(){let e=0;for(let t=0;t<this.tokens.length;t++){let i=this.tokens[t];i.type===cK.INDENT?e++:i.type===cK.DEDENT&&e--;let r=0===t||this.tokens[t-1].type===cK.NEWLINE||this.tokens[t-1].type===cK.DEDENT,n=this.tokens[t-1],s=n?.type===cK.KEYWORD&&"export"===n.value;if(0===e&&i.type===cK.KEYWORD&&"type"===i.value&&t+1<this.tokens.length&&(r||s)&&this.typeNames.add(this.tokens[t+1].value),0!==e||!(r||s)||i.type!==cK.IDENTIFIER||(this.pos=t,!this.isFunctionDeclaration()))continue;let a=this.peek(1).type!==cK.LPAREN;this.functionNames.add(this.peek(+!!a).value)}this.pos=0;let t=0;for(let e=0;e<this.tokens.length-1;e++){let i=this.tokens[e];i.type===cK.LPAREN||i.type===cK.LBRACKET?t++:(i.type===cK.RPAREN||i.type===cK.RBRACKET)&&t--;let r=this.tokens[e+1];0===t&&i.type===cK.IDENTIFIER&&this.typeNames.has(i.value)&&r.type===cK.OPERATOR&&"="===r.value&&this.typeVariableNames.add(i.value)}}variableName(e){return this.functionNames.has(e)||this.typeVariableNames.has(e)?e+"_var":e}isTypeMemberAccess(){return this.peek().type===cK.DOT&&this.peek(1).type===cK.IDENTIFIER&&("new"===this.peek(1).value||"copy"===this.peek(1).value)&&this.peek(2).type===cK.LPAREN}isOnceStatement(){if(this.peek().type!==cK.IDENTIFIER||"once"!==this.peek().value)return!1;let e=this.peek(1);if(e.type===cK.COMMA||e.type===cK.DOT||e.type===cK.OPERATOR&&["=",":=","+=","-=","*=","/=","%="].includes(e.value))return!1;let t=1,i=0;for(;;t++){let e=this.peek(t);if(e.type===cK.EOF)return!1;if(e.type===cK.LPAREN||e.type===cK.LBRACKET)i++;else if(e.type===cK.RPAREN||e.type===cK.RBRACKET)i--;else{if(i<=0&&(e.type===cK.NEWLINE||e.type===cK.INDENT))break;if(e.type===cK.OPERATOR&&"=>"===e.value)return!1}}for(;this.peek(t).type===cK.NEWLINE||this.peek(t).type===cK.COMMENT;)t++;return this.peek(t).type===cK.INDENT}parseOnceStatement(){this.advance();let e=this.match(cK.NEWLINE)||this.match(cK.INDENT)?null:this.parseExpression();this.skipNewlines();let t=this.parseBlock(),i=`__once_${this.onceCounter++}`,r=new po(i);r.varType="bool";let n=new c9([new c8(r,new pl(!1),"bool")],c5.VAR);t.body.unshift(new c6(new pp("=",new po(i),new pl(!0))));let s=e?new ps([new pi(e,t)]):t,a=new ps([n,new pi(new pc("!",new po(i)),s)]);return a._sequence=!0,a}parseStatement(e=!0){let t;this.skipNewlines();let i=this.peek().line;if(this.match(cK.COMMENT))return this.advance(),null;if(this.match(cK.KEYWORD,"enum"))t=this.parseEnumDefinition();else if(this.match(cK.KEYWORD,"type"))t=this.parseTypeDefinition();else if(this.match(cK.KEYWORD,"var")||this.match(cK.KEYWORD,"varip"))t=this.parseVarDeclaration();else if(this.match(cK.KEYWORD,"method"))t=this.parseMethodDeclaration();else if(this.isOnceStatement())t=this.parseOnceStatement();else if(this.isFunctionDeclaration())t=this.parseFunctionDeclaration();else if(this.match(cK.KEYWORD,"if"))t=this.parseIfStatement();else if(this.match(cK.KEYWORD,"for"))t=this.parseForStatement();else if(this.match(cK.KEYWORD,"while"))t=this.parseWhileStatement();else if(this.isImportStatement()||this.isExportStatement()){let e=this.peek();throw Error(`"${e.value}" is only allowed in the global scope at ${this.startOf(e)}`)}else this.match(cK.KEYWORD,"break")||this.match(cK.KEYWORD,"continue")?t=new c6(new po(this.advance().value)):this.isTupleDestructuring()?t=this.parseTupleDestructuring():this.peek().type===cK.IDENTIFIER&&this.isTypedVarDeclaration()&&(t=this.parseTypedVarDeclaration());if(!t){this.rejectReservedAssignmentTarget();let e=this.peek(),i=this.parseExpression();if(this.match(cK.OPERATOR)){let r=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(r)){this.advance(),this.skipNewlines(!0);let n=this.parseExpression();"="===r&&"Identifier"===i.type?(this.assertDeclarableName(i,e),this.assertNotTupleAssignment(i,n,e),t=new c9([new c8(i,n)],c5.LET)):t=new c6(new pp(":="===r?"=":r,i,n))}else t=new c6(i)}else t=new c6(i)}if(t&&(t._line=i,e&&this.match(cK.COMMA))){let e=[t];for(;this.match(cK.COMMA);){this.advance(),this.skipNewlines(!0);let t=this.parseStatement(!1);t&&e.push(t)}this.rejectDanglingWrappedLine();let i=new ps(e);return i._sequence=!0,i}return this.rejectDanglingWrappedLine(),t}isFunctionDeclaration(){let e=this.pos;try{let e=0;if(this.peek(e).type===cK.IDENTIFIER&&this.isNameSlot(this.peek(e+1))&&e++,!this.isNameSlot(this.peek(e))||(e++,this.peek(e).type!==cK.LPAREN))return!1;e++;let t=1;for(;t>0&&this.peek(e).type!==cK.EOF;)this.peek(e).type===cK.LPAREN&&t++,this.peek(e).type===cK.RPAREN&&t--,e++;return this.peek(e).type===cK.OPERATOR&&"=>"===this.peek(e).value}finally{this.pos=e}}parseTypeExpression(){let e=this.expect(cK.IDENTIFIER).value;for(;this.match(cK.DOT)&&this.peek(1).type===cK.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(cK.OPERATOR,"<")){this.advance();let t=[];for(t.push(this.parseTypeExpression());this.match(cK.COMMA);)this.advance(),this.skipNewlines(),t.push(this.parseTypeExpression());return this.expect(cK.OPERATOR,">"),e+"<"+t.join(", ")+">"}return this.match(cK.LBRACKET)&&this.peek(1).type===cK.RBRACKET?(this.advance(),this.advance(),"array<"+e+">"):e}parseEnumDefinition(){this.expect(cK.KEYWORD,"enum");let e=this.expectName().value;this.skipNewlines(),this.expect(cK.INDENT);let t=[];for(;!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){if(this.match(cK.COMMENT)){this.advance();continue}let e=this.expectName().value,i=null;this.match(cK.OPERATOR,"=")&&(this.advance(),i=this.expect(cK.STRING).value),t.push({name:e,title:i}),this.skipNewlines()}this.match(cK.DEDENT)&&this.advance();let i=new p_(t.map(e=>new pg(new po(e.name),new pl(null!==e.title?e.title:e.name)))),r=new c9([new c8(new po(e),i)],c5.CONST);return r._enum=!0,r}parseTypeDefinition(){this.expect(cK.KEYWORD,"type");let e=this.expectName().value;this.match(cK.OPERATOR,"=>")&&this.advance(),this.skipNewlines(),this.expect(cK.INDENT);let t=[];for(;!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){if(this.match(cK.KEYWORD,"varip")&&this.advance(),this.isNameSlot(this.peek())&&this.peek(1).type===cK.OPERATOR&&"="===this.peek(1).value){let e=this.expectName().value;this.advance(),this.skipNewlines();let i=this.parseExpression();t.push({type:this.inferFieldType(i),name:e,defaultValue:i}),this.skipNewlines();continue}let e=this.parseTypeExpression(),i=this.expectName().value,r=null;this.match(cK.OPERATOR,"=")&&(this.advance(),this.skipNewlines(),r=this.parseExpression()),t.push({type:e,name:i,defaultValue:r}),this.skipNewlines()}return this.match(cK.DEDENT)&&this.advance(),new pe(e,t)}inferFieldType(e){if(e?.type==="UnaryExpression"&&("-"===e.operator||"+"===e.operator))return this.inferFieldType(e.argument);if(e?.type==="Literal"){if("boolean"==typeof e.value)return"bool";if("string"==typeof e.value)return"string";if("number"==typeof e.value)return"string"==typeof e.raw&&/^\d+$/.test(e.raw)?"int":"float"}return e?.type==="MemberExpression"&&e.object?.type==="Identifier"&&"color"===e.object.name?"color":"float"}parseVarDeclaration(){let e=this.advance(),t=e.value,i=null,r=null;if(this.peek().type===cK.IDENTIFIER&&pA.includes(this.peek().value)&&this.peek(1).type===cK.IDENTIFIER&&this.advance(),this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.LBRACKET&&this.peek(2).type===cK.RBRACKET)i=this.advance().value,this.advance(),i+="[]",this.advance(),r=this.expectName().value;else if(this.peek().type===cK.IDENTIFIER&&(this.peek(1).type===cK.DOT||this.isNameSlot(this.peek(1))||this.peek(1).type===cK.OPERATOR&&"<"===this.peek(1).value)){for(i=this.advance().value;this.match(cK.DOT)&&this.peek(1).type===cK.IDENTIFIER;)this.advance(),i+="."+this.advance().value;if(this.match(cK.LBRACKET)&&this.peek(1).type===cK.RBRACKET)this.advance(),this.advance(),i+="[]",r=this.expectName().value;else if(this.match(cK.OPERATOR,"<")){for(this.advance(),i+="<";!this.match(cK.OPERATOR,">");)if(this.match(cK.IDENTIFIER))for(i+=this.advance().value;this.match(cK.DOT)&&this.peek(1).type===cK.IDENTIFIER;)i+=".",this.advance(),i+=this.advance().value;else if(this.match(cK.COMMA))i+=this.advance().value,this.skipNewlines();else break;this.match(cK.OPERATOR,">")&&(i+=">",this.advance()),r=this.expectName().value}else r=this.expectName().value}else if(this.isNameSlot(this.peek()))r=this.expectName().value;else throw this.match(cK.OPERATOR,"=")||this.match(cK.LPAREN)?this.reservedNameError(e):Error(`Expected identifier after ${t} at ${this.peek().line}:${this.peek().column}`);r=this.variableName(r),this.expect(cK.OPERATOR,"="),this.skipNewlines(!0);let n=this.parseExpression(),s=new po(r);i&&(s.varType=i);let a=[new c8(s,n,i)];for(;this.match(cK.COMMA)&&this.peek(1).type===cK.KEYWORD&&("var"===this.peek(1).value||"varip"===this.peek(1).value);){this.advance();let e=this.parseVarDeclaration();a.push(...e.declarations)}return new c9(a,t)}isTypedVarDeclaration(){let e=0;if(this.peek(e).type!==cK.IDENTIFIER)return!1;for(pA.includes(this.peek(e).value)&&this.peek(e+1).type===cK.IDENTIFIER&&e++,e++;this.peek(e).type===cK.DOT&&this.peek(e+1).type===cK.IDENTIFIER;)e+=2;if(this.peek(e).type===cK.LBRACKET&&this.peek(e+1).type===cK.RBRACKET)return e+=2,!!this.isNameSlot(this.peek(e))&&(e++,this.peek(e).type===cK.OPERATOR&&"="===this.peek(e).value);if(this.peek(e).type===cK.OPERATOR&&"<"===this.peek(e).value){e++;let t=1;for(;t>0&&this.peek(e).type!==cK.EOF;)this.peek(e).type===cK.OPERATOR&&"<"===this.peek(e).value?t++:this.peek(e).type===cK.OPERATOR&&">"===this.peek(e).value&&t--,e++;return!!this.isNameSlot(this.peek(e))&&(e++,this.peek(e).type===cK.OPERATOR&&"="===this.peek(e).value)}if(!this.isNameSlot(this.peek(e)))return!1;for(e++;this.isNameSlot(this.peek(e));)e++;return this.peek(e).type===cK.OPERATOR&&"="===this.peek(e).value}parseTypedVarDeclaration(){let e="";pA.includes(this.peek().value)&&this.peek(1).type===cK.IDENTIFIER&&(e=this.advance().value+" ");let t=this.advance().value;for(;this.match(cK.DOT)&&this.peek(1).type===cK.IDENTIFIER;)this.advance(),t+="."+this.advance().value;if(this.match(cK.LBRACKET)&&this.peek(1).type===cK.RBRACKET)this.advance(),this.advance(),t+="[]";else if(this.match(cK.OPERATOR,"<")){for(this.advance(),t+="<";!this.match(cK.OPERATOR,">");)if(this.match(cK.IDENTIFIER))for(t+=this.advance().value;this.match(cK.DOT)&&this.peek(1).type===cK.IDENTIFIER;)t+=".",this.advance(),t+=this.advance().value;else if(this.match(cK.COMMA))t+=this.advance().value,this.skipNewlines();else break;this.match(cK.OPERATOR,">")&&(t+=">",this.advance())}else for(;this.peek().type===cK.IDENTIFIER&&this.isNameSlot(this.peek(1));)t+=" "+this.advance().value;t=e+t;let i=this.variableName(this.expectName().value);this.expect(cK.OPERATOR,"="),this.skipNewlines(!0);let r=this.parseExpression(),n=new po(i);n.varType=t;let s=[new c8(n,r,t)];for(;this.match(cK.COMMA)&&this.peek(1).type===cK.IDENTIFIER&&this.peek(2).type===cK.OPERATOR&&"="===this.peek(2).value;){this.advance(),this.skipNewlines(!0);let e=this.variableName(this.expectName().value);this.expect(cK.OPERATOR,"="),this.skipNewlines(!0);let i=this.parseExpression(),r=new po(e);r.varType=t,s.push(new c8(r,i,t))}return new c9(s,c5.LET)}parseFunctionDeclaration(){let e,t=null;this.peek().type===cK.IDENTIFIER&&this.isNameSlot(this.peek(1))&&(t=this.advance().value);let i=this.expectName().value;this.functionNames.add(i),this.expect(cK.LPAREN);let r=[];for(;!this.match(cK.RPAREN)&&(this.skipNewlines(),!this.match(cK.RPAREN));){let e=this.peek(),t=null;for(;this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.IDENTIFIER&&this.peek(2).type!==cK.LPAREN;)t&&(t+=" "),t=(t||"")+this.advance().value;if(this.isDottedParamType()){let e=this.parseTypeExpression();t=t?t+" "+e:e}if(this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.OPERATOR&&"<"===this.peek(1).value){let e=this.parseTypeExpression();t=t?t+" "+e:e}if(this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.LBRACKET&&this.peek(2).type===cK.RBRACKET){let e=this.parseTypeExpression();t=t?t+" "+e:e}let i=new po(this.expectName().value);if(t&&(i.varType=t),this.match(cK.OPERATOR,"=")){this.advance(),this.skipNewlines();let t=this.parseExpression();this.assertParamDefault(t,e),r.push(new pb(i,t))}else r.push(i);this.match(cK.COMMA)&&this.advance()}this.expect(cK.RPAREN),this.skipNewlines(),this.expect(cK.OPERATOR,"=>"),this.skipNewlines();let n=new Set;for(let e of r){let t="AssignmentPattern"===e.type?e.left:e;t&&t.name&&n.add(t.name)}this.paramScopes.push(n);try{e=this.parseFunctionBody()}finally{this.paramScopes.pop()}let s=new po(i);t&&(s.returnType=t);let a=e.body[e.body.length-1],o=a?.type==="ReturnStatement"?a.argument:null,l=o?.type==="ArrayExpression"?o.elements.length:this.tupleArityOf(o)??null;return this.functionTupleArity.set(i,this.functionTupleArity.has(i)&&this.functionTupleArity.get(i)!==l?null:l),this.functionParamNames.set(i,this.functionParamNames.has(i)?null:[...n]),new c7(s,r,e,t)}isDottedParamType(){if(this.peek().type!==cK.IDENTIFIER||this.peek(1).type!==cK.DOT||this.peek(2).type!==cK.IDENTIFIER)return!1;let e=3;for(;this.peek(e).type===cK.DOT&&this.peek(e+1).type===cK.IDENTIFIER;)e+=2;let t=this.peek(e);return t.type===cK.LBRACKET?this.peek(e+1).type===cK.RBRACKET:t.type===cK.OPERATOR&&"<"===t.value||this.isNameSlot(t)}parseMethodDeclaration(){let e;this.expect(cK.KEYWORD,"method");let t=null;this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.IDENTIFIER&&this.peek(2).type===cK.LPAREN&&(t=this.advance().value);let i=this.expectName().value;this.expect(cK.LPAREN);let r=[];for(;!this.match(cK.RPAREN)&&(this.skipNewlines(),!this.match(cK.RPAREN));){let e=this.peek(),t=null;for(;this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.IDENTIFIER&&this.peek(2).type!==cK.LPAREN;)t&&(t+=" "),t=(t||"")+this.advance().value;if(this.isDottedParamType()){let e=this.parseTypeExpression();t=t?t+" "+e:e}if(this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.OPERATOR&&"<"===this.peek(1).value){let e=this.parseTypeExpression();t=t?t+" "+e:e}if(this.peek().type===cK.IDENTIFIER&&this.peek(1).type===cK.LBRACKET&&this.peek(2).type===cK.RBRACKET){let e=this.parseTypeExpression();t=t?t+" "+e:e}let i=new po(this.expectName().value);if(t&&(i.varType=t),this.match(cK.OPERATOR,"=")){this.advance(),this.skipNewlines();let t=this.parseExpression();this.assertParamDefault(t,e),r.push(new pb(i,t))}else r.push(i);this.match(cK.COMMA)&&this.advance()}this.expect(cK.RPAREN),this.skipNewlines(),this.expect(cK.OPERATOR,"=>"),this.skipNewlines();let n=new Set;for(let e of r){let t="AssignmentPattern"===e.type?e.left:e;t&&t.name&&n.add(t.name)}this.paramScopes.push(n);try{e=this.parseFunctionBody()}finally{this.paramScopes.pop()}let s=new po(i);return t&&(s.returnType=t),s.isMethod=!0,new c7(s,r,e,t)}parseFunctionBody(){let e=[];if(!this.match(cK.INDENT)){let e=this.parseStatementOrSequence(),t=Array.isArray(e)?e:e?[e]:[];return t.length>0&&this._addImplicitReturn(t),new ps(t)}for(this.advance();!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){let t=this.parseStatementOrSequence();Array.isArray(t)?e.push(...t):t&&e.push(t)}return this.match(cK.DEDENT)&&this.advance(),e.length>0&&this._addImplicitReturn(e),new ps(e)}_addImplicitReturn(e){this._emitLastValue(e,e=>new pa(e))}_captureLoopValue(e){let t=e[e.length-1];if(t.body?.type!=="BlockStatement"||0===t.body.body.length)return null;let i=`__loopValue_${this.loopValueCounter++}`,r=()=>new po("na"),n=e=>new c6(new pp("=",new po(i),e));return this._emitLastValue(t.body.body,n)?(t.body.body.unshift(n(r())),e.splice(e.length-1,0,new c9([new c8(new po(i),r())],c5.LET)),i):null}_valueOfTrailingLoop(e){let t=e[e.length-1];(t?.type==="ForStatement"||t?.type==="WhileStatement")&&this._emitLastValue(e,e=>new c6(e))}_emitLastValue(e,t){let i=e[e.length-1];if("ForStatement"===i.type||"WhileStatement"===i.type){let i=this._captureLoopValue(e);return!!i&&(e.push(t(new po(i))),!0)}if("ExpressionStatement"===i.type){let r=i.expression;return(r?.type!=="Identifier"||"break"!==r.name&&"continue"!==r.name)&&(r?.type==="AssignmentExpression"&&r.left?.type==="Identifier"?e.push(t(new po(r.left.name))):e[e.length-1]=t(r),!0)}if("VariableDeclaration"===i.type){let r=i.declarations[i.declarations.length-1];return r?.id?.type==="Identifier"&&(e.push(t(new po(r.id.name))),!0)}if("IfStatement"===i.type){let e=!1;for(let r=i;r;r=r.alternate?.type==="IfStatement"?r.alternate:null)for(let i of[r.consequent,r.alternate?.type==="BlockStatement"?r.alternate:null])i?.body?.length>0&&(e=this._emitLastValue(i.body,t)||e);return e}return!1}continueSequence(e){if(!this.match(cK.COMMA))return e;let t=[e];for(;this.match(cK.COMMA);){this.advance(),this.skipNewlines(!0);let e=this.parseStatementOrSequence();Array.isArray(e)?t.push(...e):e&&t.push(e)}return t}parseStatementOrSequence(){this.pos;let e=this.peek().line;if(this.match(cK.KEYWORD,"if")){let t=this.parseIfStatement();return t&&(t._line=e),t}if(this.match(cK.KEYWORD,"for"))return this.parseForStatement();if(this.match(cK.KEYWORD,"while"))return this.parseWhileStatement();if(this.isOnceStatement())return this.parseOnceStatement();if(this.match(cK.KEYWORD,"break")||this.match(cK.KEYWORD,"continue"))return new c6(new po(this.advance().value));if(this.match(cK.KEYWORD,"var")||this.match(cK.KEYWORD,"varip"))return this.continueSequence(this.parseVarDeclaration());if(this.isTupleDestructuring())return this.continueSequence(this.parseTupleDestructuring());if(this.peek().type===cK.IDENTIFIER&&this.isTypedVarDeclaration())return this.continueSequence(this.parseTypedVarDeclaration());let t=[];for(;;){if(t.length>0&&(this.match(cK.KEYWORD,"var")||this.match(cK.KEYWORD,"varip")||this.isTupleDestructuring()||this.peek().type===cK.IDENTIFIER&&this.isTypedVarDeclaration())){let e=this.parseStatementOrSequence();Array.isArray(e)?t.push(...e):e&&t.push(e);break}this.rejectReservedAssignmentTarget();let e=this.peek(),i=this.parseExpression();if(this.match(cK.OPERATOR)){let r=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(r)){this.advance(),this.skipNewlines(!0);let n=this.parseExpression();if("="===r&&"Identifier"===i.type?(this.assertDeclarableName(i,e),this.assertNotTupleAssignment(i,n,e),t.push(new c9([new c8(i,n)],c5.LET))):t.push(new c6(new pp(":="===r?"=":r,i,n))),this.match(cK.COMMA)){this.advance(),this.skipNewlines();continue}break}if(!(t.length>0))return new c6(i);t.push(new c6(i));break}if(this.match(cK.COMMA)){t.push(new c6(i)),this.advance(),this.skipNewlines();continue}if(!(t.length>0))return new c6(i);t.push(new c6(i));break}return t.length>1?t:1===t.length?t[0]:null}parseIfStatement(){this.expect(cK.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines();let t=this.parseBlock(),i=null;return this.skipNewlines(),this.match(cK.KEYWORD,"else")&&(this.advance(),this.skipNewlines(),i=this.match(cK.KEYWORD,"if")?this.parseIfStatement():this.parseBlock()),new pi(e,t,i)}parseForStatement(){this.expect(cK.KEYWORD,"for");let e=null,t=!1;if(this.match(cK.LBRACKET)){this.advance();let i=[];for(;!this.match(cK.RBRACKET);)this.skipNewlines(),i.push(new po(this.expect(cK.IDENTIFIER).value)),this.match(cK.COMMA)&&this.advance();this.expect(cK.RBRACKET),e=new px(i),t=!0}else e=new po(this.expectName().value);if(this.match(cK.KEYWORD,"in")){this.advance();let t=this.parseExpression();this.skipNewlines();let i=this.parseBlock(),r=new pr(new c9([new c8(e,t)],c5.CONST),null,null,i);return r.isForIn=!0,r}{if(t)throw Error(`Range-based for loops don't support destructuring at ${this.peek().line}:${this.peek().column}`);this.expect(cK.OPERATOR,"=");let i=this.parseExpression();this.expect(cK.KEYWORD,"to");let r=this.parseExpression(),n=null;this.match(cK.KEYWORD,"by")&&(this.advance(),n=this.parseExpression()),this.skipNewlines();let s=this.parseBlock(),a=new po(`__for_up${this.forLoopCount++}`);return new pr(new c9([new c8(e,i),new c8(a,new ph("<=",e,r))],c5.LET),new pf(a,new ph("<=",e,r),new ph(">=",e,r)),n?new pf(a,new pp("+=",e,n),new pp("-=",e,n)):new pf(a,new pu("++",e),new pu("--",e)),s)}}parseWhileStatement(){this.expect(cK.KEYWORD,"while");let e=this.parseExpression();return this.skipNewlines(),new pn(e,this.parseBlock())}parseBlock(){if(!this.match(cK.INDENT)){this.rejectDanglingWrappedLine();let e=this.parseStatement();return new ps(e?[e]:[])}let e=this.peek().indent;this.advance();let t=[];for(;!this.match(cK.EOF);){if(this.skipNewlines(),this.match(cK.DEDENT)){if(this.peek().indent<e)break;this.advance();continue}if(this.match(cK.EOF))break;let i=this.parseStatement();i&&t.push(i)}return this.match(cK.DEDENT)&&this.peek().indent<e&&this.advance(),new ps(t)}isTupleDestructuring(){if(!this.match(cK.LBRACKET))return!1;let e=1;for(;;){for(;this.peek(e).type===cK.NEWLINE;)e++;if(this.peek(e).type!==cK.IDENTIFIER)return!1;for(e++,this.peek(e).type===cK.IDENTIFIER&&e++;this.peek(e).type===cK.NEWLINE;)e++;if(this.peek(e).type===cK.RBRACKET){e++;break}if(this.peek(e).type!==cK.COMMA)return!1;e++}for(;this.peek(e).type===cK.NEWLINE;)e++;return this.peek(e).type===cK.OPERATOR&&("="===this.peek(e).value||":="===this.peek(e).value)}parseTupleDestructuring(){let e=this.expect(cK.LBRACKET),t=[],i=new Set;for(;!this.match(cK.RBRACKET);){this.skipNewlines();let r=this.expect(cK.IDENTIFIER);if(this.match(cK.IDENTIFIER))throw Error(`Mismatched input "${this.peek().value}" expecting set "]" at ${this.startOf(this.peek())}`);let n=r.value;if("_"!==n){if(i.has(n))throw Error(`"${n}" is already defined at ${this.startOf(e)}`);i.add(n)}n=this.variableName(n),t.push(new po(n)),this.match(cK.COMMA)&&this.advance()}if(this.expect(cK.RBRACKET),this.skipNewlines(),this.match(cK.OPERATOR,":="))throw Error(`Mismatched input ":=" expecting set "=" at ${this.startOf(this.peek())}`);this.expect(cK.OPERATOR,"="),this.skipNewlines(!0);let r=this.parseExpression();this.assertNotTupleLiteral(r);let n=this.tupleArityOf(r);if(void 0!==n&&n!==t.length)throw Error(`Syntax error: The quantities of tuple elements on each side of the assignment operator do not match. The right side has ${n} but the left side has ${t.length}. at ${this.startOf(e)}`);return new c9([new c8(new px(t),r)],c5.CONST)}parseExpression(){return this.parseTernary()}parseTernary(){let e=this.parseLogicalOr();if(this.match(cK.OPERATOR,"?")){let t=this.advance();this.skipNewlines(!0);let i=this.parseExpression();this.expect(cK.COLON),this.skipNewlines(!0);let r=this.parseExpression(),n=[i,r].find(e=>"ArrayExpression"===e.type);if(n)throw Error(`Ternary operations cannot return tuples. Convert the expression into an \`if\` or \`switch\` conditional structure to return a tuple. at ${this.startOf(this.tupleLiteralStart.get(n)??t)}`);return new pf(e,i,r)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match(cK.KEYWORD,"or")||this.peekOperatorEx(["||"]);)this.advance(),this.skipNewlines(!0),e=new ph("||",e,this.parseLogicalAnd());return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match(cK.KEYWORD,"and")||this.peekOperatorEx(["&&"]);)this.advance(),this.skipNewlines(!0),e=new ph("&&",e,this.parseEquality());return e}parseEquality(){let e=this.parseComparison();for(;this.peekOperatorEx(["==","!="]);){let t=this.advance().value;this.skipNewlines(!0),e=new ph(t,e,this.parseComparison())}return e}parseComparison(){let e=this.parseAdditive();for(;this.peekOperatorEx(["<",">","<=",">="]);){let t=this.advance().value;this.skipNewlines(!0),e=new ph(t,e,this.parseAdditive())}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.peekOperatorEx(["+","-"]);){let t=this.advance().value;this.skipNewlines(!0),e=new ph(t,e,this.parseMultiplicative())}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.peekOperatorEx(["*","/","%"]);){let t=this.advance().value;this.skipNewlines(!0),e=new ph(t,e,this.parseUnary())}return e}parseUnary(){if(this.match(cK.OPERATOR)){let e=this.peek().value;if(["+","-","!"].includes(e)){let t=this.advance();this.skipNewlines();let i=new pc(e,this.parseUnary());return i._pos=this.startOf(t),i}}return this.match(cK.KEYWORD,"not")?(this.advance(),this.skipNewlines(),new pc("!",this.parseUnary())):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match(cK.OPERATOR,"<")){let t=this.pos;this.advance();let i=1,r=!0,n="",s="",a=new Set(["float","int","string","bool","color","line","label","box","linefill","table"]);for(;i>0&&!this.match(cK.EOF);)if(this.match(cK.OPERATOR,"<"))i++,this.advance();else if(this.match(cK.OPERATOR,">"))i--,this.advance();else if(this.match(cK.IDENTIFIER)||this.match(cK.COMMA)||this.match(cK.DOT))1===i&&this.match(cK.IDENTIFIER)&&""===n&&(n=this.peek().value),1===i&&(s+=this.peek().value),this.advance();else{r=!1,this.pos=t;break}if(r&&"MemberExpression"===e.type&&"new"===e.property.name&&("array"===e.object.name||"matrix"===e.object.name)&&a.has(n)&&(e.property=new po("new_"+n)),r&&this.match(cK.LPAREN)){let t="MemberExpression"===e.type&&"new"===e.property.name&&"map"===e.object.name;e=this.parseCallExpression(e),t&&"string"===s.split(",")[1]&&0===e.arguments.length&&e.arguments.push(new pl("string"));continue}if(r)continue;break}else if(this.match(cK.LPAREN)){if(this.startsNewLine())break;e=this.parseCallExpression(e)}else if(this.match(cK.DOT)){this.advance(),this.skipNewlines();let t=this.peek();if(t.type!==cK.IDENTIFIER&&t.type!==cK.KEYWORD)throw Error(`Expected property name but got ${t.type} at ${t.line}:${t.column}`);this.advance(),e=new pm(e,new po(t.value),!1)}else if(this.match(cK.LBRACKET)){if(this.startsNewLine())break;this.advance(),this.skipNewlines();let t=this.parseExpression();this.expect(cK.RBRACKET),e=new pm(e,t,!0)}else break;return e}parseCallExpression(e){let t=this.tokens[this.pos-1];this.expect(cK.LPAREN);let i=[],r=[],n=this.dottedName(e),s=null!==n&&("input"===n||/^(request|input)\./.test(n)),a=(e,i,r)=>{if(!("ArrayExpression"!==e.type||s))throw void 0!==r?Error(`The "${r}" parameter of the "${n}()" function cannot accept a tuple as an argument. Pass a single argument to this parameter. at ${this.startOf(t)}`):Error(`Cannot call "${n??"function"}" with a tuple argument. Only the expression parameter of request.*() functions and the options parameter of input.*() functions accept tuples. at ${this.startOf(i)}`)},o=null!==n?this.functionParamNames.get(n):void 0;for(;!this.match(cK.RPAREN)&&(this.skipNewlines(),!this.match(cK.RPAREN));){let e=this.peek();if((this.peek().type===cK.IDENTIFIER||this.peek().type===cK.KEYWORD)&&this.peek(1).type===cK.OPERATOR&&"="===this.peek(1).value){let e=this.advance(),t=e.value;this.advance(),this.skipNewlines();let i=this.peek(),n=this.parseExpression();a(n,i,o?t:void 0);let s=new po(t);s._pos=this.startOf(e),r.push(new pg(s,n))}else{let t=this.parseExpression();a(t,e,o?.[i.length]),i.push(t)}this.match(cK.COMMA)&&this.advance(),this.skipNewlines()}return this.expect(cK.RPAREN),r.length>0&&i.push(new p_(r)),new pd(e,i)}parsePrimary(){let e=this.peek();if(this.match(cK.NUMBER)){let e=this.advance(),t=new pl(e.value,e.raw);return"string"==typeof e.raw&&(t._pos=`${e.line}:${e.column-e.raw.length}`),t}if(this.match(cK.STRING)){let e=this.advance(),t=new pl(e.value);return void 0!==e.startColumn&&(t._pos=`${e.line}:${e.startColumn}`),t}if(this.match(cK.BOOLEAN)){let e=this.advance(),t=new pl(e.value);return t._pos=this.startOf(e),t}if(this.match(cK.IDENTIFIER)){let e=this.advance(),t=e.value;(this.functionNames.has(t)&&this.peek().type!==cK.LPAREN&&!this.isCurrentFunctionParam(t)&&!(this.peek().type===cK.DOT&&oL.has(t))&&!(this.peek().type===cK.DOT&&this.typeNames.has(t))||this.typeVariableNames.has(t)&&!this.isCurrentFunctionParam(t)&&!this.isTypeMemberAccess())&&(t+="_var");let i=new po(t);return i._pos=this.startOf(e),i}if(this.match(cK.LBRACKET))return this.parseArrayLiteral();if(this.match(cK.LPAREN)){this.advance(),this.skipNewlines();let e=this.parseExpression();return this.skipNewlines(),this.expect(cK.RPAREN),e}if(this.match(cK.KEYWORD,"if"))return this.parseIfExpression();if(this.match(cK.KEYWORD,"switch"))return this.parseSwitchExpression();if(this.match(cK.KEYWORD,"for"))return this.parseForExpression();if(this.match(cK.KEYWORD,"while"))return this.parseWhileExpression();throw this.unexpected(e)}parseArrayLiteral(){let e=this.expect(cK.LBRACKET),t=[];for(;!this.match(cK.RBRACKET)&&(this.skipNewlines(),!this.match(cK.RBRACKET));)t.push(this.parseExpression()),this.match(cK.COMMA)&&this.advance(),this.skipNewlines();this.expect(cK.RBRACKET);let i=new py(t);return this.tupleLiteralStart.set(i,e),i._pos=this.startOf(e),i}parseIfExpression(){this.expect(cK.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines(),this.expect(cK.INDENT);let t=[];for(;!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){let e=this.parseStatement();e&&t.push(e)}this.advance(),this._valueOfTrailingLoop(t);let i=[];if(this.match(cK.KEYWORD,"else"))if(this.advance(),this.skipNewlines(),this.match(cK.KEYWORD,"if")){let r=this.parseIfExpression();if(!this.needsIIFE(t,i))return new pf(e,this.getBlockValue(t),r);{let i=new pf(e,new ps(t),r);return i.needsIIFE=!0,i.consequentStmts=t,i.alternateExpr=r,i}}else{for(this.expect(cK.INDENT);!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){let e=this.parseStatement();e&&i.push(e)}this.advance(),this._valueOfTrailingLoop(i)}if(this.needsIIFE(t,i)){let r=new pf(e,new ps(t),new ps(i));return r.needsIIFE=!0,r.consequentStmts=t,r.alternateStmts=i,r}return new pf(e,this.getBlockValue(t),i.length>0?this.getBlockValue(i):new pl(null))}needsIIFE(e,t){if(e.length>1||t.length>1)return!0;let i=e=>e.some(e=>"IfStatement"===e.type||"ForStatement"===e.type||"WhileStatement"===e.type||"BlockStatement"===e.type);return i(e)||i(t)}parseSwitchExpression(){this.expect(cK.KEYWORD,"switch");let e=null;this.match(cK.NEWLINE)||this.match(cK.INDENT)||(e=this.parseExpression()),this.skipNewlines(),this.expect(cK.INDENT);let t=[];for(;!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){let e=null;this.match(cK.OPERATOR,"=>")||(e=this.parseExpression()),this.expect(cK.OPERATOR,"=>"),this.skipNewlines();let i=[];if(this.match(cK.INDENT)){for(this.advance();!this.match(cK.DEDENT)&&!this.match(cK.EOF)&&(this.skipNewlines(),!this.match(cK.DEDENT));){let e=this.parseStatement();e&&i.push(e)}this.advance()}else{let e=this.parseStatement();e&&i.push(e)}this._valueOfTrailingLoop(i);let r=this.getBlockValue(i);t.push(new pw(e,r,i)),this.skipNewlines()}return this.advance(),new pv(e,t)}parseForExpression(){let e=this.parseForStatement();return e.isExpression=!0,e}parseWhileExpression(){let e=this.parseWhileStatement();return e.isExpression=!0,e}getBlockValue(e){if(0===e.length)return new pl(null);let t=e[e.length-1];return"ExpressionStatement"===t.type?t.expression:"VariableDeclaration"===t.type&&t.declarations.length>0?t.declarations[0].id:new pl(null)}};pk(pI,"STATEMENT_KEYWORDS",new Set(["if","else","for","while","switch"]));let pC={"array.new_bool":[["size","initial_value"]],"array.new_box":[["size","initial_value"]],"array.new_color":[["size","initial_value"]],"array.new_float":[["size","initial_value"]],"array.new_int":[["size","initial_value"]],"array.new_label":[["size","initial_value"]],"array.new_line":[["size","initial_value"]],"array.new_linefill":[["size","initial_value"]],"array.new_string":[["size","initial_value"]],"array.new_table":[["size","initial_value"]],"array.new<type>":[["size","initial_value"]],bool:[["x"]],box:[["x"]],"chart.point.copy":[["id"]],"chart.point.from_index":[["index","price"]],"chart.point.from_time":[["time","price"]],"chart.point.new":[["time","index","price"]],"chart.point.now":[["price"]],color:[["x"]],"color.b":[["color"]],"color.from_gradient":[["value","bottom_value","top_value","bottom_color","top_color"]],"color.g":[["color"]],"color.new":[["color","transp"]],"color.r":[["color"]],"color.rgb":[["red","green","blue","transp"]],"color.t":[["color"]],fixnan:[["source"]],float:[["x"]],"footprint.buy_volume":[["id"]],"footprint.delta":[["id"]],"footprint.get_row_by_price":[["id","price"]],"footprint.poc":[["id"]],"footprint.rows":[["id"]],"footprint.sell_volume":[["id"]],"footprint.total_volume":[["id"]],"footprint.vah":[["id"]],"footprint.val":[["id"]],int:[["x"]],label:[["x"]],line:[["x"]],linefill:[["x"]],"linefill.new":[["line1","line2","color"]],"math.abs":[["number"]],"math.acos":[["angle"]],"math.asin":[["angle"]],"math.atan":[["angle"]],"math.ceil":[["number"]],"math.cos":[["angle"]],"math.exp":[["number"]],"math.floor":[["number"]],"math.log":[["number"]],"math.log10":[["number"]],"math.pow":[["base","exponent"]],"math.random":[["min","max","seed"]],"math.round":[["number"],["number","precision"]],"math.round_to_mintick":[["number"]],"math.sign":[["number"]],"math.sin":[["angle"]],"math.sqrt":[["number"]],"math.sum":[["source","length"]],"math.tan":[["angle"]],"math.todegrees":[["radians"]],"math.toradians":[["degrees"]],"matrix.new<type>":[["rows","columns","initial_value"]],max_bars_back:[["var","num"]],na:[["x"]],nz:[["source","replacement"]],"polyline.new":[["points","curved","closed","xloc","line_color","fill_color","line_style","line_width","force_overlay"]],"request.currency_rate":[["from","to","ignore_invalid_currency"]],"request.dividends":[["ticker","field","gaps","lookahead","ignore_invalid_symbol","currency"]],"request.earnings":[["ticker","field","gaps","lookahead","ignore_invalid_symbol","currency"]],"request.economic":[["country_code","field","gaps","ignore_invalid_symbol"]],"request.financial":[["symbol","financial_id","period","gaps","ignore_invalid_symbol","currency"]],"request.quandl":[["ticker","gaps","index","ignore_invalid_symbol"]],"request.security":[["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency","calc_bars_count"]],"request.security_lower_tf":[["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe","calc_bars_count"]],"request.seed":[["source","symbol","expression","ignore_invalid_symbol","calc_bars_count"]],"request.splits":[["ticker","field","gaps","lookahead","ignore_invalid_symbol"]],"runtime.error":[["message"]],"str.contains":[["source","str"]],"str.endswith":[["source","str"]],"str.format_time":[["time","format","timezone"]],"str.length":[["string"]],"str.lower":[["source"]],"str.match":[["source","regex"]],"str.pos":[["source","str"]],"str.repeat":[["source","repeat","separator"]],"str.replace":[["source","target","replacement","occurrence"]],"str.replace_all":[["source","target","replacement"]],"str.split":[["string","separator"]],"str.startswith":[["source","str"]],"str.substring":[["source","begin_pos","end_pos"]],"str.tonumber":[["string"]],"str.tostring":[["value"],["value","format"]],"str.trim":[["source"]],"str.upper":[["source"]],"strategy.closedtrades.commission":[["trade_num"]],"strategy.closedtrades.entry_bar_index":[["trade_num"]],"strategy.closedtrades.entry_comment":[["trade_num"]],"strategy.closedtrades.entry_id":[["trade_num"]],"strategy.closedtrades.entry_price":[["trade_num"]],"strategy.closedtrades.entry_time":[["trade_num"]],"strategy.closedtrades.exit_bar_index":[["trade_num"]],"strategy.closedtrades.exit_comment":[["trade_num"]],"strategy.closedtrades.exit_id":[["trade_num"]],"strategy.closedtrades.exit_price":[["trade_num"]],"strategy.closedtrades.exit_time":[["trade_num"]],"strategy.closedtrades.max_drawdown":[["trade_num"]],"strategy.closedtrades.max_drawdown_percent":[["trade_num"]],"strategy.closedtrades.max_runup":[["trade_num"]],"strategy.closedtrades.max_runup_percent":[["trade_num"]],"strategy.closedtrades.profit":[["trade_num"]],"strategy.closedtrades.profit_percent":[["trade_num"]],"strategy.closedtrades.size":[["trade_num"]],"strategy.convert_to_account":[["value"]],"strategy.convert_to_symbol":[["value"]],"strategy.default_entry_qty":[["fill_price"]],"strategy.opentrades.commission":[["trade_num"]],"strategy.opentrades.entry_bar_index":[["trade_num"]],"strategy.opentrades.entry_comment":[["trade_num"]],"strategy.opentrades.entry_id":[["trade_num"]],"strategy.opentrades.entry_price":[["trade_num"]],"strategy.opentrades.entry_time":[["trade_num"]],"strategy.opentrades.max_drawdown":[["trade_num"]],"strategy.opentrades.max_drawdown_percent":[["trade_num"]],"strategy.opentrades.max_runup":[["trade_num"]],"strategy.opentrades.max_runup_percent":[["trade_num"]],"strategy.opentrades.profit":[["trade_num"]],"strategy.opentrades.profit_percent":[["trade_num"]],"strategy.opentrades.size":[["trade_num"]],"strategy.risk.allow_entry_in":[["value"]],"strategy.risk.max_cons_loss_days":[["count","alert_message"]],"strategy.risk.max_drawdown":[["value","type","alert_message"]],"strategy.risk.max_intraday_filled_orders":[["count","alert_message"]],"strategy.risk.max_intraday_loss":[["value","type","alert_message"]],"strategy.risk.max_position_size":[["contracts"]],string:[["x"]],"syminfo.prefix":[["symbol"]],"syminfo.ticker":[["symbol"]],"ta.alma":[["series","length","offset","sigma","floor"]],"ta.atr":[["length"]],"ta.barssince":[["condition"]],"ta.bb":[["series","length","mult"]],"ta.bbw":[["series","length","mult"]],"ta.cci":[["source","length"]],"ta.change":[["source","length"]],"ta.cmo":[["series","length"]],"ta.cog":[["source","length"]],"ta.correlation":[["source1","source2","length"]],"ta.cross":[["source1","source2"]],"ta.crossover":[["source1","source2"]],"ta.crossunder":[["source1","source2"]],"ta.cum":[["source"]],"ta.dev":[["source","length"]],"ta.dmi":[["diLength","adxSmoothing"]],"ta.ema":[["source","length"]],"ta.falling":[["source","length"]],"ta.highest":[["source","length"]],"ta.highestbars":[["source","length"]],"ta.hma":[["source","length"]],"ta.kc":[["series","length","mult","useTrueRange"]],"ta.kcw":[["series","length","mult","useTrueRange"]],"ta.linreg":[["source","length","offset"]],"ta.lowest":[["source","length"]],"ta.lowestbars":[["source","length"]],"ta.macd":[["source","fastlen","slowlen","siglen"]],"ta.max":[["source"]],"ta.median":[["source","length"]],"ta.mfi":[["series","length"]],"ta.min":[["source"]],"ta.mode":[["source","length"]],"ta.mom":[["source","length"]],"ta.percentile_linear_interpolation":[["source","length","percentage"]],"ta.percentile_nearest_rank":[["source","length","percentage"]],"ta.percentrank":[["source","length"]],"ta.pivot_point_levels":[["type","anchor","developing"]],"ta.pivothigh":[["leftbars","rightbars"],["source","leftbars","rightbars"]],"ta.pivotlow":[["leftbars","rightbars"],["source","leftbars","rightbars"]],"ta.range":[["source","length"]],"ta.rci":[["source","length"]],"ta.rising":[["source","length"]],"ta.rma":[["source","length"]],"ta.roc":[["source","length"]],"ta.rsi":[["source","length"]],"ta.sar":[["start","inc","max"]],"ta.sma":[["source","length"]],"ta.stdev":[["source","length","biased"]],"ta.stoch":[["source","high","low","length"]],"ta.supertrend":[["factor","atrPeriod"]],"ta.swma":[["source"]],"ta.tr":[["handle_na"]],"ta.tsi":[["source","short_length","long_length"]],"ta.valuewhen":[["condition","source","occurrence"]],"ta.variance":[["source","length","biased"]],"ta.vwap":[["source","anchor"],["source","anchor","stdev_mult"]],"ta.vwma":[["source","length"]],"ta.wma":[["source","length"]],"ta.wpr":[["length"]],table:[["x"]],"ticker.heikinashi":[["symbol"]],"ticker.inherit":[["from_tickerid","symbol"]],"ticker.kagi":[["symbol","reversal"],["symbol","param","style"]],"ticker.linebreak":[["symbol","number_of_lines"]],"ticker.modify":[["tickerid","session","adjustment","backadjustment","settlement_as_close"]],"ticker.new":[["prefix","ticker","session","adjustment","backadjustment","settlement_as_close"]],"ticker.pointfigure":[["symbol","source","style","param","reversal"]],"ticker.renko":[["symbol","style","param","request_wicks","source"]],"ticker.standard":[["symbol"]],"timeframe.change":[["timeframe"]],"timeframe.from_seconds":[["seconds"]],"timeframe.in_seconds":[["timeframe"]],"volume_row.buy_volume":[["id"]],"volume_row.delta":[["id"]],"volume_row.down_price":[["id"]],"volume_row.has_buy_imbalance":[["id"]],"volume_row.has_sell_imbalance":[["id"]],"volume_row.sell_volume":[["id"]],"volume_row.total_volume":[["id"]],"volume_row.up_price":[["id"]]};var pM=Object.defineProperty,pP=(e,t,i)=>((e,t,i)=>t in e?pM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let pD=new Set(oW),pR=e=>"string"==typeof e&&/(^|\s)string$/.test(e),pO=e=>e?.type==="Identifier"&&"na"===e.name;class pj{constructor(e={}){pP(this,"indent"),pP(this,"indentStr"),pP(this,"output"),pP(this,"sourceCode"),pP(this,"sourceLines"),pP(this,"lastCommentedLine"),pP(this,"includeSourceComments"),pP(this,"paramRenameCounter"),pP(this,"functionParams"),pP(this,"methodParams"),pP(this,"userFunctionCollisions"),pP(this,"userFunctionRenames"),pP(this,"renamedTypeNames"),pP(this,"methodNameCounts",new Map),pP(this,"stringVarScopes",[new Map]),this.indent=0,this.indentStr=e.indentStr||" ",this.output=[],this.sourceCode=e.sourceCode||null,this.sourceLines=this.sourceCode?this.sourceCode.split(`
319
+ `):[],this.lastCommentedLine=-1,this.includeSourceComments=e.includeSourceComments||!1,this.paramRenameCounter=0,this.functionParams=new Map,this.methodParams=new Map,this.userFunctionCollisions=new Set,this.userFunctionRenames=new Map,this.renamedTypeNames=new Set}renameDiscardTargets(e){let t=new Set;for(let i of e)i&&"Identifier"===i.type&&("_"===i.name?i.name=this.freshDiscardName():t.has(i.name)&&(i.name=`${i.name}${this.paramRenameCounter++}`),t.add(i.name))}freshDiscardName(){return`_$${this.paramRenameCounter++}`}generate(e){if(this.output=[],this.indent=0,this.lastCommentedLine=-1,this.functionParams=new Map,this.methodParams=new Map,this.userFunctionCollisions=new Set,this.userFunctionRenames=new Map,"Program"===e.type)this.preProcessAST(e),this.generateProgram(e);else throw Error(`Expected Program node, got ${e.type}`);return this.output.join("")}preProcessAST(e){this.renameConflictingVariables(e),this.renameFunctionsSharingTypeNames(e),this.collectFunctionParams(e)}renameFunctionsSharingTypeNames(e){let t=new Set;for(let i of e.body)"TypeDefinition"===i.type&&"string"==typeof i.name&&t.add(i.name);if(0===t.size)return;let i=new Map;for(let r of e.body){let e="FunctionDeclaration"!==r.type||r.id?.isMethod?void 0:r.id?.name;e&&t.has(e)&&!i.has(e)&&i.set(e,`${e}_$${this.paramRenameCounter++}`)}if(0===i.size)return;let r=e=>{if(!(!e||"object"!=typeof e))for(let t of("FunctionDeclaration"===e.type&&!e.id?.isMethod&&i.has(e.id?.name)&&(e.id.name=i.get(e.id.name)),"CallExpression"===e.type&&e.callee?.type==="Identifier"&&i.has(e.callee.name)&&(e.callee.name=i.get(e.callee.name)),Object.keys(e))){if("type"===t)continue;let i=e[t];if(Array.isArray(i))for(let e of i)r(e);else i&&"object"==typeof i&&i.type&&r(i)}};r(e)}renameConflictingVariables(e){let t=new Map;this.renamedTypeNames=new Set,this.collectConflictingVarNames(e,t),t.size>0&&this.renameVariableRefsInAST(e,t)}renameTypeString(e,t){return"string"!=typeof e||0===this.renamedTypeNames.size?e:e.replace(/[A-Za-z_]\w*/g,e=>this.renamedTypeNames.has(e)&&t.has(e)?t.get(e):e)}isReservedName(e){return!!e&&(oL.has(e)||oB.has(e))}collectConflictingVarNames(e,t){if(!(!e||"object"!=typeof e)){if("VariableDeclaration"===e.type){for(let i of e.declarations)if(i.id?.type==="Identifier"&&this.isReservedName(i.id.name)&&!t.has(i.id.name)&&t.set(i.id.name,`${i.id.name}_$${this.paramRenameCounter++}`),i.id?.type==="ArrayPattern")for(let e of i.id.elements)e?.type==="Identifier"&&this.isReservedName(e.name)&&!t.has(e.name)&&t.set(e.name,`${e.name}_$${this.paramRenameCounter++}`)}for(let i of(("AssignmentExpression"===e.type||"ReassignmentExpression"===e.type)&&e.left?.type==="Identifier"&&this.isReservedName(e.left.name)&&!t.has(e.left.name)&&t.set(e.left.name,`${e.left.name}_$${this.paramRenameCounter++}`),"FunctionDeclaration"===e.type&&e.id?.type==="Identifier"&&!e.id.isMethod&&this.isReservedName(e.id.name)&&(t.has(e.id.name)||t.set(e.id.name,`${e.id.name}_$${this.paramRenameCounter++}`),this.userFunctionRenames.set(e.id.name,t.get(e.id.name)),oL.has(e.id.name)&&this.userFunctionCollisions.add(e.id.name)),"TypeDefinition"===e.type&&"string"==typeof e.name&&oB.has(e.name)&&(t.has(e.name)||t.set(e.name,`${e.name}_$${this.paramRenameCounter++}`),this.renamedTypeNames.add(e.name)),Object.keys(e))){if("type"===i)continue;let r=e[i];if(Array.isArray(r))for(let e of r)e&&"object"==typeof e&&this.collectConflictingVarNames(e,t);else r&&"object"==typeof r&&r.type&&this.collectConflictingVarNames(r,t)}}}renameVariableRefsInAST(e,t){if(!(!e||"object"!=typeof e)){if("FunctionDeclaration"===e.type){e.id?.type==="Identifier"&&t.has(e.id.name)&&(e.id.name=t.get(e.id.name)),e.id&&(e.id.returnType=this.renameTypeString(e.id.returnType,t)),e.returnType=this.renameTypeString(e.returnType,t);let i=t;for(let r of e.params??[]){let e="AssignmentPattern"===r.type?r.left:r;e&&(e.varType=this.renameTypeString(e.varType,t),"Identifier"===e.type&&i.has(e.name)&&(i===t&&(i=new Map(t)),i.delete(e.name)))}for(let t of e.params??[])"AssignmentPattern"===t.type&&t.right&&this.renameVariableRefsInAST(t.right,i);i.size>0&&this.renameVariableRefsInAST(e.body,i);return}if("TypeDefinition"===e.type){for(let i of("string"==typeof e.name&&t.has(e.name)&&(e.name=t.get(e.name)),e.fields??[]))i.type=this.renameTypeString(i.type,t),i.defaultValue&&this.renameVariableRefsInAST(i.defaultValue,t);return}if("VariableDeclarator"===e.type&&(e.varType=this.renameTypeString(e.varType,t)),"Identifier"===e.type&&(e.varType=this.renameTypeString(e.varType,t)),"CallExpression"===e.type){if(e.callee?.type==="Identifier"&&t.has(e.callee.name)?(oB.has(e.callee.name)||this.userFunctionCollisions.has(e.callee.name))&&(e.callee.name=t.get(e.callee.name)):e.callee?.type==="Identifier"&&this.userFunctionRenames.has(e.callee.name)?e.callee.name=this.userFunctionRenames.get(e.callee.name):this.renameVariableRefsInAST(e.callee,t),e.arguments)for(let i of e.arguments)this.renameVariableRefsInAST(i,t);return}if("MemberExpression"===e.type)return!e.computed&&e.object?.type==="Identifier"&&t.has(e.object.name)&&oL.has(e.object.name)?void 0:!e.computed&&e.property?.type==="Identifier"&&t.has(e.property.name)?void this.renameVariableRefsInAST(e.object,t):(this.renameVariableRefsInAST(e.object,t),void(e.computed&&this.renameVariableRefsInAST(e.property,t)));if("Property"===e.type)return void this.renameVariableRefsInAST(e.value,t);if("Identifier"===e.type&&t.has(e.name)){e.name=t.get(e.name);return}for(let i of Object.keys(e)){if("type"===i)continue;let r=e[i];if(Array.isArray(r))for(let e of r)e&&"object"==typeof e&&this.renameVariableRefsInAST(e,t);else r&&"object"==typeof r&&r.type&&this.renameVariableRefsInAST(r,t)}}}collectFunctionParams(e){if(!(!e||"object"!=typeof e)){if("FunctionDeclaration"===e.type&&e.id?.name){let t={names:[],defaults:[]};for(let i of e.params)if("Identifier"===i.type)t.names.push(i.name),t.defaults.push(null);else if("AssignmentPattern"===i.type&&i.left?.name){t.names.push(i.left.name);let e=pR(i.left.varType)&&pO(i.right);t.defaults.push(e?{type:"Literal",value:"",raw:'""'}:i.right)}if(this.functionParams.set(e.id.name,t),e.id.isMethod){let i=this.methodParams.get(e.id.name)??[];i.push({names:t.names.slice(1),defaults:t.defaults.slice(1)}),this.methodParams.set(e.id.name,i)}}if(Array.isArray(e.body))for(let t of e.body)this.collectFunctionParams(t);else e.body&&"object"==typeof e.body&&this.collectFunctionParams(e.body)}}writeSourceComment(e,t=null){if(!this.sourceLines.length)return;let i=t||e,r=[];for(let t=e-1;t<i&&t<this.sourceLines.length;t++)if(t>this.lastCommentedLine){let e=this.sourceLines[t].trim();!e||e.startsWith("//@")||e.startsWith("//")||r.push(this.sourceLines[t])}if(r.length>0){for(let e of r)this.write(this.indentStr.repeat(this.indent)),this.write("/// "),this.write(e.trimEnd()),this.write(`
320
+ `);this.lastCommentedLine=Math.max(this.lastCommentedLine,i-1)}}write(e){this.output.push(e)}writeLine(e=""){e?this.output.push(this.indentStr.repeat(this.indent)+e+`
321
+ `):this.output.push(`
322
+ `)}increaseIndent(){this.indent++}decreaseIndent(){this.indent--}generateProgram(e){for(let t=0;t<e.body.length;t++)if(this.generateStatement(e.body[t]),t<e.body.length-1){let i=e.body[t],r=e.body[t+1];("FunctionDeclaration"===i.type||"TypeDefinition"===i.type)&&("FunctionDeclaration"===r.type||"TypeDefinition"===r.type)&&this.writeLine()}}generateStatement(e){switch(this.includeSourceComments&&e._line&&this.sourceLines.length>0&&this.writeSourceComment(e._line),e.type){case"FunctionDeclaration":return this.generateFunctionDeclaration(e);case"VariableDeclaration":return this.generateVariableDeclaration(e);case"ExpressionStatement":return this.generateExpressionStatement(e);case"IfStatement":return this.generateIfStatement(e);case"ForStatement":return this.generateForStatement(e);case"WhileStatement":return this.generateWhileStatement(e);case"ReturnStatement":return this.generateReturnStatement(e);case"BlockStatement":if(e._sequence){for(let t of e.body)this.generateStatement(t);return}return this.generateBlockStatement(e);case"TypeDefinition":return this.generateTypeDefinition(e);case"ImportDeclaration":return;default:throw Error(`Unknown statement type: ${e.type}`)}}generateTypeDefinition(e){if(this.write(this.indentStr.repeat(this.indent)),this.write(`const ${e.name} = Type({`),e.fields.length>0){this.write(" ");for(let t=0;t<e.fields.length;t++){let i=e.fields[t];i.defaultValue?(this.write(`${i.name}: ['${i.type}', `),this.generateExpression(i.defaultValue),this.write("]")):this.write(`${i.name}: '${i.type}'`),t<e.fields.length-1&&this.write(", ")}this.write(" ")}this.write(`});
323
+ `)}renameIdentifiersInAST(e,t){if(!(!e||"object"!=typeof e)){if("Identifier"===e.type&&t.has(e.name)){e.name=t.get(e.name);return}if("FunctionDeclaration"!==e.type)for(let i of Object.keys(e)){if("type"===i)continue;let r=e[i];if(Array.isArray(r))for(let e of r)e&&"object"==typeof e&&this.renameIdentifiersInAST(e,t);else r&&"object"==typeof r&&r.type&&this.renameIdentifiersInAST(r,t)}}}renameParamRefsInBody(e,t){if(!(!e||"object"!=typeof e)&&"FunctionDeclaration"!==e.type){if("CallExpression"===e.type){if(e.callee?.type==="Identifier"&&t.has(e.callee.name)||this.renameParamRefsInBody(e.callee,t),e.arguments)for(let i of e.arguments)this.renameParamRefsInBody(i,t);return}if("MemberExpression"===e.type){if(!e.computed&&e.object?.type==="Identifier"&&t.has(e.object.name))return;this.renameParamRefsInBody(e.object,t),e.computed&&this.renameParamRefsInBody(e.property,t);return}if("Property"===e.type)return void this.renameParamRefsInBody(e.value,t);if("Identifier"===e.type&&t.has(e.name)){e.name=t.get(e.name);return}for(let i of Object.keys(e)){if("type"===i)continue;let r=e[i];if(Array.isArray(r))for(let e of r)e&&"object"==typeof e&&this.renameParamRefsInBody(e,t);else r&&"object"==typeof r&&r.type&&this.renameParamRefsInBody(r,t)}}}generateFunctionDeclaration(e){let t;this.write(this.indentStr.repeat(this.indent));let i=e.id.isMethod,r=new Map;for(let t of e.params){let e="AssignmentPattern"===t.type?t.left.name:t.name;if(e&&pD.has(e)){let t=`${e}_$${this.paramRenameCounter++}`;r.set(e,t)}}let n=new Map;i&&e.params.length>0&&("Identifier"===(t=e.params[0]).type&&"this"===t.name||"AssignmentPattern"===t.type&&t.left?.name==="this")&&n.set("this","self");let s=new Map;if(e.params.forEach((e,t)=>{let n=("AssignmentPattern"===e.type?e.left:e)?.name;!n||!oB.has(n)||r.has(n)||i&&0===t&&"this"===n||s.set(n,`${n}_$${this.paramRenameCounter++}`)}),r.size>0||n.size>0||s.size>0){for(let t of e.params){let e="AssignmentPattern"===t.type?t.left:t;if(e?.type==="Identifier"){let t=r.get(e.name)??n.get(e.name)??s.get(e.name);t&&(e.name=t)}"AssignmentPattern"===t.type&&t.right&&(r.size>0&&this.renameParamRefsInBody(t.right,r),n.size>0&&this.renameIdentifiersInAST(t.right,n),s.size>0&&this.renameVariableRefsInAST(t.right,s))}r.size>0&&this.renameParamRefsInBody(e.body,r),n.size>0&&this.renameIdentifiersInAST(e.body,n),s.size>0&&this.renameVariableRefsInAST(e.body,s)}let a=e.id.name;if(i){let t=(this.methodNameCounts.get(e.id.name)??0)+1;this.methodNameCounts.set(e.id.name,t),a=1===t?`$M_${e.id.name}`:`$M_${e.id.name}$${t}`}this.write("function "),this.write(a),this.write("(");let o=e.params,l=new Map;for(let e=0;e<o.length;e++){let t=o[e];if("Identifier"===t.type)this.write(t.name),l.set(t.name,pR(t.varType));else if("AssignmentPattern"===t.type){let e=pR(t.left.varType);l.set(t.left.name,e),this.write(t.left.name),this.write(" = "),e&&pO(t.right)?this.write('""'):this.generateExpression(t.right)}e<o.length-1&&this.write(", ")}this.write(") "),this.stringVarScopes.push(l);try{this.generateBlockStatement(e.body,!1)}finally{this.stringVarScopes.pop()}if(this.write(`
324
+ `),i){this.write(this.indentStr.repeat(this.indent)),this.write(`${a}.__pineMethod__ = true;
325
+ `);let t=e.params[0],i=t?.type==="AssignmentPattern"?t.left?.varType:t?.varType;"string"==typeof i&&i.length>0&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${a}.__pineReceiverType__ = ${JSON.stringify(i)};
326
+ `))}let h=[];for(let t=0;t<e.params.length;t++){let r=e.params[t],n="AssignmentPattern"===r.type?r.left?.name:r.name;if(i&&0===t&&"self"===n)continue;let s="AssignmentPattern"===r.type?r.left?.varType:r.varType;n&&s&&h.push([n,s])}if(h.length>0){this.write(this.indentStr.repeat(this.indent));let e=h.map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ");this.write(`${a}.__pineParamTypes__ = {${e}};
327
+ `)}}generateVariableDeclaration(e){let t="var"===e.kind||"varip"===e.kind?"var":"let";for(let i=0;i<e.declarations.length;i++){let r=e.declarations[i];if(r.id?.type==="Identifier"&&"_"===r.id.name?r.id.name=this.freshDiscardName():r.id?.type==="ArrayPattern"&&this.renameDiscardTargets(r.id.elements),"varip"===e.kind&&r.id?.type==="Identifier"&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${JSON.stringify(`__pineVarip:${r.id.name}`)};
328
+ `)),r.init&&"ConditionalExpression"===r.init.type&&r.init.needsIIFE){let e="Identifier"===r.id.type?r.id.name:null;if(e){this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" "),this.write(e),this.write(`;
329
+ `),this.generateIfStatementWithAssignment(r.init,e);continue}}this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" "),"Identifier"===r.id.type?this.write(r.id.name):"ArrayPattern"===r.id.type&&(this.write("["),this.write(r.id.elements.map(e=>e.name).join(", ")),this.write("]"));let n="Identifier"===r.id.type&&(r.id.varType?pR(r.id.varType):r.init?.type==="Literal"&&"string"==typeof r.init.value);"Identifier"===r.id.type&&this.stringVarScopes[this.stringVarScopes.length-1].set(r.id.name,n),r.init&&(this.write(" = "),n&&pO(r.init)?this.write('""'):this.generateExpression(r.init)),this.write(`;
330
+ `);let s=r.id?.varType,a=r.id?.type==="Identifier"?r.id.name:null;a&&"string"==typeof s&&/^[A-Za-z_$][\w$]*$/.test(s)&&s[0]===s[0].toUpperCase()?(this.write(this.indentStr.repeat(this.indent)),this.write(`"__pineUdtVar:${a}=${s}";
331
+ `)):a&&"string"==typeof s&&s.length>0&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${JSON.stringify(`__pineTypedVar:${a}=${s}`)};
332
+ `))}}generateExpressionStatement(e){if("SwitchExpression"===e.expression.type&&null===e.expression.discriminant){this.write(this.indentStr.repeat(this.indent)),this.generateSwitchAsIfElse(e.expression),this.write(`
333
+ `);return}this.write(this.indentStr.repeat(this.indent)),this.generateExpression(e.expression),this.write(`;
334
+ `)}generateIfStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(") "),this.generateBlockStatement(e.consequent,!1),e.alternate?(this.write(" else "),"IfStatement"===e.alternate.type?this.generateIfStatement(e.alternate):this.generateBlockStatement(e.alternate,!1)):this.write(`
335
+ `)}generateIfStatementWithAssignment(e,t){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {
336
+ `),this.indent++,e.consequentStmts)for(let i=0;i<e.consequentStmts.length;i++){let r=e.consequentStmts[i];i===e.consequentStmts.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
337
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternateExpr)this.write(` else {
338
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(e.alternateExpr),this.write(`;
339
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");else if(e.alternateStmts&&e.alternateStmts.length>0){this.write(` else {
340
+ `),this.indent++;for(let i=0;i<e.alternateStmts.length;i++){let r=e.alternateStmts[i];i===e.alternateStmts.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
341
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}else this.write(` else {
342
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(` = false;
343
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");this.write(`
344
+ `)}generateNestedIfWithAssignments(e,t){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {
345
+ `),this.indent++,"BlockStatement"===e.consequent.type&&e.consequent.body.length>0)for(let i=0;i<e.consequent.body.length;i++){let r=e.consequent.body[i];i===e.consequent.body.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
346
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternate)if("IfStatement"===e.alternate.type){if(this.write(" else "),this.write("if ("),this.generateExpression(e.alternate.test),this.write(`) {
347
+ `),this.indent++,"BlockStatement"===e.alternate.consequent.type&&e.alternate.consequent.body.length>0)for(let i=0;i<e.alternate.consequent.body.length;i++){let r=e.alternate.consequent.body[i];i===e.alternate.consequent.body.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
348
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternatesWithAssignments(e.alternate.alternate,t)}else if("BlockStatement"===e.alternate.type&&e.alternate.body.length>0){this.write(` else {
349
+ `),this.indent++;for(let i=0;i<e.alternate.body.length;i++){let r=e.alternate.body[i];i===e.alternate.body.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
350
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
351
+ `)}else this.write(` else {
352
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(` = false;
353
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
354
+ `);else this.write(`
355
+ `)}generateNestedIfAlternatesWithAssignments(e,t){if(e)if("IfStatement"===e.type){if(this.write(" else "),this.write("if ("),this.generateExpression(e.test),this.write(`) {
356
+ `),this.indent++,"BlockStatement"===e.consequent.type&&e.consequent.body.length>0)for(let i=0;i<e.consequent.body.length;i++){let r=e.consequent.body[i];i===e.consequent.body.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
357
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternatesWithAssignments(e.alternate,t)}else if("BlockStatement"===e.type&&e.body.length>0){this.write(` else {
358
+ `),this.indent++;for(let i=0;i<e.body.length;i++){let r=e.body[i];i===e.body.length-1?"ExpressionStatement"===r.type?(this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(" = "),this.generateExpression(r.expression),this.write(`;
359
+ `)):"IfStatement"===r.type?this.generateNestedIfWithAssignments(r,t):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
360
+ `)}else this.write(` else {
361
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(t),this.write(` = false;
362
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
363
+ `)}generateForStatement(e){if(this.write(this.indentStr.repeat(this.indent)),e.isForIn){if(this.write("for ("),e.init&&"VariableDeclaration"===e.init.type){let t=e.init.declarations[0];this.write(`${e.init.kind} `),"Identifier"===t.id.type?this.write(t.id.name):"ArrayPattern"===t.id.type&&(this.renameDiscardTargets(t.id.elements),this.write("["),this.write(t.id.elements.map(e=>e.name).join(", ")),this.write("]")),this.write(" of "),this.generateExpression(t.init)}this.write(") "),this.generateBlockStatement(e.body,!1);return}this.write("for ("),e.init&&("VariableDeclaration"===e.init.type?(this.write(`${e.init.kind} `),e.init.declarations.forEach((e,t)=>{t&&this.write(", "),this.write(e.id.name),e.init&&(this.write(" = "),this.generateExpression(e.init))})):this.generateExpression(e.init)),this.write("; "),e.test&&this.generateExpression(e.test),this.write("; "),e.update&&("AssignmentExpression"===e.update.type?(this.generateExpression(e.update.left),this.write(` ${e.update.operator} `),this.generateExpression(e.update.right)):this.generateExpression(e.update)),this.write(") "),this.generateBlockStatement(e.body,!1)}generateWhileStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("while ("),this.generateExpression(e.test),this.write(") "),this.generateBlockStatement(e.body,!1)}generateReturnStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("return"),e.argument&&(this.write(" "),this.generateExpression(e.argument)),this.write(`;
364
+ `)}generateBlockStatement(e,t=!0){for(let i of(this.write(`{
365
+ `),t?this.increaseIndent():this.indent++,e.body))this.generateStatement(i);t?this.decreaseIndent():this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),t&&this.write(`
366
+ `)}generateExpression(e){switch(e.type){case"Identifier":return this.write(e.name);case"Literal":return this.generateLiteral(e);case"BinaryExpression":case"LogicalExpression":return this.generateBinaryExpression(e);case"UnaryExpression":return this.generateUnaryExpression(e);case"AssignmentExpression":return this.generateAssignmentExpression(e);case"UpdateExpression":return this.generateUpdateExpression(e);case"CallExpression":return this.generateCallExpression(e);case"MemberExpression":return this.generateMemberExpression(e);case"ConditionalExpression":return this.generateConditionalExpression(e);case"ArrayExpression":return this.generateArrayExpression(e);case"ObjectExpression":return this.generateObjectExpression(e);case"SwitchExpression":return this.generateSwitchExpression(e);case"SequenceExpression":return this.generateSequenceExpression(e);case"ForStatement":return this.generateLoopAsExpression(e,"for");case"WhileStatement":return this.generateLoopAsExpression(e,"while");default:throw Error(`Unknown expression type: ${e.type}`)}}generateLiteral(e){if("string"==typeof e.value){let t=e.value.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");this.write(`'${t}'`)}else if(null===e.value)this.write("null");else{let t=String(e.value);"string"==typeof e.raw&&/[.eE]/.test(e.raw)&&!/[.eE]/.test(t)?this.write(t+".0"):this.write(t)}}generateBinaryExpression(e){let t=this.getPrecedence(e);this.getPrecedence(e.left)<t?(this.write("("),this.generateExpression(e.left),this.write(")")):this.generateExpression(e.left),this.write(" ");let i=e.operator;"and"===i?i="&&":"or"===i&&(i="||"),this.write(i),this.write(" ");let r=this.getPrecedence(e.right),n=r<t;r===t&&("-"===i||"/"===i||"%"===i)&&(n=!0),n?(this.write("("),this.generateExpression(e.right),this.write(")")):this.generateExpression(e.right)}generateUnaryExpression(e){let t=e.operator;"not"===t&&(t="!"),this.write(t),15>this.getPrecedence(e.argument)||"UnaryExpression"===e.argument.type&&("-"===t||"+"===t)&&("-"===e.argument.operator||"+"===e.argument.operator)?(this.write("("),this.generateExpression(e.argument),this.write(")")):this.generateExpression(e.argument)}generateAssignmentExpression(e){this.generateExpression(e.left),this.write(" ");let t=e.operator;":="===t&&(t="="),this.write(t),this.write(" "),"="===t&&"Identifier"===e.left.type&&pO(e.right)&&this.isStringVariable(e.left.name)?this.write('""'):this.generateExpression(e.right)}isStringVariable(e){for(let t=this.stringVarScopes.length-1;t>=0;t--){let i=this.stringVarScopes[t].get(e);if(void 0!==i)return i}return!1}generateUpdateExpression(e){e.prefix?(this.write(e.operator),this.generateExpression(e.argument)):(this.generateExpression(e.argument),this.write(e.operator))}userMethodParams(e){if(e?.type!=="MemberExpression"||e.computed||e.property?.type!=="Identifier")return null;let t=e.property.name;return oF.has(t)||e.object?.type==="Identifier"&&pD.has(e.object.name)?null:this.methodParams.get(t)??null}generateCallExpression(e){19>this.getPrecedence(e.callee)?(this.write("("),this.generateExpression(e.callee),this.write(")")):this.generateExpression(e.callee),this.write("(");let t=e.callee?.type==="Identifier"?e.callee.name:null,i=e.arguments.length>0?e.arguments[e.arguments.length-1]:null,r=i?.type==="ObjectExpression",n=t?this.functionParams.get(t):null,s=r?n||this.namedParamsFor(e.callee,e.arguments.length-1,i):null;if(r&&s){let t=e.arguments.slice(0,-1),r=new Map;for(let e of i.properties){let t=e.key?.name||e.key?.value;t&&r.set(t,e.value)}let n=[],a=-1;for(let e=0;e<s.names.length;e++)e<t.length?(n.push(t[e]),a=e):r.has(s.names[e])?(n.push(r.get(s.names[e])),a=e):n.push(s.defaults[e]);let o=n.slice(0,a+1);for(let e=0;e<o.length;e++)null===o[e]?this.write("undefined"):this.generateExpression(o[e]),e<o.length-1&&this.write(", ")}else for(let t=0;t<e.arguments.length;t++){let i=e.arguments[t];"AssignmentExpression"===i.type&&"="===i.operator?this.generateExpression(i.right):this.generateExpression(i),t<e.arguments.length-1&&this.write(", ")}this.write(")")}calleePath(e){if(e?.type==="Identifier")return e.name;if(e?.type==="MemberExpression"&&!e.computed&&e.property?.type==="Identifier"){let t=this.calleePath(e.object);return t?`${t}.${e.property.name}`:null}return null}namedParamsFor(e,t,i){let r=this.calleePath(e),n=r&&/^(array|matrix)\.new(_\w+)?$/.test(r)?pC[`${r.split(".")[0]}.new<type>`]:void 0,s=r?pC[r]??n:void 0;if(s){let e=s.map(e=>({names:e,defaults:e.map(()=>null)}));return this.pickOverload(e,t,i)}let a=this.userMethodParams(e);return a?this.pickOverload(a,t,i):null}pickOverload(e,t,i){let r=i.properties.map(e=>e.key?.name??e.key?.value),n=null,s=1/0;for(let i of e){let e=i.names;if(t>e.length||!r.every(i=>e.indexOf(i)>=t))continue;let a=Math.max(t-1,...r.map(t=>e.indexOf(t)))+1-t-r.length;a<s&&(n=i,s=a)}return n}generateMemberExpression(e){19>this.getPrecedence(e.object)?(this.write("("),this.generateExpression(e.object),this.write(")")):this.generateExpression(e.object),e.computed?(this.write("["),this.generateExpression(e.property),this.write("]")):(this.write("."),this.generateExpression(e.property))}generateConditionalExpression(e){if(e.needsIIFE)return void this.generateIIFEConditional(e);this.write("("),this.generateExpression(e.test),this.write(" ? "),this.generateExpression(e.consequent),this.write(" : "),this.generateExpression(e.alternate),this.write(")")}generateIIFEConditional(e){this.write(`(() => {
367
+ `),this.indent++,this.generateIIFEIfBlock(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateIIFEIfBlock(e){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {
368
+ `),this.indent++,e.consequentStmts)for(let t=0;t<e.consequentStmts.length;t++){let i=e.consequentStmts[t];t===e.consequentStmts.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
369
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternateExpr)this.write(` else {
370
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(e.alternateExpr),this.write(`;
371
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");else if(e.alternateStmts&&e.alternateStmts.length>0){this.write(` else {
372
+ `),this.indent++;for(let t=0;t<e.alternateStmts.length;t++){let i=e.alternateStmts[t];t===e.alternateStmts.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
373
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}else this.write(` else {
374
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;
375
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");this.write(`
376
+ `)}generateNestedIfWithReturns(e){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {
377
+ `),this.indent++,"BlockStatement"===e.consequent.type&&e.consequent.body.length>0)for(let t=0;t<e.consequent.body.length;t++){let i=e.consequent.body[t];t===e.consequent.body.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
378
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternate)if("IfStatement"===e.alternate.type){if(this.write(" else "),this.write("if ("),this.generateExpression(e.alternate.test),this.write(`) {
379
+ `),this.indent++,"BlockStatement"===e.alternate.consequent.type&&e.alternate.consequent.body.length>0)for(let t=0;t<e.alternate.consequent.body.length;t++){let i=e.alternate.consequent.body[t];t===e.alternate.consequent.body.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
380
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternates(e.alternate.alternate)}else if("BlockStatement"===e.alternate.type&&e.alternate.body.length>0){this.write(` else {
381
+ `),this.indent++;for(let t=0;t<e.alternate.body.length;t++){let i=e.alternate.body[t];t===e.alternate.body.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
382
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
383
+ `)}else this.write(` else {
384
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;
385
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
386
+ `);else this.write(`
387
+ `)}generateNestedIfAlternates(e){if(e)if("IfStatement"===e.type){if(this.write(" else "),this.write("if ("),this.generateExpression(e.test),this.write(`) {
388
+ `),this.indent++,"BlockStatement"===e.consequent.type&&e.consequent.body.length>0)for(let t=0;t<e.consequent.body.length;t++){let i=e.consequent.body[t];t===e.consequent.body.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
389
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternates(e.alternate)}else if("BlockStatement"===e.type&&e.body.length>0){this.write(` else {
390
+ `),this.indent++;for(let t=0;t<e.body.length;t++){let i=e.body[t];t===e.body.length-1?"ExpressionStatement"===i.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.expression),this.write(`;
391
+ `)):"IfStatement"===i.type?this.generateNestedIfWithReturns(i):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
392
+ `)}else this.write(` else {
393
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;
394
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
395
+ `)}generateIfWithReturns(e){this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(") "),this.generateBlockWithReturn(e.consequent),e.alternate&&(this.write(" else "),"IfStatement"===e.alternate.type?(this.write(`{
396
+ `),this.indent++,this.generateIfWithReturns(e.alternate),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")):this.generateBlockWithReturn(e.alternate)),this.write(`
397
+ `)}generateBlockWithReturn(e){let t="BlockStatement"===e.type?e.body:[e];this.write(`{
398
+ `),this.indent++,t.forEach((e,i)=>{let r=i===t.length-1;r&&"ExpressionStatement"===e.type?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(e.expression),this.write(`;
399
+ `)):r&&"IfStatement"===e.type?this.generateIfWithReturns(e):(this.write(this.indentStr.repeat(this.indent)),this.generateStatement(e))}),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}generateNestedIfAsExpression(e){if("IfStatement"===e.type){if(this.write("("),this.generateExpression(e.test),this.write(" ? "),"BlockStatement"===e.consequent.type&&e.consequent.body.length>0){let t=e.consequent.body[e.consequent.body.length-1];"ExpressionStatement"===t.type?this.generateExpression(t.expression):"IfStatement"===t.type&&this.generateNestedIfAsExpression(t)}if(this.write(" : "),e.alternate)if("IfStatement"===e.alternate.type)this.generateNestedIfAsExpression(e.alternate);else if("BlockStatement"===e.alternate.type&&e.alternate.body.length>0){let t=e.alternate.body[e.alternate.body.length-1];"ExpressionStatement"===t.type&&this.generateExpression(t.expression)}else this.write("false");else this.write("false");this.write(")")}}generateArrayExpression(e){this.write("[");for(let t=0;t<e.elements.length;t++)this.generateExpression(e.elements[t]),t<e.elements.length-1&&this.write(", ");this.write("]")}generateObjectExpression(e){this.write("{");for(let t=0;t<e.properties.length;t++){let i=e.properties[t];"Identifier"===i.key.type?this.write(i.key.name):this.generateExpression(i.key),this.write(": "),this.generateExpression(i.value),t<e.properties.length-1&&this.write(", ")}this.write("}")}generateSwitchExpression(e){if(null===e.discriminant)return void this.generateSwitchAsIfElseIIFE(e);for(let t of(this.write(`(() => {
400
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write("switch ("),this.generateExpression(e.discriminant),this.write(`) {
401
+ `),this.indent++,e.cases)){if(this.write(this.indentStr.repeat(this.indent)),t.test?(this.write("case "),this.generateExpression(t.test),this.write(`: {
402
+ `)):this.write(`default: {
403
+ `),this.indent++,t.statements&&t.statements.length>0){let e=t.statements[t.statements.length-1];if("ExpressionStatement"===e.type||"VariableDeclaration"===e.type){for(let e=0;e<t.statements.length-1;e++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(t.statements[e]);this.write(this.indentStr.repeat(this.indent)),this.write("return "),"ExpressionStatement"===e.type?this.generateExpression(e.expression):this.generateExpression(t.consequent),this.write(`;
404
+ `)}else if("IfStatement"===e.type){for(let e=0;e<t.statements.length-1;e++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(t.statements[e]);this.generateIfWithReturns(e),this.write(this.indentStr.repeat(this.indent)),this.write(`return null;
405
+ `)}else{for(let e=0;e<t.statements.length;e++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(t.statements[e]);this.write(this.indentStr.repeat(this.indent)),this.write(`return null;
406
+ `)}}else this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(t.consequent),this.write(`;
407
+ `);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
408
+ `)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}
409
+ `),this.writeNaForMissingDefault(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateSwitchAsIfElseIIFE(e){this.write(`(() => {
410
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent));for(let t=0;t<e.cases.length;t++){let i=e.cases[t];if(i.test?(0===t?this.write("if ("):this.write(" else if ("),this.generateExpression(i.test),this.write(`) {
411
+ `)):t>0?this.write(` else {
412
+ `):this.write(`{
413
+ `),this.indent++,i.statements&&i.statements.length>0){let e=i.statements[i.statements.length-1];if("ExpressionStatement"===e.type||"VariableDeclaration"===e.type){for(let e=0;e<i.statements.length-1;e++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(i.statements[e]);this.write(this.indentStr.repeat(this.indent)),this.write("return "),"ExpressionStatement"===e.type?this.generateExpression(e.expression):this.generateExpression(i.consequent),this.write(`;
414
+ `)}else if("IfStatement"===e.type){for(let e=0;e<i.statements.length-1;e++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(i.statements[e]);this.generateIfWithReturns(e),this.write(this.indentStr.repeat(this.indent)),this.write(`return null;
415
+ `)}else{for(let e of i.statements)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(e);this.write(this.indentStr.repeat(this.indent)),this.write(`return null;
416
+ `)}}else this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(i.consequent),this.write(`;
417
+ `);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),t>=e.cases.length-1&&this.write(`
418
+ `)}this.writeNaForMissingDefault(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}writeNaForMissingDefault(e){if(e.cases.some(e=>!e.test))return;let t=e.cases.length>0&&e.cases.every(e=>{let t=(e=>{let t=e.statements?.length?e.statements[e.statements.length-1]:null;return t?"ExpressionStatement"===t.type?t.expression:null:e.consequent})(e);return t?.type==="Literal"&&"string"==typeof t.value});this.write(this.indentStr.repeat(this.indent)),this.write(t?`return "";
419
+ `:`return na;
420
+ `)}generateSwitchAsIfElse(e){for(let t=0;t<e.cases.length;t++){let i=e.cases[t];if(i.test?(0===t?this.write("if ("):this.write(" else if ("),this.generateExpression(i.test),this.write(`) {
421
+ `)):t>0?this.write(` else {
422
+ `):this.write(`{
423
+ `),this.indent++,i.statements&&i.statements.length>0)for(let e of i.statements)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(e);else this.write(this.indentStr.repeat(this.indent)),this.generateExpression(i.consequent),this.write(`;
424
+ `);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),t<e.cases.length-1||this.write(`
425
+ `)}}generateLoopAsExpression(e,t){this.write(`(() => {
426
+ `),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`let __result;
427
+ `);let i=e.body;if(i&&i.body&&i.body.length>0){let e=i.body.length-1,t=i.body[e];"ExpressionStatement"===t.type&&(i.body[e]={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"__result"},right:t.expression},_line:t._line})}"for"===t?this.generateForStatement(e):this.generateWhileStatement(e),this.write(this.indentStr.repeat(this.indent)),this.write(`return __result;
428
+ `),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateSequenceExpression(e){this.write("(");for(let t=0;t<e.expressions.length;t++)this.generateExpression(e.expressions[t]),t<e.expressions.length-1&&this.write(", ");this.write(")")}getPrecedence(e){switch(e.type){case"Literal":case"Identifier":case"ArrayExpression":case"ObjectExpression":return 20;case"CallExpression":case"MemberExpression":return 19;case"UnaryExpression":case"UpdateExpression":return 15;case"BinaryExpression":case"LogicalExpression":switch(e.operator){case"*":case"/":case"%":return 13;case"+":case"-":return 12;case"<":case"<=":case">":case">=":return 10;case"==":case"!=":return 9;case"and":case"&&":return 5;case"or":case"||":return 4;default:return 0}case"ConditionalExpression":return 3;case"AssignmentExpression":case"AssignmentPattern":return 2;case"SequenceExpression":return 1;default:return 0}}}let pV={pi:Math.PI,e:Math.E,phi:1.618033988749895,rphi:.618033988749895},p$=/^#[0-9a-f]{6}([0-9a-f]{2})?$/i,pL=(e,t,i=!0)=>Number.isFinite(e)?{value:e,type:t,exact:i}:void 0,pB=e=>!!e&&("int"===e.type||"float"===e.type)&&"number"==typeof e.value,pF=(...e)=>e.every(e=>"int"===e.type)?"int":"float",pq=(...e)=>e.every(e=>e.exact);function pz(e){return"int"===e.type&&"number"==typeof e.value?Math.trunc(e.value):e.value}function pU(e){if(e?.type==="Identifier")return e.name;if(e?.type==="MemberExpression"&&!e.computed&&e.property?.type==="Identifier"){let t=pU(e.object);return null===t?null:`${t}.${e.property.name}`}return null}function pW(e,t){if(null!=e)switch(e.type){case"Literal":var i=e;let r=i.value;if("boolean"==typeof r)return{value:r,type:"bool",exact:!0};if("string"==typeof r)return p$.test(r)?{value:r,type:"color",exact:!1}:{value:r,type:"string",exact:!0};if("number"==typeof r){let e="string"==typeof i.raw?/[.eE]/.test(i.raw):!Number.isInteger(r);return pL(r,e?"float":"int")}return;case"Identifier":return"na"===e.name?void 0:tH.has(e.name)?{value:e.name,type:"source",exact:!1}:t.lookup(e.name);case"MemberExpression":var n=e,s=t;let a=pU(n);if(null===a)return;if(s.enums.has(a))return{value:s.enums.get(a),type:"enum",exact:!1};let[o,l]=a.split(".");if("math"===o&&l in pV)return pL(pV[l],"float");if("color"===o&&y(a))return{value:a,type:"color",exact:!1};let h=ee[o];if("display"!==o&&h&&"object"==typeof h&&l in h){let e=h[l];if("string"==typeof e)return{value:e,type:"string",exact:!1};if("number"==typeof e)return{value:e,type:Number.isInteger(e)?"int":"float",exact:!1}}return{value:a,type:"other",exact:!1};case"UnaryExpression":var c=e,p=t;let u=pW(c.argument,p);if(u){if("!"===c.operator||"not"===c.operator)return"bool"===u.type?{value:!u.value,type:"bool",exact:u.exact}:void 0;if(pB(u)){if("-"===c.operator)return pL(-u.value,u.type,u.exact);if("+"===c.operator)return u}}return;case"BinaryExpression":case"LogicalExpression":return function(e,t){let i=e.operator;if("&&"===i||"||"===i||"and"===i||"or"===i){let r=pW(e.left,t);if(r?.type!=="bool")return;if("&&"===i||"and"===i?!r.value:r.value)return r;let n=pW(e.right,t);return n?.type==="bool"?{value:n.value,type:"bool",exact:r.exact&&n.exact}:void 0}let r=pW(e.left,t),n=pW(e.right,t);if(!r||!n)return;if("+"===i&&"string"===r.type&&"string"===n.type)return{value:String(r.value)+String(n.value),type:"string",exact:pq(r,n)};if("=="===i||"==="===i||"!="===i||"!=="===i){if(!(pB(r)&&pB(n)||r.type===n.type&&["string","bool"].includes(r.type)))return;let e=pB(r)?1e-10>Math.abs(r.value-n.value):r.value===n.value;return{value:i.startsWith("=")?e:!e,type:"bool",exact:pq(r,n)}}if(!pB(r)||!pB(n))return;let s=r.value,a=n.value,o=pq(r,n);switch(i){case"+":return pL(s+a,pF(r,n),o);case"-":return pL(s-a,pF(r,n),o);case"*":return pL(s*a,pF(r,n),o);case"/":{if(0===a)return;let e=pF(r,n),i=s/a;return pL("int"===e&&t.truncatingIntDivision?Math.trunc(i):i,e,o)}case"%":return 0===a?void 0:pL(s%a,pF(r,n),o);case">":return{value:s>a,type:"bool",exact:o};case"<":return{value:s<a,type:"bool",exact:o};case">=":return{value:s>=a,type:"bool",exact:o};case"<=":return{value:s<=a,type:"bool",exact:o};default:return}}(e,t);case"ConditionalExpression":{let i=pW(e.test,t);return i?.type!=="bool"?void 0:pW(i.value?e.consequent:e.alternate,t)}case"CallExpression":return function(e,t){let i=pU(e.callee);if(null===i)return;let r=e.arguments??[];if(r.some(e=>e?.type==="ObjectExpression"))return;let n=r.map(e=>pW(e,t));if(!n.some(e=>!e)){if("int"===i&&1===n.length&&pB(n[0]))return pL(Math.trunc(n[0].value),"int",n[0].exact);if("float"===i&&1===n.length&&pB(n[0]))return pL(pz(n[0]),"float",n[0].exact);if(i.startsWith("math.")){let e=i.slice(5);if("round"===e){if(!n.every(pB)||n.length<1||n.length>2)return;let e=n[0].value;if(1===n.length)return pL(Math.round(e),"int",n[0].exact);let t=Math.pow(10,n[1].value);return pL(Math.round(e*t)/t,"float",pq(...n))}let t=pK[e];if(!t||n.length<t.arity[0]||n.length>t.arity[1]||!n.every(pB))return;let r="same"===t.type?pF(...n):t.type;return pL(t.fn(...n.map(e=>e.value)),r,pq(...n))}if("str.upper"===i||"str.lower"===i||"str.length"===i){if(1!==n.length||"string"!==n[0].type)return;let e=String(n[0].value);return"str.length"===i?pL(e.length,"int",n[0].exact):{value:"str.upper"===i?e.toUpperCase():e.toLowerCase(),type:"string",exact:n[0].exact}}return"color.new"===i||"color.rgb"===i?function(e,t){let i=e=>Math.max(0,Math.min(1,e));if("color.rgb"===e){let[e,r,n,s]=t.map(e=>e.value);if("number"!=typeof e||"number"!=typeof r||"number"!=typeof n)return;return{value:_(e,r,n,i((100-("number"==typeof s?s:0))/100)),type:"color",exact:!1}}let r=y(t[0]?.value),n=t[1]?.value;if(!(!r||"number"!=typeof n))return{value:_(r[0],r[1],r[2],i((100-n)/100)),type:"color",exact:!1}}(i,n):"timestamp"===i&&1===n.length&&"string"===n[0].type?function(e){let t=e.trim(),i=/[Zz]$/.test(t)||/[+-]\d{2}:?\d{2}$/.test(t),r=i?new Date(t).getTime():new Date(t.includes("T")?t+"Z":t.replace(/\s+/,"T")+"Z").getTime();return!i&&Number.isNaN(r)&&(r=new Date(`${t} UTC`).getTime()),pL(r,"int",i)}(String(n[0].value)):void 0}}(e,t);default:return}}let pK={abs:{arity:[1,1],type:"same",fn:Math.abs},max:{arity:[2,1/0],type:"same",fn:Math.max},min:{arity:[2,1/0],type:"same",fn:Math.min},avg:{arity:[2,1/0],type:"float",fn:(...e)=>e.reduce((e,t)=>e+t,0)/e.length},floor:{arity:[1,1],type:"int",fn:Math.floor},ceil:{arity:[1,1],type:"int",fn:Math.ceil},sqrt:{arity:[1,1],type:"float",fn:Math.sqrt},pow:{arity:[2,2],type:"float",fn:Math.pow},exp:{arity:[1,1],type:"float",fn:Math.exp},log:{arity:[1,1],type:"float",fn:Math.log},log10:{arity:[1,1],type:"float",fn:Math.log10},sign:{arity:[1,1],type:"float",fn:Math.sign},sin:{arity:[1,1],type:"float",fn:Math.sin},cos:{arity:[1,1],type:"float",fn:Math.cos},tan:{arity:[1,1],type:"float",fn:Math.tan},asin:{arity:[1,1],type:"float",fn:Math.asin},acos:{arity:[1,1],type:"float",fn:Math.acos},atan:{arity:[1,1],type:"float",fn:Math.atan},todegrees:{arity:[1,1],type:"float",fn:e=>180*e/Math.PI},toradians:{arity:[1,1],type:"float",fn:e=>e*Math.PI/180}},pG={const:0,input:1,simple:2,series:3},pH=(...e)=>e.reduce((e,t)=>pG[t]>pG[e]?t:e,"const"),pY={},pZ=(e,t,i)=>i.forEach(i=>pY[i]={qual:e,type:t});pZ("series","float",["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","ask","bid"]),pZ("series","int",["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]),pZ("series","bool",["barstate.isfirst","barstate.islast","barstate.ishistory","barstate.isrealtime","barstate.isnew","barstate.isconfirmed","barstate.islastconfirmedhistory"]),pZ("simple","int",["timeframe.multiplier"]),pZ("simple","float",["syminfo.mintick","syminfo.pointvalue"]),pZ("simple","string",["timeframe.period","syminfo.ticker","syminfo.tickerid","syminfo.timezone","syminfo.currency","syminfo.type","syminfo.prefix","syminfo.root","syminfo.description"]),pZ("simple","bool",["timeframe.isintraday","timeframe.isdaily","timeframe.isweekly","timeframe.ismonthly","timeframe.isdwm","timeframe.isminutes","timeframe.isseconds"]);let pJ=new Set(["cross","crossover","crossunder","rising","falling"]),pQ=new Set(["barssince","highestbars","lowestbars"]),pX=new Set(["floor","ceil"]),p0=new Set(["abs","max","min"]),p1=(...e)=>e.every(e=>"int"===e)?"int":"float",p2=e=>"int"===e||"float"===e;function p3(e,t){if(e)switch(e.type){case"Literal":return"boolean"==typeof e.value?{qual:"const",type:"bool"}:"string"==typeof e.value?{qual:"const",type:p$.test(e.value)?"color":"string"}:"number"==typeof e.value?{qual:"const",type:"string"==typeof e.raw&&/[.eE]/.test(e.raw)?"float":"int"}:void 0;case"Identifier":{let i=t.lookup(e.name);return null===i?void 0:i??pY[e.name]}case"MemberExpression":{let t=pU(e);return t?.startsWith("color.")&&y(t)?{qual:"const",type:"color"}:t?pY[t]:void 0}case"UnaryExpression":{let i=p3(e.argument,t);return i?"!"===e.operator?"bool"===i.type?i:void 0:p2(i.type)?i:void 0:void 0}case"BinaryExpression":case"LogicalExpression":{let i=p3(e.left,t),r=p3(e.right,t);if(!i||!r)return;let n=pH(i.qual,r.qual),s=e.operator;return["&&","||",">","<",">=","<=","==","!=","===","!=="].includes(s)?{qual:n,type:"bool"}:"+"===s&&"string"===i.type&&"string"===r.type?{qual:n,type:"string"}:["+","-","*","/","%"].includes(s)&&p2(i.type)&&p2(r.type)?{qual:n,type:p1(i.type,r.type)}:void 0}case"ConditionalExpression":{let i=p3(e.test,t),r=p3(e.consequent,t),n=p3(e.alternate,t);if(!i||!r||!n)return;let s=pH(i.qual,r.qual,n.qual);return r.type===n.type?{qual:s,type:r.type}:p2(r.type)&&p2(n.type)?{qual:s,type:"float"}:void 0}case"CallExpression":return function(e,t){let i=pU(e.callee);if(!i)return;let r=(e.arguments??[]).filter(e=>e?.type!=="ObjectExpression");if(i.startsWith("ta.")){let e=i.slice(3);return{qual:"series",type:pJ.has(e)?"bool":pQ.has(e)?"int":"float"}}let n=r.map(e=>p3(e,t));if(n.some(e=>!e))return;let s=pH(...n.map(e=>e.qual));if("timestamp"===i)return 1===n.length&&"string"===n[0].type?{qual:s,type:"int"}:n.length>=3?{qual:pH("simple",s),type:"int"}:void 0;if("color.new"===i||"color.rgb"===i)return{qual:s,type:"color"};if("int"===i&&1===n.length&&p2(n[0].type))return{qual:s,type:"int"};if("float"===i&&1===n.length&&p2(n[0].type))return{qual:s,type:"float"};if("str.tostring"===i||"str.format"===i)return{qual:pH("simple",s),type:"string"};if(i.startsWith("math.")&&n.length&&n.every(e=>p2(e.type))){let e=i.slice(5);return"round"===e?{qual:s,type:1===n.length?"int":"float"}:pX.has(e)?{qual:s,type:"int"}:p0.has(e)?{qual:s,type:p1(...n.map(e=>e.type))}:{qual:s,type:"float"}}}(e,t);default:return}}let p4={"&&":"and","||":"or","!":"not","===":"==","!==":"!="};function p6(e,t){let i=`(${t.qual} ${t.type})`;switch(e?.type){case"Identifier":case"MemberExpression":return pU(e)??"";case"CallExpression":return`call "${pU(e.callee)}" ${i}`;case"ConditionalExpression":return`call "operator ?:" ${i}`;case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":return`call "operator ${p4[e.operator]??e.operator}" ${i}`;default:return""}}function p5(e){switch(e?.type){case"Identifier":case"Literal":case"UnaryExpression":case"ArrayExpression":return e._pos;case"MemberExpression":return p5(e.object);case"CallExpression":return p5(e.callee);case"BinaryExpression":case"LogicalExpression":return p5(e.left);case"ConditionalExpression":return p5(e.test);default:return}}var p9=Object.defineProperty,p8=(e,t,i)=>((e,t,i)=>t in e?p9(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let p7=new Set(["bool","color","enum","float","int","price","session","source","string","symbol","text_area","time","timeframe"]),ue={"":["defval","title","tooltip","inline","group","display","active"],bool:["defval","title","tooltip","inline","group","confirm","display","active"],color:["defval","title","tooltip","inline","group","confirm","display","active"],enum:["defval","title","options","tooltip","inline","group","confirm","display","active"],price:["defval","title","tooltip","inline","group","confirm","display","active"],session:["defval","title","options","tooltip","inline","group","confirm","display","active"],source:["defval","title","tooltip","inline","group","display","active","confirm"],string:["defval","title","options","tooltip","inline","group","confirm","display","active"],symbol:["defval","title","tooltip","inline","group","confirm","display","active"],text_area:["defval","title","tooltip","group","confirm","display","active"],time:["defval","title","tooltip","inline","group","confirm","display","active"],timeframe:["defval","title","options","tooltip","inline","group","confirm","display","active"]},ut=["defval","title","inline","group","tooltip","display","active"],ui=["defval","title","options","tooltip","inline","group","confirm","display","active"],ur=["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display","active"],un={"":"bool",int:"int",float:"float",bool:"bool",string:"string",text_area:"string",session:"string",symbol:"string",timeframe:"string",time:"int",price:"float",color:"color"};class us{constructor(e){this.parent=e,p8(this,"vars",new Map)}resolve(e){for(let t=this;t;t=t.parent){let i=t.vars.get(e);if(i)return i}}}function ua(e){if(e?.type!=="CallExpression")return null;let t=pU(e.callee);return"input"===t?"":t?.startsWith("input.")&&p7.has(t.slice(6))?t.slice(6):null}class uo{constructor(e,t){this.ast=e,p8(this,"sites",[]),p8(this,"enums",new Map),p8(this,"reassigned",new Set),p8(this,"visited",new WeakSet),p8(this,"inputDefaults",new WeakMap),p8(this,"functionNames",new Set),p8(this,"truncatingIntDivision"),this.truncatingIntDivision=null!=t.version&&t.version<6}run(){this.collectEnumsAndReassignments(this.ast);let e=new us(null);return this.visitStatements(this.ast.body??[],{scope:e,target:null,fnName:null}),this.sites}collectEnumsAndReassignments(e){ud(e,e=>{if("FunctionDeclaration"===e.type&&e.id?.name&&this.functionNames.add(e.id.name),"AssignmentExpression"===e.type&&e.left?.type==="Identifier"&&this.reassigned.add(e.left.name),"VariableDeclaration"===e.type)for(let t of e.declarations??[]){let e=t?.init;if(!(t?.id?.type!=="Identifier"||e?.type!=="ObjectExpression"||!e.properties?.length||!e.properties.every(e=>e.value?.type==="Literal"&&"string"==typeof e.value.value)))for(let i of e.properties)this.enums.set(`${t.id.name}.${i.key.name}`,i.value.value)}})}pineName(e){return e.endsWith("_var")&&this.functionNames.has(e.slice(0,-4))?e.slice(0,-4):e}env(e,t=!1){return{enums:this.enums,truncatingIntDivision:this.truncatingIntDivision,lookup:i=>{let r=e.resolve(i);return t&&r?.kind==="value"&&!r.nonConst&&r.inputDefault?r.inputDefault:!r||"value"!==r.kind||r.nonConst||r.busy?void 0:(void 0===r.cache&&(r.busy=!0,r.cache=pW(r.init,this.env(r.scope))??null,r.busy=!1),r.cache??void 0)}}}fold(e,t){return pW(e,this.env(t))}foldCondition(e,t){let i=this.fold(e,t);return i?.type==="bool"?i.value:void 0}declareValue(e,t,i,r){let n=this.reassigned.has(t)||/\b(series|simple)\b/.test(r??"");e.vars.set(t,{kind:"value",name:t,init:i,scope:e,nonConst:n,inputDerived:up(i)})}declarePattern(e,t,i){if(t?.type==="Identifier")e.vars.set(t.name,{kind:i,name:t.name});else if(t?.type==="ArrayPattern")for(let r of t.elements??[])this.declarePattern(e,r,i);else t?.type==="AssignmentPattern"&&this.declarePattern(e,t.left,i)}visitStatements(e,t){for(let i of e)this.visit(i,t)}visit(e,t){if(!(!e||"object"!=typeof e)){if(Array.isArray(e)){for(let i of e)this.visit(i,t);return}if(!("string"!=typeof e.type||this.visited.has(e)))switch(this.visited.add(e),e.type){case"VariableDeclaration":for(let i of e.declarations??[]){let e=i.id?.type==="Identifier"?i.id.name:null;if(this.visit(i.init,{...t,target:e?this.pineName(e):t.target}),e){this.declareValue(t.scope,e,i.init,i.varType??i.id?.varType??null);let r=t.scope.vars.get(e),n=this.inputDefaults.get(i.init);r?.kind==="value"&&n&&(r.inputDefault=n)}}return;case"AssignmentExpression":{let i=e.left?.type==="Identifier"?e.left.name:null;if(this.visit(e.right,{...t,target:i?this.pineName(i):t.target}),i&&up(e.right)){let e=t.scope.resolve(i);e?.kind==="value"&&(e.inputDerived=!0)}return}case"BlockStatement":this.visitStatements(e.body??[],e._sequence?t:{...t,scope:new us(t.scope)});return;case"IfStatement":{this.visit(e.test,t);let i=this.foldCondition(e.test,t.scope);!1!==i&&this.visitBranch(e.consequent,t),!0!==i&&e.alternate&&this.visitBranch(e.alternate,t);return}case"ConditionalExpression":{this.visit(e.test,t);let i=this.foldCondition(e.test,t.scope);!1!==i&&this.visit(e.consequent,t),!0!==i&&this.visit(e.alternate,t);return}case"BinaryExpression":case"LogicalExpression":{this.visit(e.left,t);let i=e.operator;if(("&&"===i||"||"===i)&&this.foldCondition(e.left,t.scope)===("||"===i))return;this.visit(e.right,t);return}case"SwitchExpression":this.visitSwitch(e,t);return;case"ForStatement":{let i=new us(t.scope),r=e.init;if(r?.type==="VariableDeclaration")for(let e of r.declarations??[])this.visit(e.init,t),this.declarePattern(i,e.id,"loop");else this.visit(r,t);let n={...t,scope:i};this.visit(e.test,n),this.visit(e.update,n),this.visitBranch(e.body,n);return}case"FunctionDeclaration":{let i=new us(t.scope);for(let t of e.params??[])this.declarePattern(i,t,"param");let r={scope:i,target:null,fnName:e.id?.name??null};this.visit(e.params,r),this.visitBranch(e.body,r);return}case"CallExpression":{let i=ua(e);if(null!==i)return void this.recordInput(e,i,t);this.visit(e.callee,t),this.visit(e.arguments,t);return}default:this.visitChildren(e,t)}}}visitBranch(e,t){e?.type==="BlockStatement"?this.visit(e,t):this.visit(e,{...t,scope:new us(t.scope)})}visitSwitch(e,t){this.visit(e.discriminant,t);let i=e.discriminant?this.fold(e.discriminant,t.scope):void 0,r=!1;for(let n of e.cases??[]){let s=!r;if(s&&n.test)if(this.visit(n.test,t),e.discriminant){let e=i?this.fold(n.test,t.scope):void 0;i&&e&&e.type===i.type&&(e.value===i.value?r=!0:s=!1)}else{let e=this.foldCondition(n.test,t.scope);!0===e?r=!0:!1===e&&(s=!1)}else s&&!n.test&&(r=!0);if(!s)continue;let a={...t,scope:new us(t.scope)};n.statements?.length?this.visitStatements(n.statements,a):this.visit(n.consequent,a)}}visitChildren(e,t){for(let i of Object.keys(e)){if("args"===i||"type"===i||i.startsWith("_"))continue;let r=e[i];r&&"object"==typeof r&&this.visit(r,t)}}recordInput(e,t,i){let r,n=e.arguments??[],s=n[n.length-1],a=s?.type==="ObjectExpression",o=a?s.properties??[]:[],l=a?n.slice(0,-1):n.slice(),h=""===t?"input":`input.${t}`,c={},p=l[0]??o.find(e=>e.key?.name==="defval")?.value,u="int"===t||"float"===t?o.some(e=>e.key?.name==="options")||l[2]?.type==="ArrayExpression"?ui:ur:""===t&&ul(p,i.scope)?ut:ue[t];l.forEach((e,t)=>{t<u.length&&(c[u[t]]={node:e,holder:n,key:String(t)})});let d=new Set("int"===t||"float"===t?[...ui,...ur]:ue[t]);for(let e of o)if(!("Property"!==e.type||!e.key?.name)){if(!d.has(e.key.name))throw Error(`The "${h}" function does not have an argument with the name "${e.key.name}"${e.key._pos?` at ${e.key._pos}`:""}`);c[e.key.name]={node:e.value,holder:e,key:"value"}}this.validateArguments(e,i.scope,c.active?.node),this.checkArgumentTypes(e,t,c,i.scope);let m={};for(let[t,{node:n}]of Object.entries(c)){let s=n?.type==="ArrayExpression"?void 0:"active"===t?pW(n,this.env(i.scope,!0)):this.fold(n,i.scope);"defval"===t&&(r=s?.type,s&&this.inputDefaults.set(e,s)),m[t]=s?pz(s):function(e,t){if(e?.type==="ArrayExpression")return(e.elements??[]).map(e=>{let i=t(e);return i?pz(i):void 0})}(n,e=>this.fold(e,i.scope))}if(this.checkDefvalConstraints(e,t,c,m,i.scope),"enum"===t&&void 0===m.options){let e=this.enumField(c.defval?.node,i.scope),t=e?.slice(0,e.lastIndexOf(".")+1);t&&(m.options=[...this.enums].filter(([e])=>e.startsWith(t)&&!e.slice(t.length).includes(".")).map(([,e])=>e))}this.inlineDefval(c.defval,i.scope);let f=`in_${this.sites.length}`,y="string"==typeof m.title?m.title:void 0,_=i.target??void 0,g={id:f,fn:t,name:y??i.target??i.fnName??"untitled",args:m};void 0!==_&&(g.varId=_),void 0!==r&&(g.defvalType=r),this.sites.push(g);let x=[new pg(new po("__inputId"),new pl(f))];void 0!==_&&x.push(new pg(new po("__varId"),new pl(_))),n.push(new p_(x))}inlineDefval(e,t){if(!e||!e.node||"Literal"===e.node.type)return;let i=this.fold(e.node,t);if(!i||!i.exact||!["int","float","bool","string"].includes(i.type))return;let r=pz(i),n="float"===i.type&&"number"==typeof r&&Number.isInteger(r)?`${r}.0`:"number"==typeof r?String(r):null;e.holder[e.key]=new pl(r,n)}qualifierEnv(e,t=new Set){return{lookup:i=>{let r=e.resolve(i);if(!r)return;if("value"!==r.kind||r.nonConst||r.inputDerived||t.has(r))return null;let n=this.fold({type:"Identifier",name:i},e);if(n&&["int","float","bool","string"].includes(n.type))return{qual:"const",type:n.type};t.add(r);let s=p3(r.init,this.qualifierEnv(r.scope,t));return t.delete(r),s??null}}}checkArgumentTypes(e,t,i,r){let n=this.qualifierEnv(r),s=""===t?"input":`input.${t}`,a=uu(e.callee),o=e=>e?` at ${e}`:"";for(let[e,{node:l}]of Object.entries(i)){if(!l)continue;if("source"===t&&"defval"===e){if(ul(l,r))continue;throw Error(`Invalid value for the "defval" parameter of the "input.source" function. Possible values: [open, high, low, close, hl2, hlc3, ohlc4, hlcc4].${o(a)}`)}if("enum"===t)continue;if("defval"===e&&"Identifier"===l.type&&"na"===l.name&&!r.resolve("na"))throw""===t?Error(`Arguments of input function must be of constant type, or "source" builtin variables.${o(a)}`):"bool"===t?Error(`Cannot call "input.bool" with argument "defval"="na". An argument of "simple na" type was used but a "const bool" is expected.${o(p5(l))}`):Error(`The "defval" parameter of the "${s}()" function cannot accept a "na" argument.${o(p5(l))}`);if("options"===e&&"ArrayExpression"===l.type){this.checkOptionTypes(s,t,l,n);continue}let i="defval"===e?un[t]:"title"===e||"tooltip"===e||"group"===e||"inline"===e?"string":"minval"===e||"maxval"===e||"step"===e?"int"===t?"int":"float":"confirm"===e?"bool":void 0;if(!i)continue;let h=p3(l,n);if(!h)continue;let c="simple"===h.qual||"series"===h.qual;if(""===t&&"defval"===e){if(!c)continue;if("bool"!==h.type&&"string"!==h.type){if(ul(l,r)||"ConditionalExpression"===l.type)continue;throw Error(`Arguments of input function must be of constant type, or "source" builtin variables.${o(a)}`)}}else if(!c&&uh(h.type,i))continue;let p="Literal"===l.type,u=p?uc(l):p6(l,h);throw Error(`Cannot call "${s}" with argument "${e}"="${u}". An argument of "${p?"literal":h.qual} ${h.type}" type was used but a "const ${i}" is expected.${o(p5(l))}`)}}checkOptionTypes(e,t,i,r){let n="int"===t?"int":"float"===t?"float":["string","session","timeframe"].includes(t)?"string":void 0;if(!n)return;let s=i.elements??[],a=s.map(e=>p3(e,r));if(a.some(e=>!e)||a.every(e=>"simple"!==e.qual&&"series"!==e.qual&&uh(e.type,n)))return;let o=s.map((e,t)=>"Literal"===e.type?uc(e):p6(e,a[t])).join(","),l=s.map((e,t)=>`${"Literal"===e.type?"literal":a[t].qual} ${a[t].type}`).join(", "),h=p5(i);throw Error(`Cannot call "${e}" with argument "options"="${o}". An argument of "[${l}]" type was used but a "[const ${n}...]" is expected.${h?` at ${h}`:""}`)}enumField(e,t){if(e?.type==="ConditionalExpression"){let i=this.foldCondition(e.test,t);return void 0===i?null:this.enumField(i?e.consequent:e.alternate,t)}return pU(e)}checkDefvalConstraints(e,t,i,r,n){let s=i.defval?.node,a=e=>e?` at ${e}`:"";if("enum"===t){let t=[s,...i.options?.node?.type==="ArrayExpression"?i.options.node.elements:[]].map(e=>this.enumField(e,n));if(t.some(e=>!e||!this.enums.has(e)))return;if(new Set(t.map(e=>e.slice(0,e.lastIndexOf(".")))).size>1)throw Error(`All values passed to "input.enum()" as its "defval" or "options" must be fields of the same enum.${a(uu(e.callee))}`);if(i.options){let[e,...i]=t;if(!i.includes(e))throw Error(`input's defval should be in options, but '${e}' is not in [${i.join(", ")}]${a(p5(s))}`)}return}let o=r.defval;if("number"==typeof o&&("int"===t||"float"===t)){let{minval:e,maxval:t}=r;if("number"==typeof e&&o<e||"number"==typeof t&&o>t)throw Error(`Input's "defval" value must be between "minval" and "maxval"${a(p5(s))}`)}let l=r.options;if(Array.isArray(l)&&i.options?.node?.type==="ArrayExpression"&&("number"==typeof o||"string"==typeof o)&&!l.some(e=>"number"==typeof e&&"number"==typeof o?1e-10>Math.abs(e-o):e===o)&&l.every(e=>typeof e==typeof o)){let e="string"==typeof o?`'${o}'`:String(o);throw Error(`input's defval should be in options, but ${e} is not in [${l.map(String).join(", ")}]${a(p5(s))}`)}}validateArguments(e,t,i){let r=new Set;i&&ud(i,e=>r.add(e)),ud({type:"Args",list:e.arguments??[]},(i,n,s)=>{if("Identifier"!==i.type||n?.type==="Property"&&"key"===s||n?.type==="MemberExpression"&&"property"===s&&!n.computed)return;let a=t.resolve(i.name);if(a){if("loop"===a.kind||"param"===a.kind)throw Error(`Undeclared identifier "${i.name}"${i._pos?` at ${i._pos}`:""}`);if("value"===a.kind&&a.inputDerived&&!r.has(i)){let t=uu(e.callee);throw Error(`Arguments of input function must be of constant type, or "source" builtin variables.${t?` at ${t}`:""}`)}}})}}function ul(e,t){return e?.type==="Identifier"&&tH.has(e.name)&&!t.resolve(e.name)}function uh(e,t){return e===t||"float"===t&&"int"===e}function uc(e){return String(e.value)}function up(e){let t=!1;return ud(e,e=>{t||null===ua(e)||(t=!0)}),t}function uu(e){let t=e;for(;t?.type==="MemberExpression";)t=t.object;return t?._pos}function ud(e,t){let i=new WeakSet,r=(e,n,s)=>{if(!(!e||"object"!=typeof e)){if(Array.isArray(e)){for(let t of e)r(t,n,s);return}if(!i.has(e))for(let a of(i.add(e),"string"==typeof e.type&&t(e,n,s),Object.keys(e))){if("args"===a||a.startsWith("_"))continue;let t=e[a];t&&"object"==typeof t&&r(t,e,a)}}};r(e,null,"")}function um(e){let t=e.match(/^\s*\/\/\s*@version\s*=\s*(\d+)\s*$/im);return t&&t[1]?parseInt(t[1],10):null}var uf=Object.defineProperty,uy=(e,t,i)=>((e,t,i)=>t in e?uf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let u_=new Set(oW),ug=/[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?/g;class ux{constructor(e,t){this.spec=e,this.prefix=t,uy(this,"decls",[]),uy(this,"byKey",new Map),uy(this,"exported",new Set),uy(this,"functions",new Map),uy(this,"types",new Map),uy(this,"enums",new Map),uy(this,"globals",new Map),uy(this,"methodRenames",new Map),uy(this,"methods",new Set),uy(this,"imports",new Map)}addDecl(e,t){let i={node:e,keys:t,edges:[]};for(let r of(this.decls.push(i),t)){let t=this.byKey.get(r)??[];t.push(i),this.byKey.set(r,t),e.exported&&this.exported.add(r)}}}class ub{constructor(e,t,i){this.mod=e,this.imports=t,this.refs=i,uy(this,"shadow",new Set),uy(this,"seen",new WeakSet)}}let uv=e=>!!e&&"missing"in e;class uw{constructor(e){this.libraries=e,uy(this,"modules",new Map),uy(this,"loading",[]),uy(this,"prefixes",new Set)}link(e,t){let i=this.loadImports(t,null),r=e.body.findIndex(e=>"ImportDeclaration"===e.type);e.body=e.body.filter(e=>"ImportDeclaration"!==e.type);let n=[],s=new ub(null,i,n);for(let t of e.body)this.visit(t,s);return e.body.splice(r,0,...this.emit(i,this.reach(n))),{imports:t,unresolved:t.filter(e=>uv(i.get(e.alias)))}}loadImports(e,t){let i=new Map;for(let r of e){if(i.has(r.alias))throw Error(`Duplicate import alias "${r.alias}"${t?` in library "${t.spec.path}"`:""}`);i.set(r.alias,this.load(r)??{missing:r})}return i}load(e){let t=this.modules.get(e.path);if(t)return t;let i=this.libraries[e.path];if("string"!=typeof i)return null;if(this.loading.includes(e.path))throw Error(`Circular library import: ${[...this.loading,e.path].join(" -> ")}`);this.loading.push(e.path);try{let t=this.parseLibrary(e,i);return this.modules.set(e.path,t),t}finally{this.loading.pop()}}parseLibrary(e,t){let i,r=um(t);if(null===r||r<5)throw Error(`Library "${e.path}": ${null===r?"missing //@version annotation":`Pine Script version ${r} is not supported`}`);try{i=new pI(new c0(t).tokenize()).parse()}catch(t){throw Error(`Failed to parse library "${e.path}": ${t.message}`)}let n=function e(t){return t.flatMap(t=>t?.type==="BlockStatement"&&t._sequence?e(t.body):[t])}(i.body);if(!n.some(uS))throw Error(`"${e.path}" is not a library: its source has no library() declaration`);let s=new ux(e,this.prefixFor(e));for(let e of(s.imports=this.loadImports(n.filter(e=>"ImportDeclaration"===e.type),s),n))if("FunctionDeclaration"===e.type){let t=e.id.name;e.id.isMethod?s.methods.add(t):s.functions.set(t,s.prefix+t),s.addDecl(e,[(e.id.isMethod?"m:":"f:")+t])}else if("TypeDefinition"===e.type)s.types.set(e.name,s.prefix+e.name),s.addDecl(e,["t:"+e.name]);else if("VariableDeclaration"===e.type&&e._enum){let t=e.declarations[0].id.name;s.enums.set(t,s.prefix+t),s.addDecl(e,["e:"+t])}else if("VariableDeclaration"===e.type){let t=e.declarations.flatMap(e=>uE(e.id).map(e=>e.name));for(let e of t)s.globals.set(e,s.prefix+e);s.addDecl(e,t.map(e=>"g:"+e))}for(let e of s.methods)s.exported.has("m:"+e)||oF.has(e)||s.methodRenames.set(e,s.prefix+e);for(let e of s.decls)this.rewriteDeclaration(s,e);return s}prefixFor(e){let t=e=>e.replace(/[^A-Za-z0-9_]/g,"_"),i=`${t(e.user)}$${t(e.name)}$${e.version}$`;/^\d/.test(i)&&(i="_"+i);let r=i;for(let e=2;this.prefixes.has(r);e++)r=`${i}${e}$`;return this.prefixes.add(r),r}rewriteDeclaration(e,t){let i=new ub(e,e.imports,t.edges),r=t.node;if(delete r._line,"FunctionDeclaration"===r.type){let t=r.id.name;for(let n of(r.id.name=r.id.isMethod?e.methodRenames.get(t)??t:e.functions.get(t),i.shadow=function(e){let t=new Set;for(let i of e.params){let e="AssignmentPattern"===i.type?i.left:i;e?.name&&t.add(e.name)}let i=new WeakSet,r=e=>{if(!(!e||"object"!=typeof e||i.has(e))){if(i.add(e),Array.isArray(e))return e.forEach(r);if("VariableDeclarator"===e.type)for(let i of uE(e.id))t.add(i.name);for(let t of Object.keys(e))"type"!==t&&r(e[t])}};return r(e.body),t}(r),this.renameTypes(r,i),this.renameTypes(r.id,i),r.params))this.renameTypes("AssignmentPattern"===n.type?n.left:n,i),"AssignmentPattern"===n.type&&this.visit(n.right,i);this.visit(r.body,i)}else if("TypeDefinition"===r.type)r.name=e.types.get(r.name),this.visit(r,i);else if(r._enum){let t=r.declarations[0].id;t.name=e.enums.get(t.name)}else{for(let t of r.declarations)for(let i of uE(t.id))i.name=e.globals.get(i.name)??i.name;this.visit(r.declarations,i)}}visit(e,t){if(!(!e||"object"!=typeof e)){if(Array.isArray(e)){for(let i of e)this.visit(i,t);return}if(!("string"!=typeof e.type||t.seen.has(e))){switch(t.seen.add(e),t.mod&&delete e._line,this.renameTypes(e,t),e.type){case"CallExpression":return this.visitCall(e,t);case"MemberExpression":return this.visitMember(e,t);case"Identifier":return this.visitReference(e,t);case"Property":return this.visit(e.value,t);case"VariableDeclarator":for(let i of uE(e.id))this.renameTypes(i,t);return this.visit(e.init,t);case"TypeDefinition":for(let i of e.fields)i.type=this.renameTypeString(i.type,t),this.visit(i.defaultValue,t);return}for(let i of Object.keys(e))"type"!==i&&this.visit(e[i],t)}}}visitReference(e,t){if(!t.mod||t.shadow.has(e.name))return;let i=t.mod.globals.get(e.name);i&&(t.refs.push({mod:t.mod,key:"g:"+e.name}),e.name=i)}visitMember(e,t){let i=e.object;if(e.computed||i?.type!=="MemberExpression"||i.computed||i.object?.type!=="Identifier"){if(!e.computed&&i?.type==="Identifier"&&t.mod&&!t.shadow.has(i.name)){let e=t.mod.types.get(i.name),r=t.mod.enums.get(i.name);e&&t.refs.push({mod:t.mod,key:"t:"+i.name}),r&&t.refs.push({mod:t.mod,key:"e:"+i.name}),(e||r)&&(i.name=e||r)}}else{let e=this.aliasType(i.object.name,i.property?.name,t);e&&function(e,t){for(let t of Object.keys(e))delete e[t];e.type="Identifier",e.name=t}(i,e)}this.visit(i,t),e.computed&&this.visit(e.property,t)}visitCall(e,t){let i=e.callee;if(i?.type==="Identifier")t.mod&&this.linkCallee(i,t);else if(i?.type!=="MemberExpression"||i.computed||i.property?.type!=="Identifier")this.visit(i,t);else{let r=i.object;r?.type==="Identifier"&&t.imports.has(r.name)&&this.linkAliasCall(e,r.name,i.property.name,t)?"MemberExpression"===e.callee.type&&this.visit(e.callee.object,t):(this.linkMethodCall(i,t),this.visit(i,t))}this.visit(e.arguments,t)}linkCallee(e,t){let i=t.mod,r=e.name,n=i.functions.get(r);if(n){t.refs.push({mod:i,key:"f:"+r}),e.name=n;return}if(i.methods.has(r)){t.refs.push({mod:i,key:"m:"+r}),e.name=i.methodRenames.get(r)??r;return}let s=!t.shadow.has(r)&&i.types.get(r);s&&(t.refs.push({mod:i,key:"t:"+r}),e.name=s)}linkAliasCall(e,t,i,r){let n=r.imports.get(t);if(uv(n))return this.missingRef(n,`${t}.${i}()`,r),!1;if(n.exported.has("f:"+i))return r.refs.push({mod:n,key:"f:"+i}),e.callee=new po(n.functions.get(i)),!0;if(n.exported.has("m:"+i)){r.refs.push({mod:n,key:"m:"+i});let[t,...s]=e.arguments;return t&&"ObjectExpression"!==t.type?(e.callee=new pm(t,new po(i),!1),e.arguments=s):e.callee=new po(i),!0}if(u_.has(t))return!1;throw Error(`Could not find function or function reference "${t}.${i}": library "${n.spec.path}" does not export it`)}linkMethodCall(e,t){let i=e.object;if(i?.type==="Identifier"&&!t.shadow.has(i.name)&&(u_.has(i.name)||t.imports.has(i.name)))return;let r=e.property.name;if(t.mod?.methods.has(r)){t.refs.push({mod:t.mod,key:"m:"+r});let i=t.mod.methodRenames.get(r);i&&(e.property.name=i)}for(let e of t.imports.values())!uv(e)&&e.exported.has("m:"+r)&&t.refs.push({mod:e,key:"m:"+r})}aliasType(e,t,i){let r=i.imports.get(e);if(!(!r||!t)){if(uv(r))return void this.missingRef(r,`${e}.${t}`,i);if(r.exported.has("t:"+t))return i.refs.push({mod:r,key:"t:"+t}),r.types.get(t);if(r.exported.has("e:"+t))return i.refs.push({mod:r,key:"e:"+t}),r.enums.get(t)}}missingRef(e,t,i){i.mod&&i.refs.push({missing:e.missing,via:t,from:i.mod.spec.path})}renameTypes(e,t){"string"==typeof e.varType&&(e.varType=this.renameTypeString(e.varType,t)),"string"==typeof e.returnType&&(e.returnType=this.renameTypeString(e.returnType,t))}renameTypeString(e,t){return"string"!=typeof e?e:e.replace(ug,e=>{let i=e.indexOf(".");if(i>0)return this.aliasType(e.slice(0,i),e.slice(i+1),t)??e;let r=t.mod;if(!r)return e;let n=r.types.get(e);if(n)return t.refs.push({mod:r,key:"t:"+e}),n;let s=r.enums.get(e);return s?(t.refs.push({mod:r,key:"e:"+e}),s):e})}reach(e){let t=new Set,i=[...e];for(;i.length>0;){let e=i.pop();if("missing"in e)throw Error(`Library "${e.from}" uses ${e.via} from "${e.missing.path}", which could not be resolved`);for(let r of e.mod.byKey.get(e.key)??[])t.has(r)||(t.add(r),i.push(...r.edges))}return t}emit(e,t){let i=[],r=new Set,n=e=>{if(!(uv(e)||r.has(e))){for(let t of(r.add(e),e.imports.values()))n(t);i.push(e)}};for(let t of e.values())n(t);return i.flatMap(e=>e.decls.filter(e=>t.has(e)).map(e=>e.node))}}function uS(e){let t=e?.type==="ExpressionStatement"?e.expression:null;return t?.type==="CallExpression"&&t.callee?.type==="Identifier"&&"library"===t.callee.name}function uE(e){return e?.type==="Identifier"?[e]:e?.type==="ArrayPattern"?e.elements.filter(e=>e?.type==="Identifier"):[]}function uN(e,t={}){let i=um(e);if(null===i)return{success:!1,version:null,error:"Pine Script version not found. Please add //@version=X comment to your script."};if(i<5)return{success:!1,version:i,error:`Pine Script version ${i} is not supported. Only version 5 and above are supported.`};try{let r=new c0(e).tokenize(),n=new pI(r).parse(),{libraries:s,...a}=t,o=function(e,t){let i=e.body.filter(e=>"ImportDeclaration"===e.type).map(e=>({path:e.path,user:e.user,name:e.name,version:e.version,alias:e.alias}));return 0===i.length?{imports:i,unresolved:[]}:t?new uw(t).link(e,i):{imports:i,unresolved:i}}(n,s),l=function(e,t={}){return new uo(e,t).run()}(n,{version:i}),h={...a,sourceCode:e},c=new pj(h).generate(n);return{success:!0,version:i,code:c,ast:n,tokens:r,inputs:l,imports:o.imports,unresolvedImports:o.unresolved}}catch(e){return{success:!1,version:i,error:e.message,stack:e.stack}}}let uT=new Set(["security_lower_tf","security"]),uk=new Set(["type","loc","start","end","range","parent","leadingComments","trailingComments"]);function uA(e){return!!e&&("FunctionExpression"===e.type||"ArrowFunctionExpression"===e.type||"FunctionDeclaration"===e.type)}function uI(e,t,i){if(i>=t.length-1)return e;let r=t[i+1];switch(e.type){case"BlockStatement":{let n=e.body.indexOf(r);if(n<0)return e;let s=e.body.slice(0,n);return s.push(uI(r,t,i+1)),{...e,body:s}}case"IfStatement":return r===e.test?{...e,test:uI(r,t,i+1),consequent:{type:"BlockStatement",body:[]},alternate:null}:r===e.consequent?{...e,consequent:uI(r,t,i+1),alternate:null}:r===e.alternate?{...e,alternate:uI(r,t,i+1)}:e;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"ForInStatement":case"ForOfStatement":case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return r===e.body?{...e,body:uI(r,t,i+1)}:e;case"SwitchStatement":{let n=e.cases.indexOf(r);if(n>=0){let s=e.cases.slice(0,n);return s.push(uI(r,t,i+1)),{...e,cases:s}}return e}case"SwitchCase":{let n=e.consequent.indexOf(r);if(n>=0){let s=e.consequent.slice(0,n);return s.push(uI(r,t,i+1)),{...e,consequent:s}}return e}default:return e}}let uC=new Set(["undefined","NaN","Infinity"]),uM=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","context","pineTS","marketData","provider","_context"]),uP=new Set(["type","parent","loc","start","end","range","leadingComments","trailingComments"]);class uD extends Error{constructor(e){super(e),this.name="ClosedWorldViolation"}}function uR(e,t){if(!(!e||"object"!=typeof e))switch(e.type){case"Identifier":t.add(e.name);return;case"ObjectPattern":for(let i of e.properties||[])"RestElement"===i.type?uR(i.argument,t):uR(i.value,t);return;case"ArrayPattern":for(let i of e.elements||[])uR(i,t);return;case"AssignmentPattern":uR(e.left,t);return;case"RestElement":uR(e.argument,t);return;default:return}}function uO(e){if("string"==typeof e&&uM.has(e))throw new uD(`Access to reserved property "${e}" is not allowed`)}let uj={bool:"bool",color:"color",enum:"enum",float:"float",int:"int",price:"price",session:"session",source:"source",string:"string",symbol:"symbol",text_area:"text_area",time:"time",timeframe:"timeframe"},uV=new Set(["bool","color","time","text_area"]),u$=["open","high","low","close","hl2","hlc3","hlcc4","ohlc4"];function uL(e,t,i,r,n="key"){let s={},a=new Map;for(let t of e)a.set(t.key,t),s[t.key]=r&&t.key in r?r[t.key]:t.defval;for(let t of e)for(let e of t.aliases??[])!e||a.has(e)||a.set(e,t);return{proxy:new Proxy(s,{get(e,t){if("symbol"==typeof t)return e[t];let i=a.get(t);return i?e[i.key]:e[t]},set(e,r,s){if("string"!=typeof r)return!1;let o=a.get(r);if(!o)throw Error(`[${t}] unknown ${n} "${r}". Known: ${[...a.keys()].join(", ")||"(none)"}`);return function(e,t,i){let r=e.key;switch(e.type){case"int":if("number"!=typeof t||!Number.isInteger(t))throw TypeError(`[${i}] "${r}" expects an int; got ${uB(t)}`);break;case"float":case"price":case"time":if("number"!=typeof t||!Number.isFinite(t))throw TypeError(`[${i}] "${r}" expects a number; got ${uB(t)}`);break;case"bool":if("boolean"!=typeof t)throw TypeError(`[${i}] "${r}" expects a boolean; got ${uB(t)}`);break;case"string":case"session":case"symbol":case"timeframe":case"text_area":case"color":case"enum":case"source":if("string"!=typeof t)throw TypeError(`[${i}] "${r}" expects a string; got ${uB(t)}`)}if(e.options&&!e.options.some(e=>{var i,r;return(i=e)===(r=t)||"number"==typeof i&&"number"==typeof r&&1e-12>Math.abs(i-r)}))throw RangeError(`[${i}] "${r}" value ${uB(t)} is not one of: ${e.options.map(uB).join(", ")}`);if("number"==typeof t){if("number"==typeof e.minval&&t<e.minval)throw RangeError(`[${i}] "${r}" value ${t} is below minval ${e.minval}`);if("number"==typeof e.maxval&&t>e.maxval)throw RangeError(`[${i}] "${r}" value ${t} is above maxval ${e.maxval}`)}}(o,s,t),e[o.key]=s,i?.(o.key),!0},deleteProperty(e,i){throw Error(`[${t}] cannot delete "${String(i)}" \u2014 keys are fixed by the script's source.`)},defineProperty(){throw Error(`[${t}] cannot define new properties \u2014 keys are fixed by the script's source.`)},ownKeys:e=>Reflect.ownKeys(e),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,t),has:(e,t)=>"string"==typeof t&&a.has(t)}),values:s,entryByKey:a}}function uB(e){return null===e?"null":"string"==typeof e?JSON.stringify(e):String(e)}let uF=[{name:"title",type:"string",defval:"",mutable:!1,appliesTo:"both"},{name:"shorttitle",type:"string",defval:"",mutable:!1,appliesTo:"both"},{name:"overlay",type:"bool",defval:!1,mutable:!0,appliesTo:"both"},{name:"format",type:"enum",defval:"inherit",options:["inherit","price","volume","percent","mintick"],mutable:!0,appliesTo:"both"},{name:"precision",type:"int",defval:10,minval:0,maxval:16,mutable:!0,appliesTo:"both"},{name:"scale",type:"enum",defval:"right",options:["right","left","none"],mutable:!0,appliesTo:"both"},{name:"max_bars_back",type:"int",defval:0,minval:0,maxval:5e3,mutable:!0,appliesTo:"both"},{name:"explicit_plot_zorder",type:"bool",defval:!1,mutable:!0,appliesTo:"both"},{name:"max_lines_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"max_labels_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"max_boxes_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"calc_bars_count",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"both"},{name:"max_polylines_count",type:"int",defval:50,minval:1,maxval:100,mutable:!0,appliesTo:"both"},{name:"dynamic_requests",type:"bool",defval:!0,mutable:!0,appliesTo:"both",version:6},{name:"behind_chart",type:"bool",defval:!0,mutable:!0,appliesTo:"both",version:6}],uq=[...uF.filter(e=>"both"===e.appliesTo).map(e=>({...e,appliesTo:"indicator"})),{name:"timeframe",type:"string",defval:"",mutable:!0,appliesTo:"indicator"},{name:"timeframe_gaps",type:"bool",defval:!0,mutable:!0,appliesTo:"indicator"}],uz=[...uF.filter(e=>"both"===e.appliesTo).map(e=>({...e,appliesTo:"strategy"})),{name:"pyramiding",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"calc_on_order_fills",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"calc_on_every_tick",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"backtest_fill_limits_assumption",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"default_qty_type",type:"enum",defval:"fixed",options:["fixed","cash","percent_of_equity"],mutable:!0,appliesTo:"strategy"},{name:"default_qty_value",type:"float",defval:1,minval:0,mutable:!0,appliesTo:"strategy"},{name:"initial_capital",type:"float",defval:1e6,minval:0,mutable:!0,appliesTo:"strategy"},{name:"currency",type:"enum",defval:"USD",options:["AED","ARS","AUD","BDT","BHD","BRL","BTC","CAD","CHF","CLP","CNY","COP","CZK","DKK","EGP","ETH","EUR","GBP","HKD","HUF","IDR","ILS","INR","ISK","JPY","KES","KRW","KWD","LKR","MAD","MXN","MYR","NGN","NOK","NONE","NZD","PEN","PHP","PKR","PLN","QAR","RON","RSD","RUB","SAR","SEK","SGD","THB","TND","TRY","TWD","USD","USDT","VES","VND","ZAR"],mutable:!0,appliesTo:"strategy"},{name:"slippage",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"commission_type",type:"enum",defval:"percent",options:["percent","cash_per_contract","cash_per_order"],mutable:!0,appliesTo:"strategy"},{name:"commission_value",type:"float",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"process_orders_on_close",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"close_entries_rule",type:"enum",defval:"FIFO",options:["FIFO","ANY"],mutable:!0,appliesTo:"strategy"},{name:"margin_long",type:"float",defval:100,minval:0,maxval:100,mutable:!0,appliesTo:"strategy"},{name:"margin_short",type:"float",defval:100,minval:0,maxval:100,mutable:!0,appliesTo:"strategy"},{name:"risk_free_rate",type:"float",defval:2,mutable:!0,appliesTo:"strategy"},{name:"use_bar_magnifier",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"fill_orders_on_standard_ohlc",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"}];function uU(e){return"strategy"===e?uz:uq}function uW(e,t){let i={},r=e[e.length-1],n=r?.type==="ObjectExpression",s=n?e.slice(0,-1):e.slice();for(let e=0;e<s.length&&e<t.length;e++)i[t[e].name]=uK(s[e]);if(n)for(let e of r.properties??[])"Property"===e.type&&e.key?.name&&(i[e.key.name]=uK(e.value));return i}function uK(e){if(null!=e)switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;for(;t?.type==="MemberExpression";)t=t.property;return t?.type==="Identifier"?t.name:void 0}case"UnaryExpression":return"-"===e.operator&&e.argument?.type==="Literal"&&"number"==typeof e.argument.value?-e.argument.value:void 0;case"ArrayExpression":return(e.elements??[]).map(uK);default:return}}function uG(e,t){if(!(!e||"object"!=typeof e))for(let i of(t(e),Object.keys(e))){let r=e[i];if("loc"!==i&&"range"!==i&&"start"!==i&&"end"!==i)if(Array.isArray(r))for(let e of r)uG(e,t);else r&&"object"==typeof r&&"string"==typeof r.type&&uG(r,t)}}var uH=Object.defineProperty,uY=(e,t,i)=>((e,t,i)=>t in e?uH(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class uZ{constructor(e){uY(this,"_configured"),uY(this,"_resolverName"),uY(this,"_cached"),uY(this,"_cacheDuration",1/0),uY(this,"_cache",new Map),this._resolverName=e.resolverName,this._configured=!e.requiresConfig,this._cached=e.cached??!0}ensureConfigured(){if(!this._configured)throw Error(`The ${this._resolverName} import resolver requires configuration before use. Call ImportResolver.${this._resolverName}.configure({ ... }) or instantiate directly: new ${this._resolverName}ImportResolver({ ... })`)}configure(e){this._configured=!0,e?.cacheDuration!==void 0&&(this._cacheDuration=e.cacheDuration),this.clearCache()}get isConfigured(){return this._configured}resolve(e,t){if(!this._cached)return this._resolveUncached(t);let i=this._cache.get(e);if(i&&Date.now()-i.time<this._cacheDuration)return i.source;let r={source:this._resolveUncached(t),time:Date.now()};return this._cache.set(e,r),r.source.catch(()=>{this._cache.get(e)===r&&this._cache.delete(e)}),r.source}clearCache(){this._cache.clear()}async firstFound(e,t,i){for(let r of t){let t=await i(e+r);if(null!==t)return t}return null}_resolveUncached(e){return Promise.resolve().then(()=>(this.ensureConfigured(),this._resolveNative(e))).then(e=>"string"==typeof e?e:null)}}class uJ extends uZ{constructor(e){super({requiresConfig:!1,resolverName:"Function"}),this._fn=e}_resolveNative(e){return this._fn(e.path,e)}}function uQ(e){return"function"==typeof e?new uJ(e):e}async function uX(e,t){let i={};if(!/^import\s/m.test(e)||null===um(e))return i;let r=pN(e);if(0===r.length)return i;if(!t)throw Error(`The script imports ${r.map(e=>`"${e.path}"`).join(", ")} but no import resolver is configured. Call pineTS.setImportResolver(...) with a resolver that returns the library sources.`);let n=uQ(t),s=new Set,a=async(e,t)=>{let r;if(s.has(e.path))return;s.add(e.path);let{path:o,user:l,name:h,version:c}=e,p=await n.resolve(o,{path:o,user:l,name:h,version:c,importer:t});if("string"!=typeof p){if(void 0===t)throw Error(`Import "${o}" could not be resolved: the import resolver returned no source`);return}i[o]=p;try{r=pN(p)}catch(e){throw Error(`Library "${o}": ${e.message}`)}await Promise.all(r.map(e=>a(e,o)))};return await Promise.all(r.map(e=>a(e))),i}var u0=Object.defineProperty,u1=(e,t,i)=>((e,t,i)=>t in e?u0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class u2{constructor(e,t={}){u1(this,"source"),u1(this,"inputs"),u1(this,"_prepared",null),u1(this,"_libraries",null),u1(this,"_librariesResolver",null),u1(this,"_inputMeta",null),u1(this,"_inputValues",{}),u1(this,"_explicitOverrides",new Set),u1(this,"_inputProxy",null),u1(this,"_inputMetaByKey",new Map),u1(this,"_propMeta",null),u1(this,"_propValues",{}),u1(this,"_propProxy",null),u1(this,"_declarationType",null),u1(this,"_sourcePropArgs",{}),u1(this,"_explicitPropOverrides",new Set),this.source=e,this.inputs=t,Object.defineProperty(this,"input",{get:()=>this._getInputProxy(),set:()=>{throw Error('[Indicator] .input cannot be replaced — mutate individual keys (e.g. ind.input["My Title"] = 20).')},enumerable:!0,configurable:!1}),Object.defineProperty(this,"prop",{get:()=>this._getPropProxy(),set:()=>{throw Error('[Indicator] .prop cannot be replaced — mutate individual keys (e.g. ind.prop["initial_capital"] = 50000).')},enumerable:!0,configurable:!1})}static from(e){return e instanceof u2?e:new u2(e)}prepare(e={}){if(this._prepared)return this._prepared;let t=function(e,t={debug:!1,ln:!1}){let i;"boolean"==typeof t&&(t={debug:t,ln:!0});let{debug:r}=t,{code:n,version:s}=function(e,t={}){if("function"==typeof e)return{code:e.toString(),version:null};{let i=um(e);if(null===i){if(t.pineOnly)throw Error("Pine Script version marker required: markerless source is treated as raw JavaScript and is rejected when pineOnly is set.");return{code:e,version:null}}if(i>=5){let r=uN(e,{libraries:t.libraries});if(r.success){let e=r.unresolvedImports??[];if(e.length>0)throw Error(`Unresolved Pine Script import${e.length>1?"s":""}: ${e.map(e=>`"${e.path}"`).join(", ")}. Provide the library source with an import resolver (pineTS.setImportResolver) or the "libraries" transpile option.`);return{code:r.code,version:i}}throw Error(`Failed to transpile Pine Script version ${i}: ${r.error}`)}throw Error(`Unsupported Pine Script version ${i}. Only version 5 and above are supported.`)}}(e,{pineOnly:t.pineOnly,libraries:t.libraries}),a=n;a=function(e){let{isWrapped:t,isAsync:i,functionNode:r}=function(e){try{let t=hA(e,{ecmaVersion:"latest",sourceType:"module"});if("Program"===t.type&&1===t.body.length){let e=t.body[0];if("ExpressionStatement"===e.type){let t=e.expression;if("ArrowFunctionExpression"===t.type||"FunctionExpression"===t.type)return{isWrapped:!0,isAsync:t.async||!1,functionNode:t}}if("FunctionDeclaration"===e.type)return{isWrapped:!0,isAsync:e.async||!1,functionNode:e}}return{isWrapped:!1,isAsync:!1}}catch{return{isWrapped:!1,isAsync:!1}}}(e=e.trim());return t&&r?i?e:(r.async=!0,hB(r)):`async (context) => {
429
+ ${e}
430
+ }`}(a);let o=r?a.split(`
431
+ `):[],l=hA(a,{ecmaVersion:"latest",sourceType:"module",locations:r});hY(l,null,{VariableDeclaration(e,t,i){e.declarations&&e.declarations.length>0&&e.declarations.forEach(t=>{t.init&&"ArrowFunctionExpression"===t.init.type&&0!==t.init.start&&Object.assign(e,{type:"FunctionDeclaration",id:t.id,params:t.init.params,body:"BlockStatement"===t.init.body.type?t.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t.init.body}]},async:t.init.async,generator:!1})}),e.body&&e.body.body&&e.body.body.forEach(e=>i(e,t))}}),function(e){let t=new Set;if(hG(e,{FunctionDeclaration(e){e.id?.name&&t.add(e.id.name)}}),0===t.size)return;let i=e=>"AssignmentPattern"===e.type?e.left:e,r=new Map;hG(e,{FunctionDeclaration(e){let n=new Map;for(let r of e.params){let e=i(r);e?.type==="Identifier"&&t.has(e.name)&&(n.set(e.name,`${e.name}_$arg`),e.name=`${e.name}_$arg`)}0!==n.size&&(r.set(e.id.name,n),hH(e.body,{Identifier(e,t,i){let r=n.get(e.name);if(!r)return;let s=i[i.length-2];(s?.type!=="CallExpression"||s.callee!==e)&&(s?.type!=="MemberExpression"||s.property!==e||s.computed)&&(s?.type!=="Property"||s.key!==e||s.computed)&&(s?.type!=="FunctionDeclaration"||s.id!==e)&&(e.name=r)}}))}}),hG(e,{AssignmentExpression(e){let t=e.left;if(t?.type!=="MemberExpression"||t.property?.name!=="__pineParamTypes__")return;let i=r.get(t.object?.name);if(!(!i||e.right?.type!=="ObjectExpression"))for(let t of e.right.properties){let e=t.key?.type==="Identifier"?t.key.name:t.key?.value,r=i.get(e);r&&(t.key={type:"Literal",value:r})}}})}(l),function(e){let t=null,i="$";if("Program"===e.type&&e.body.length>0){let r=e.body[0];if("ExpressionStatement"===r.type&&("ArrowFunctionExpression"===r.expression.type||"FunctionExpression"===r.expression.type)){let e=r.expression;"BlockStatement"===e.body.type&&(t=e.body.body,e.params.length>0&&"Identifier"===e.params[0].type&&(i=e.params[0].name))}}if(!t)return;let r=new Set(oU),n=new Set(oW),s=new Set(oK),a=new Map;t.forEach(e=>{"VariableDeclaration"===e.type&&e.declarations.forEach(e=>{if(e.init&&"MemberExpression"===e.init.type&&"Identifier"===e.init.object.type&&e.init.object.name===i&&"Identifier"===e.init.property.type){let t=e.init.property.name,i=null;if("data"===t?i=r:"pine"===t?i=n:"core"===t&&(i=s),i&&"ObjectPattern"===e.id.type)e.id.properties.forEach(e=>{if("Property"===e.type&&"Identifier"===e.key.type&&"Identifier"===e.value.type){let t=e.key.name,r=e.value.name;i.has(t)&&t!==r&&(a.set(r,t),e.value.name=t,e.shorthand=!0)}});else if("Identifier"===e.id.type&&oP.includes(t)){let i=e.id.name;t!==i&&(a.set(i,t),e.id.name=t)}}})}),a.size>0&&hY(e,{},{Identifier(e){a.has(e.name)&&(e.name=a.get(e.name))},MemberExpression(e,t,i){i(e.object,t),e.computed&&i(e.property,t)},Property(e,t,i){e.computed&&i(e.key,t),i(e.value,t)}})}(l),function(e){let t=null,i="$";if("Program"===e.type&&e.body.length>0){let r=e.body[0];if("ExpressionStatement"===r.type&&("ArrowFunctionExpression"===r.expression.type||"FunctionExpression"===r.expression.type)){let e=r.expression;"BlockStatement"===e.body.type&&(t=e.body.body,e.params.length>0&&"Identifier"===e.params[0].type&&(i=e.params[0].name))}}if(!t)return;let r=new Set,n=new Set,s=e=>{"Identifier"===e.type?r.add(e.name):"ObjectPattern"===e.type?e.properties.forEach(e=>s(e.value)):"ArrayPattern"===e.type&&e.elements.forEach(e=>{e&&s(e)})};hY(e,{},{VariableDeclarator(e,t,i){s(e.id),e.init&&i(e.init,t)},FunctionDeclaration(e,t,i){for(let r of(s(e.id),e.params))r&&"AssignmentPattern"===r.type&&r.right&&i(r.right,t);i(e.body,t)},Identifier(e,t,i){n.add(e.name)},MemberExpression(e,t,i){i(e.object,t),e.computed&&i(e.property,t)},Property(e,t,i){e.computed&&i(e.key,t),i(e.value,t)}}),t.forEach(e=>{"VariableDeclaration"===e.type?e.declarations.forEach(e=>s(e.id)):"FunctionDeclaration"===e.type&&s(e.id)});let a=oU.filter(e=>!r.has(e)),o=oW.filter(e=>!r.has(e)),l=a.filter(e=>n.has(e)),h=o.filter(e=>n.has(e)),c=[];l.length>0&&c.push({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"ObjectPattern",properties:l.map(e=>({type:"Property",key:{type:"Identifier",name:e},value:{type:"Identifier",name:e},kind:"init",shorthand:!0}))},init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"data"},computed:!1}}]}),h.length>0&&c.push({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"ObjectPattern",properties:h.map(e=>({type:"Property",key:{type:"Identifier",name:e},value:{type:"Identifier",name:e},kind:"init",shorthand:!0}))},init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"pine"},computed:!1}}]}),c.length>0&&t.unshift(...c)}(l);let c=new hK;hG(l,{VariableDeclaration(e){e.declarations.forEach(e=>{let t=e.init&&"MemberExpression"===e.init.type&&e.init.object&&("context"===e.init.object.name||"$"===e.init.object.name||"context2"===e.init.object.name),i=e.init&&"MemberExpression"===e.init.type&&e.init.object?.object&&("context"===e.init.object.object.name||"$"===e.init.object.object.name||"context2"===e.init.object.object.name);(t||i)&&(e.id.name&&c.addContextBoundVar(e.id.name),e.id.properties&&e.id.properties.forEach(e=>{e.key.name&&c.addContextBoundVar(e.key.name)}))})}}),function(e,t){hG(e,{VariableDeclaration(e){for(let i of e.declarations)if(!(i.id?.type!=="Identifier"||!i.init)&&"CallExpression"===i.init.type&&i.init.callee?.type==="Identifier"&&"Type"===i.init.callee.name&&i.init.arguments?.length===1&&i.init.arguments[0]?.type==="ObjectExpression"){let e={};for(let t of i.init.arguments[0].properties)"Property"!==t.type||t.key?.type!=="Identifier"||(t.value?.type==="ArrayExpression"&&t.value.elements?.[0]?.type==="Literal"?e[t.key.name]=String(t.value.elements[0].value):t.value?.type==="Literal"&&(e[t.key.name]=String(t.value.value)));t.addUdtTypeName(i.id.name,e),i.init._udtName=i.id.name}}});let i=!0;for(;i;)i=!1,hG(e,{FunctionDeclaration(e){if(!e.id?.name)return;let r=e.id.name;if(t.getFunctionReturnType(r)||t.getFunctionReturnTupleType(r))return;let n=function(e){let t=[];return e&&function e(i){if(!(!i||"object"!=typeof i)&&"FunctionDeclaration"!==i.type&&"FunctionExpression"!==i.type&&"ArrowFunctionExpression"!==i.type){if("ReturnStatement"===i.type&&i.argument)return void t.push(i.argument);for(let t of Object.keys(i)){if("type"===t)continue;let r=i[t];Array.isArray(r)?r.forEach(e):r&&"object"==typeof r&&r.type&&e(r)}}}(e),t}(e.body);if(0===n.length)return;if(n.every(e=>"ArrayExpression"===e.type)){let e=n[0].elements.length;if(e>0&&n.every(t=>t.elements.length===e)){let s=[],a=!0;for(let i=0;i<e;i++){let e=n.map(e=>h3(e.elements[i],t)),r=e[0];if(!e.every(e=>e===r)){a=!1;break}s.push(r)}if(a&&s.some(e=>!!e)){t.setFunctionReturnTupleType(r,s),i=!0;return}}}let s=n.map(e=>h3(e,t)),a=s[0];a&&s.every(e=>e===a)&&(t.setFunctionReturnType(r,a),i=!0)}});hG(e,{VariableDeclaration(e){for(let i of e.declarations)if(i.init){if(i.id?.type==="Identifier"){let e=h3(i.init,t);if(e){t.markVariableAsUdtInstance(i.id.name,e);continue}let r=function e(t){if(t){if("CallExpression"===t.type&&t.callee?.type==="MemberExpression"&&!t.callee.computed&&t.callee.object?.type==="Identifier"&&t.callee.property?.type==="Identifier"){let e=t.callee.object.name,i=t.callee.property.name;if(h1.has(e)&&("new"===i||"copy"===i||"from"===i||i.startsWith("new_")))return e;let r=h2[`${e}.${i}`];if(r)return r}if("ConditionalExpression"===t.type){let i=e(t.consequent),r=e(t.alternate);if(i&&i===r)return i}}}(i.init);r&&t.setVarStaticType(i.id.name,r);continue}if(i.id?.type==="ArrayPattern"&&"CallExpression"===i.init.type&&i.init.callee?.type==="Identifier"){let e=t.getFunctionReturnTupleType(i.init.callee.name);if(!e)continue;i.id.elements?.forEach((i,r)=>{if(!i||"Identifier"!==i.type)return;let n=e[r];n&&t.markVariableAsUdtInstance(i.name,n)})}}},ExpressionStatement(e){let i=e.expression;if(i?.type==="Literal"&&"string"==typeof i.value&&i.value.startsWith("__pineUdtVar:")){let e=i.value.match(/^__pineUdtVar:([A-Za-z_$][\w$]*)=([A-Za-z_$][\w$]*)$/);if(e){let[,i,r]=e;t.isUdtTypeName(r)&&t.markVariableAsUdtInstance(i,r)}}else if(i?.type==="Literal"&&"string"==typeof i.value&&i.value.startsWith("__pineTypedVar:")){let e=i.value.slice(15),r=e.indexOf("=");if(r>0){let i=e.slice(0,r),n=e.slice(r+1);/^[A-Za-z_$][\w$]*$/.test(i)&&n&&t.setVarStaticType(i,n)}}}});let r=e=>{for(let t=0;t<e.length-1;t++){let i=e[t]?.type==="ExpressionStatement"?e[t].expression:null;if(i?.type!=="Literal"||"string"!=typeof i.value||!i.value.startsWith("__pineVarip:"))continue;let r=i.value.slice(12),n=e[t+1];if(n?.type==="VariableDeclaration"&&"var"===n.kind)for(let e of n.declarations)e.id?.type==="Identifier"&&e.id.name===r&&(e._varip=!0)}};hG(e,{Program(e){r(e.body)},BlockStatement(e){r(e.body)},SwitchCase(e){r(e.consequent)}}),hG(e,{ExpressionStatement(e){let i=e.expression;if(!i||"AssignmentExpression"!==i.type||"="!==i.operator)return;let r=i.left;if(r?.type!=="MemberExpression"||r.computed||r.property?.type!=="Identifier"||r.object?.type!=="Identifier")return;let n=r.object.name,s=n.startsWith("$M_")?n.slice(3):n;if("__pineReceiverType__"===r.property.name){i.right?.type==="Literal"&&"string"==typeof i.right.value&&t.setMethodReceiverType(s,i.right.value);return}if("__pineParamTypes__"!==r.property.name||i.right?.type!=="ObjectExpression")return;let a={},o={};for(let e of i.right.properties){let i;if("Property"!==e.type||(e.key?.type==="Identifier"?i=e.key.name:e.key?.type==="Literal"&&"string"==typeof e.key.value&&(i=e.key.value),!i||e.value?.type!=="Literal"||"string"!=typeof e.value.value))continue;o[i]=e.value.value;let r=e.value.value.split(/\s+/).pop();t.isUdtTypeName(r)&&(a[i]=r)}Object.keys(a).length>0&&t.setFunctionParamUdtTypes(s,a),Object.keys(o).length>0&&t.setFunctionParamStaticTypes(s,o)}})}(l,c);let p=(hH(l,{FunctionDeclaration(e){e.id&&e.id.name&&(c.addReservedName(e.id.name),c.addUserFunction(e.id.name),e.id.name.startsWith("$M_")||c.addRegularUserFunction(e.id.name))},ExpressionStatement(e){let t=e.expression;if(t&&"AssignmentExpression"===t.type&&"="===t.operator&&t.left?.type==="MemberExpression"&&t.left.property?.name==="__pineMethod__"&&t.left.object?.type==="Identifier"&&t.right?.value===!0){let e=t.left.object.name,i=e.startsWith("$M_")?e.slice(3):e;c.addMethodCandidate(i.replace(/\$\d+$/,""),e),c.addUserMethod(i),c.addUserFunction(i)}},ArrowFunctionExpression(e){let t=0===e.start;t&&e.params&&e.params.length>0&&(i=e.params[0].name,e.params[0].name="$"),function(e,t,i=!1){e.params.forEach(e=>{"Identifier"===e.type&&i&&t.addContextBoundVar(e.name,i)})}(e,c,t)},VariableDeclaration(e,t){let i=t.length>1?t[t.length-2]:null,r=i&&("ForOfStatement"===i.type||"ForInStatement"===i.type)&&i.left===e;e.declarations.forEach(i=>{if("Identifier"===i.id.type)c.addReservedName(i.id.name);else if("ObjectPattern"===i.id.type)i.id.properties.forEach(e=>{e.key&&"Identifier"===e.key.type&&c.addReservedName(e.key.name)});else if("ArrayPattern"===i.id.type){if(i.id.elements?.forEach(e=>{e&&"Identifier"===e.type&&c.addReservedName(e.name)}),r)return;let n=[...t].reverse().find(t=>t!==e&&("FunctionDeclaration"===t.type||"FunctionExpression"===t.type||"ArrowFunctionExpression"===t.type));if(n&&"FunctionDeclaration"!==n.type&&("ArrowFunctionExpression"!==n.type||0!==n.start)){i.init={type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"$"},property:{type:"Identifier",name:"toTuple"},computed:!1},arguments:[i.init,{type:"Literal",value:i.id.elements.length}],_transformed:!0},property:{type:"Literal",value:0},computed:!0};return}let s=c.generateTempVar(),a={type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:i.init,_tupleArity:i.id.elements.length}]};i.id.elements?.forEach(e=>{"Identifier"===e.type&&c.addArrayPatternElement(e.name)});let o=i.id.elements.map((t,i)=>({type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:t,init:{type:"MemberExpression",object:{type:"Identifier",name:s},property:{type:"Literal",value:i},computed:!0}}]}));Object.assign(e,{type:"BlockStatement",body:[a,...o]})}})},ForStatement(e){}}),i||"");if(null!==s&&function(e,t,i={intDivision:!0}){let r=new h8,n=function(e){let t=new Set;return function e(i){if(!(!i||"object"!=typeof i))for(let r in"AssignmentExpression"===i.type&&i.left?.type==="Identifier"?t.add(i.left.name):"UpdateExpression"===i.type&&i.argument?.type==="Identifier"&&t.add(i.argument.name),i){if("type"===r||"start"===r||"end"===r||"loc"===r||"raw"===r)continue;let t=i[r];if(Array.isArray(t))for(let i of t)i&&"object"==typeof i&&e(i);else t&&"object"==typeof t&&e(t)}}(e),t}(e);!function e(t){var s,a;if(!t||"object"!=typeof t)return"notint";switch(t.type){case"Literal":return"number"==typeof t.value&&(s=t)&&"Literal"===s.type&&"number"==typeof s.value&&Number.isInteger(s.value)&&!("string"==typeof s.raw&&/[.eE]/.test(s.raw))?"constint":"notint";case"Identifier":return h6.has(t.name)?"int":r.get(t.name)??"notint";case"UnaryExpression":return"-"===t.operator||"+"===t.operator?e(t.argument):(e(t.argument),"notint");case"BinaryExpression":{let r=e(t.left),n=e(t.right);if("/"===t.operator){if(i.intDivision&&"constint"===r&&"constint"===n){let e=h0.createMathIntDivCall(t.left,t.right);return Object.assign(t,e),"constint"}return"notint"}return"+"===t.operator||"-"===t.operator||"*"===t.operator||"%"===t.operator?"constint"===r&&"constint"===n?"constint":"notint"!==r&&"notint"!==n?"int":"notint":"notint"}case"ConditionalExpression":return e(t.test),h9(e(t.consequent),e(t.alternate));case"LogicalExpression":return e(t.left),e(t.right),"notint";case"CallExpression":{t.callee?.type==="MemberExpression"&&e(t.callee.object);let i=(t.arguments||[]).map(t=>e(t)),r=(a=t.callee)?"Identifier"===a.type?a.name:"MemberExpression"!==a.type||a.computed||a.object?.type!=="Identifier"||a.property?.type!=="Identifier"?null:`${a.object.name}.${a.property.name}`:null;return"array.from"===r&&i.length>0&&i.every(e=>"notint"!==e)&&(t.callee.property.name="__from_int"),r&&h5.has(r)?"int":"notint"}case"MemberExpression":return e(t.object),t.computed&&e(t.property),"notint";case"VariableDeclaration":for(let i of t.declarations||[]){let s=i.init?e(i.init):"notint";i.id?.type==="Identifier"&&("constint"===s&&("var"===t.kind||n.has(i.id.name))&&(s="int"),r.set(i.id.name,s))}return"notint";case"AssignmentExpression":{let i=e(t.right);return t.left?.type==="Identifier"?r.assign(t.left.name,i):e(t.left),i}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":for(let e of(r.push(),t.params||[])){let t="AssignmentPattern"===e.type?e.left:e;t?.type==="Identifier"&&r.set(t.name,"notint")}return e(t.body),r.pop(),"notint";default:return function(t){for(let i in t){if("type"===i||"start"===i||"end"===i||"loc"===i||"raw"===i)continue;let r=t[i];if(Array.isArray(r))for(let t of r)t&&"string"==typeof t.type&&e(t);else r&&"string"==typeof r.type&&e(r)}}(t),"notint"}}(e)}(l,0,{intDivision:s<6}),!function e(t,i,r){if(ct(t)){if(i&&(t._lazyOperand=!0),h7.has(t.type)){Array.isArray(t.params)&&t.params.forEach(t=>e(t,i,r)),e(t.body,!1,r);return}if("CallExpression"===t.type&&t.callee?.type==="MemberExpression"&&t.callee.object?.type==="Identifier"&&"request"===t.callee.object.name){t._lazyOperand=!1,t.arguments.forEach(t=>e(t,!1,r));return}if("ConditionalExpression"===t.type){e(t.test,i,r),e(t.consequent,!0,r),e(t.alternate,!0,r);return}if("LogicalExpression"===t.type&&ce.has(t.operator)){if(r.lazyLogical){e(t.left,i,r),e(t.right,!0,r);return}i&&"??"!==t.operator&&(t._strictLogical=!0)}for(let n of Object.keys(t)){if("parent"===n||n.startsWith("_"))continue;let s=t[n];Array.isArray(s)?s.forEach(t=>e(t,i,r)):ct(s)&&e(s,i,r)}}}(l,!1,{lazyLogical:null===s||s>=6}),function(e,t,i,r={debug:!1,ln:!1},n=[]){let s=e=>{if(!r.debug||!e.loc||!n.length)return null;let t=e.loc.start.line-1;if(t>=0&&t<n.length){let i=n[t].trim();if(i)return{type:"LineComment",value:`${r.ln?` [Line ${e.loc.start.line}]`:""} ${i}`}}return null};hY(e,t,{Program(e,t,i){let r=[];e.body.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope(),a=s(e);a&&r.push(a),r.push(...n),r.push(e)}),e.body=r},BlockStatement(e,t,i){let r=[];e.body.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope(),a=s(e);a&&r.push(a),r.push(...n),r.push(e)}),e.body=r},ReturnStatement(e,t,i){e.argument&&"ArrayExpression"!==e.argument.type&&"ObjectExpression"!==e.argument.type&&"Identifier"!==e.argument.type&&"MemberExpression"!==e.argument.type&&"fn"!==t.getCurrentScopeType()&&i(e.argument,t),function(e,t){let i=t.getCurrentScopeType();if(e.argument){if("ArrayExpression"===e.argument.type)e.argument.elements=e.argument.elements.map(e=>{if("Identifier"===e.type){if(t.isContextBound(e.name)&&!t.isRootParam(e.name))return h0.createGetCall(e,0);if(t.isLocalSeriesVar(e.name)){let t=h0.createIdentifier(e.name);return t._skipTransformation=!0,h0.createGetCall(t,0)}return ca(e.name,t)}return"MemberExpression"===e.type&&function(e){let t=e.object;return t?.type==="MemberExpression"&&t.object?.type==="Identifier"&&"$"===t.object.name&&["const","let","var","params"].includes(t.property?.name)}(e)?h0.createGetCall(e,0):"MemberExpression"===e.type&&e.computed?(cg(e,"",t),e):"MemberExpression"===e.type||"BinaryExpression"===e.type||"LogicalExpression"===e.type||"ConditionalExpression"===e.type||"CallExpression"===e.type||"UnaryExpression"===e.type?(hY(e,t,{Identifier(e,t){cu(e,t),"Identifier"!==e.type||e._arrayAccessed||(cp(e),e._arrayAccessed=!0)},MemberExpression(e,i,r){c$(e,i,r),cg(e,"",t)},CallExpression(e,t,i){("ArrowFunctionExpression"===e.callee.type||"FunctionExpression"===e.callee.type)&&i(e.callee,t),cC(e,t),"CallExpression"===e.type&&e.arguments.forEach(e=>i(e,t))},BinaryExpression(e,t,i){i(e.left,t),i(e.right,t)}}),e):e}),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("ObjectExpression"===e.argument.type)e.argument.properties=e.argument.properties.map(e=>e.shorthand?t.isContextBound(e.value.name)?e:(t.getVariable(e.value.name),{type:"Property",key:h0.createIdentifier(e.key.name),value:cs(e.value.name,t),kind:"init",method:!1,shorthand:!1,computed:!1}):(e.value&&"Identifier"===e.value.type&&(t.isContextBound(e.value.name)&&!t.isRootParam(e.value.name)||t.isContextBound(e.value.name)||(e.value=cs(e.value.name,t))),e));else if("Identifier"===e.argument.type)cu(e.argument,t),"Identifier"===e.argument.type&&cp(e.argument);else if("MemberExpression"===e.argument.type)if("Identifier"!==e.argument.object.type||t.isContextBound(e.argument.object.name)||t.isLoopVariable(e.argument.object.name)||e.argument.computed&&t.isLocalSeriesVar(e.argument.object.name))if(e.argument.computed||"MemberExpression"!==e.argument.object.type){if(e.argument.computed&&"MemberExpression"===e.argument.object.type){let i=e.argument.object;for(;i.object&&"MemberExpression"===i.object.type;)i=i.object;i.object?.type==="Identifier"&&t.isUdtInstance(i.object.name)&&cg(e.argument,"",t)}}else{let i=e.argument.object;for(;"MemberExpression"===i.type&&!i.computed;)i=i.object;"Identifier"!==i.type||t.isContextBound(i.name)||t.isLoopVariable(i.name)||cu(i,t)}else cu(e.argument.object,t);if("fn"===i){"Identifier"===e.argument.type&&t.isContextBound(e.argument.name)&&!t.isRootParam(e.argument.name)?e.argument=h0.createArrayAccess(e.argument,0):"MemberExpression"===e.argument.type?e.argument.computed&&(cd.includes(e.argument.object.type)||cm(e.argument.object,t))?(cg(e.argument,"",t),e.argument._historyTransformed&&(e.argument.arguments[1]=cy(e.argument.arguments[1],t))):"Identifier"===e.argument.object.type&&t.isContextBound(e.argument.object.name)&&!t.isRootParam(e.argument.object.name)?e.argument.computed?cg(e.argument,"",t):e.argument._indexTransformed||(cl(e.argument,t),e.argument._indexTransformed=!0):e.argument.computed&&"Identifier"===e.argument.object.type&&t.isLocalSeriesVar(e.argument.object.name)&&cg(e.argument,"",t):("BinaryExpression"===e.argument.type||"LogicalExpression"===e.argument.type||"ConditionalExpression"===e.argument.type||"CallExpression"===e.argument.type||"UnaryExpression"===e.argument.type||"AssignmentExpression"===e.argument.type)&&hY(e.argument,t,{Identifier(e,t){cu(e,t),"Identifier"!==e.type||e._arrayAccessed||(cp(e),e._arrayAccessed=!0)},MemberExpression(e,i,r){c$(e,i,r),cg(e,"",t)},AssignmentExpression(e,t,i){if("Identifier"===e.left.type){let[r]=t.getVariable(e.left.name);if(r===e.left.name&&!t.isContextBound(e.left.name))return void i(e.right,t)}cD(e,t)},CallExpression(e,t,i){("ArrowFunctionExpression"===e.callee.type||"FunctionExpression"===e.callee.type)&&i(e.callee,t),cC(e,t),"CallExpression"===e.type&&e.arguments.forEach(e=>i(e,t))},BinaryExpression(e,t,i){i(e.left,t),i(e.right,t)},ForStatement(e,t,i){cO(e,t,i)},WhileStatement(e,t,i){cj(e,t,i)},ArrowFunctionExpression(e,i,r){if(e.body)if("BlockStatement"===e.body.type){let n=[];e.body.body.forEach(e=>{t.enterHoistingScope(),r(e,i);let s=t.exitHoistingScope();n.push(...s),n.push(e)}),e.body.body=n}else r(e.body,i)},FunctionExpression(e,i,r){if(e.body&&"BlockStatement"===e.body.type){let n=[];e.body.body.forEach(e=>{t.enterHoistingScope(),r(e,i);let s=t.exitHoistingScope();n.push(...s),n.push(e)}),e.body.body=n}},SwitchStatement(e,t,i){e.discriminant.parent=e,i(e.discriminant,t),e.cases.forEach(r=>{r.parent=e,i(r,t)})},SwitchCase(e,i,r){e.test&&(e.test.parent=e,r(e.test,i));let n=[];e.consequent.forEach(e=>{t.enterHoistingScope(),r(e,i);let s=t.exitHoistingScope();n.push(...s),n.push(e)}),e.consequent=n},BlockStatement(e,t,i){let r=[];e.body.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope();r.push(...n),r.push(e)}),e.body=r}});let i=h0.createCallExpression(h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("precision")),[e.argument]);e.argument=i}}}(e,t)},VariableDeclaration(e,t){!function e(t,i){t._skipTransformation||t.declarations.forEach(r=>{let n;if(r.init?.type==="CallExpression"&&r.id?.type==="Identifier"){let e=r.init.callee;(e?.type==="MemberExpression"&&e.object?.type==="Identifier"&&"input"===e.object.name||e?.type==="Identifier"&&"input"===e.name)&&(r.init._varId=r.id.name)}if(r.init&&"Identifier"===r.init.type&&oD.includes(r.init.name)&&i.isContextBound(r.init.name)){let e=r.init.name;Object.assign(r.init,{type:"MemberExpression",object:{type:"Identifier",name:e},property:{type:"Identifier",name:"__value"},computed:!1}),delete r.init.name}let s=r.init&&"MemberExpression"===r.init.type&&r.init.object&&("context"===r.init.object.name||"$"===r.init.object.name||"context2"===r.init.object.name),a=r.init&&"MemberExpression"===r.init.type&&r.init.object?.object&&("context"===r.init.object.object.name||"$"===r.init.object.object.name||"context2"===r.init.object.object.name),o=r.init&&"ArrowFunctionExpression"===r.init.type;if(s){r.id.name&&i.addContextBoundVar(r.id.name),r.id.properties&&r.id.properties.forEach(e=>{e.key.name&&i.addContextBoundVar(e.key.name)}),r.init.object.name="$";return}if(a){r.id.name&&i.addContextBoundVar(r.id.name),r.id.properties&&r.id.properties.forEach(e=>{e.key.name&&i.addContextBoundVar(e.key.name)}),r.init.object.object.name="$";return}i.addVariable(r.id.name,t.kind);let l=t.kind,h=i.hideCurrentScopeVariable(r.id.name),c=i.isArrayPatternElement(r.id.name)&&r.init&&"MemberExpression"===r.init.type&&r.init.computed;!r.init||o||c||("CallExpression"===r.init.type&&"MemberExpression"===r.init.callee.type&&r.init.callee.object&&"Identifier"===r.init.callee.object.type&&i.isContextBound(r.init.callee.object.name)?cC(r.init,i):cR(r.init,i)),h();let p=cs(r.id.name,i),u=!c&&r.init&&"MemberExpression"===r.init.type&&r.init.computed&&r.init.property&&("Literal"===r.init.property.type||"MemberExpression"===r.init.property.type);if(r.init?.property?.type==="MemberExpression"&&(r.init.property._indexTransformed||(cl(r.init.property,i),r.init.property._indexTransformed=!0)),"var"===l){let e=i.getCurrentHoistingScope();if(e){for(let t of e)if("VariableDeclaration"===t.type)for(let e of t.declarations){let t;if(!e.init||"CallExpression"!==e.init.type)continue;let i=e.init.callee;if(i?.type!=="MemberExpression")continue;let r=i.property?.name;if(i.object?.type==="Identifier"?t=i.object.name:i.object?.type==="MemberExpression"&&i.object.property?.name&&(t=i.object.property.name),t&&r){let i=`${t}.${r}`;o$.includes(i)&&(e.init={type:"ArrowFunctionExpression",params:[],body:e.init,expression:!0,async:!1})}}}}if(r.init)if(o||c)n=r.init;else if("var"===l)n=h0.createInitVarCall(p,r.init,!0===r._varip);else if(void 0!==r._tupleArity){let e=h0.createCallExpression(h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("toTuple")),[r.init,h0.createLiteral(r._tupleArity)]);n=h0.createInitCall(p,e)}else n=h0.createInitCall(p,u?r.init.object:r.init,u?r.init.property:void 0);else n="var"!==l?h0.createInitCall(p,h0.createIdentifier("NaN")):h0.createIdentifier("undefined");let d=h0.createExpressionStatement(h0.createAssignmentExpression(p,n));if(c){let e=cs(r.init.object.name,i),t=r.init.property.value,n={type:"MemberExpression",object:h0.createGetCall(e,0),property:{type:"Literal",value:t},computed:!0};d.expression.right=h0.createCallExpression(h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("init")),[p,n])}o&&(i.pushScope("fn"),hY(r.init.body,i,{IfStatement(e,t,i){t.pushScope("if"),e.test&&cV(e.test,t),i(e.consequent,t),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope()),t.popScope()},VariableDeclaration(t,i){e(t,i)},Identifier(e,t){cu(e,t)},AssignmentExpression(e,t){cD(e,t)},SwitchStatement(e,t,i){e.discriminant.parent=e,i(e.discriminant,t),e.cases.forEach(r=>{r.parent=e,i(r,t)})},SwitchCase(e,t,i){e.test&&(e.test.parent=e,i(e.test,t));let r=[];e.consequent.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope();r.push(...n),r.push(e)}),e.consequent=r},BlockStatement(e,t,i){let r=[];e.body.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope();r.push(...n),r.push(e)}),e.body=r}}),i.popScope()),Object.assign(t,d)})}(e,t)},Identifier(e,t){cu(e,t)},CallExpression(e,t,i){e.callee&&("ArrowFunctionExpression"===e.callee.type||"FunctionExpression"===e.callee.type)?i(e.callee,t):e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&(e.callee.object.parent=e.callee,i(e.callee.object,t)),cC(e,t)},ArrowFunctionExpression(e,t,i){e.body&&i(e.body,t)},FunctionExpression(e,t,i){e.body&&i(e.body,t)},ForOfStatement(e,t,i){if(e.left&&"VariableDeclaration"===e.left.type){e.left._skipTransformation=!0;let i=e.left.declarations[0];"Identifier"===i.id.type?t.addLoopVariable(i.id.name,i.id.name):"ArrayPattern"===i.id.type&&i.id.elements.forEach(e=>{"Identifier"===e.type&&t.addLoopVariable(e.name,e.name)})}if(e.right){"Identifier"===e.right.type?(cu(e.right,t),"Identifier"===e.right.type&&cp(e.right)):i(e.right,t);let r=e.left&&"VariableDeclaration"===e.left.type&&"ArrayPattern"===e.left.declarations[0].id.type?"entries":"iter",n={...e.right},s=h0.createCallExpression(h0.createMemberExpression(h0.createIdentifier("$"),h0.createIdentifier(r),!1),[n]);Object.assign(e.right,s)}let r=cP(t.getNextLoopGuardName());if(t.addHoistedStatement(r.counterDecl),e.body&&i(e.body,t),e.body&&("BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[e.body]}),e.body.body.unshift(r.guardCheck)),e.left&&"VariableDeclaration"===e.left.type){let i=e.left.declarations[0];"Identifier"===i.id.type?t.removeLoopVariable(i.id.name):"ArrayPattern"===i.id.type&&i.id.elements.forEach(e=>{"Identifier"===e.type&&t.removeLoopVariable(e.name)})}},ForInStatement(e,t,i){e.left&&"VariableDeclaration"===e.left.type&&(e.left._skipTransformation=!0),e.right&&"Identifier"===e.right.type?(cu(e.right,t),"Identifier"===e.right.type&&cp(e.right)):e.right&&i(e.right,t);let r=cP(t.getNextLoopGuardName());t.addHoistedStatement(r.counterDecl),e.body&&(i(e.body,t),"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[e.body]}),e.body.body.unshift(r.guardCheck))},DoWhileStatement(e,t,i){let r=cP(t.getNextLoopGuardName());t.addHoistedStatement(r.counterDecl),e.test&&i(e.test,t),e.body&&(i(e.body,t),"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[e.body]}),e.body.body.unshift(r.guardCheck))},MemberExpression(e,t,r){e.object&&("CallExpression"===e.object.type||"MemberExpression"===e.object.type)&&(e.object.parent=e,r(e.object,t)),e.object&&"Identifier"===e.object.type&&!t.isContextBound(e.object.name)&&(e.object.parent=e,r(e.object,t)),cg(e,i,t)},AssignmentExpression(e,t,i){cD(e,t);let r=e=>{e&&("CallExpression"===e.type&&e.callee&&!e._iifeTransformed&&("ArrowFunctionExpression"===e.callee.type||"FunctionExpression"===e.callee.type)&&i(e.callee,t),("BinaryExpression"===e.type||"LogicalExpression"===e.type||"ConditionalExpression"===e.type)&&(r(e.left),r(e.right),r(e.consequent),r(e.alternate)))};"AssignmentExpression"===e.type?r(e.right):"CallExpression"===e.type&&e.arguments&&e.arguments.forEach(e=>r(e))},FunctionDeclaration(e,t,i){!function(e,t,i){let r=h0.createVariableDeclaration("$$",h0.createCallExpression(h0.createMemberExpression(h0.createContextIdentifier(),h0.createIdentifier("peekCtx")),[]));if(r._skipTransformation=!0,t.addLoopVariable("$$","$$"),e.body&&"BlockStatement"===e.body.type){e.body.body.unshift(r),t.pushScope("fn"),e.params.forEach(e=>{"Identifier"===e.type?t.addFunctionParam(e.name):"AssignmentPattern"===e.type&&e.left?.type==="Identifier"&&t.addFunctionParam(e.left.name)});let n=e.id?.name,s=n?.startsWith("$M_")?n.slice(3):n,a=s?t.getFunctionParamUdtTypes(s):void 0,o={};if(a)for(let[e,i]of Object.entries(a))o[e]=t.getVariableUdtType(e),t.markVariableAsUdtInstance(e,i);let l=s?t.getFunctionParamStaticTypes(s):void 0,h={};if(l)for(let[e,i]of Object.entries(l))h[e]=t.getVarStaticType(e),t.setVarStaticType(e,i);if(t.enterFunctionHoistingRoot(),i(e.body,t),t.exitFunctionHoistingRoot(),e.params.forEach(e=>{"Identifier"===e.type?t.removeFunctionParam(e.name):"AssignmentPattern"===e.type&&e.left?.type==="Identifier"&&t.removeFunctionParam(e.left.name)}),a)for(let e of Object.keys(a)){t.unmarkVariableAsUdtInstance(e);let i=o[e];void 0!==i&&t.markVariableAsUdtInstance(e,i)}if(l)for(let e of Object.keys(l)){t.unsetVarStaticType(e);let i=h[e];void 0!==i&&t.setVarStaticType(e,i)}t.popScope()}}(e,t,i)},ForStatement(e,t,i){cO(e,t,i)},WhileStatement(e,t,i){cj(e,t,i)},IfStatement(e,t,i){let r=e._chainHoistFrame??t.getCurrentHoistingScope();if(e.test){t.pushScope("if");let i=e._chainHoistFrame?t.setChainHoistFrame(e._chainHoistFrame):void 0;try{cV(e.test,t)}finally{e._chainHoistFrame&&t.restoreChainHoistFrame(i??null)}t.popScope()}if(t.pushScope("if"),i(e.consequent,t),t.popScope(),e.alternate){if(t.pushScope("els"),"IfStatement"===e.alternate.type){r&&(e.alternate._chainHoistFrame=r);let n={type:"BlockStatement",body:[e.alternate]};i(n,t),e.alternate=1===n.body.length&&"IfStatement"===n.body[0].type?n.body[0]:n}else i(e.alternate,t);t.popScope()}},SwitchStatement(e,t,i){e.discriminant.parent=e,i(e.discriminant,t),e.cases.forEach(r=>{r.parent=e,i(r,t)})},SwitchCase(e,t,i){e.test&&(e.test.parent=e,i(e.test,t));let r=[];e.consequent.forEach(e=>{t.enterHoistingScope(),i(e,t);let n=t.exitHoistingScope();r.push(...n),r.push(e)}),e.consequent=r},AwaitExpression(e,t,i){e.argument&&(e.argument._insideAwait=!0,i(e.argument,t),"Identifier"===e.argument.type&&!0===e.argument._wasInsideAwait&&(e.type="Identifier",e.name=e.argument.name,e.argument._wasHoisted&&(e._wasHoisted=e.argument._wasHoisted),delete e.argument))}})}(l,c,p,t,o),function(e){let t={...hX,LineComment:()=>{}};hH(e,{BinaryExpression(e,t,i){let r=cL[e.operator];if(!r||cB.has(e.operator)&&function(e,t){if(e._skipCompare)return!0;for(let e=0;e<t.length-1;e++){let i=t[e],r=t[e+1];if("ForStatement"===i.type&&(r===i.test||r===i.update)||"ForStatement"===i.type&&r===i.init&&t.slice(e+1).some(e=>"VariableDeclarator"===e.type&&/^__for_up\d+$/.test(e.id?.name))||("WhileStatement"===i.type||"DoWhileStatement"===i.type)&&r===i.test)return!0}return!1}(e,i))return;let n=h0.createMathCompareCall(r,e.left,e.right);n._transformed=!0,Object.assign(e,n)}},t)}(l),function(e){let t={...hX,LineComment:()=>{}};hG(e,{LogicalExpression(e){if(!e._strictLogical)return;let t=cF[e.operator];if(!t)return;let i=h0.createMathCompareCall(t,e.left,e.right);i._transformed=!0,Object.assign(e,i),delete e.operator,delete e.left,delete e.right}},t)}(l),function(e){let t={...hX,LineComment:()=>{}};hG(e,{BinaryExpression(e){let t=cq[e.operator];if(!t||!cz(e.left)&&!cz(e.right))return;let i=h0.createMemberExpression(h0.createIdentifier("display"),h0.createIdentifier(t),!1),r=h0.createCallExpression(i,[e.left,e.right]);r._displaySetOp=!0,Object.assign(e,r)}},t)}(l),function(e){let t={...hX,LineComment:()=>{}},i=new Map;function r(e){let i=!1,r={...t,FunctionDeclaration:()=>{},FunctionExpression:()=>{},ArrowFunctionExpression:()=>{}};return hG(e,{AwaitExpression(){i=!0}},r),i}hG(e,{FunctionDeclaration(e){e.id?.name&&i.set(e.id.name,e)}},t);let n=!0,s=0;for(;n&&s<20;){n=!1,s++,hG(e,{ArrowFunctionExpression(e){!e.async&&r(e.body)&&(e.async=!0,n=!0)},FunctionExpression(e){!e.async&&r(e.body)&&(e.async=!0,n=!0)}},t);let a=[];for(let i of(hG(e,{CallExpression(e){e._asyncWrapped||e.callee?.type!=="ArrowFunctionExpression"&&e.callee?.type!=="FunctionExpression"||!0!==e.callee.async||a.push(e)}},t),a)){let e={};for(let t of Object.keys(i))e[t]=i[t];for(let t of(e._asyncWrapped=!0,Object.keys(i)))delete i[t];i.type="AwaitExpression",i.argument=e,n=!0}let o=new Set;for(let[e,t]of i)r(t.body)&&(t.async||(t.async=!0,n=!0),o.add(e));if(o.size>0){let i=[];for(let r of(hG(e,{CallExpression(e){if(!e._asyncWrapped&&e.callee?.type==="MemberExpression"&&e.callee.object?.name==="$"&&e.callee.property?.name==="call"&&e.arguments?.length>0){var t;let r=(t=e.arguments[0])?"Identifier"===t.type?t.name:"CallExpression"===t.type&&t.callee?.type==="MemberExpression"&&t.callee.object?.name==="$"&&t.callee.property?.name==="get"&&t.arguments?.[0]?.type==="Identifier"?t.arguments[0].name:null:null;r&&o.has(r)&&i.push(e)}}},t),i)){let e={};for(let t of Object.keys(r))e[t]=r[t];for(let t of(e._asyncWrapped=!0,Object.keys(r)))delete r[t];r.type="AwaitExpression",r.argument=e,n=!0}}}}(l),"Program"===l.type&&l.body.length>0){let e=l.body[0],t=e?.expression||e;t.body?.type==="BlockStatement"&&t.body.body.unshift({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"__maxLoops"},init:{type:"LogicalExpression",operator:"||",left:{type:"MemberExpression",object:{type:"Identifier",name:"$"},property:{type:"Identifier",name:"__maxLoops"},computed:!1},right:{type:"Literal",value:5e5}}}]})}let u=hB(l,{generator:Object.assign({},hV||hV||void 0,{LineComment(e,t){t.write("//"+e.value)}}),comments:r});if(!1!==t.verify&&null!==s){var d=hA(u,{ecmaVersion:"latest"});let e=new Set;(function e(t,i,r){if(!(!t||"object"!=typeof t||r.has(t))){switch(r.add(t),t.type){case"VariableDeclarator":uR(t.id,i);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":for(let e of(t.id?.name&&i.add(t.id.name),t.params||[]))uR(e,i);break;case"ClassDeclaration":case"ClassExpression":t.id?.name&&i.add(t.id.name);break;case"CatchClause":t.param&&uR(t.param,i)}for(let n of Object.keys(t)){if(uP.has(n))continue;let s=t[n];if(Array.isArray(s))for(let t of s)e(t,i,r);else s&&"object"==typeof s&&"string"==typeof s.type&&e(s,i,r)}}})(d,e,new WeakSet),function e(t,i,r,n,s){if(!(!t||"object"!=typeof t||"string"!=typeof t.type||s.has(t))){switch(s.add(t),t.type){case"ThisExpression":throw new uD('"this" is not available in Pine scripts');case"Super":throw new uD('"super" is not available in Pine scripts');case"MetaProperty":throw new uD('"import.meta" is not available in Pine scripts');case"ImportExpression":throw new uD("dynamic import() is not available in Pine scripts");case"WithStatement":throw new uD('"with" is not available in Pine scripts');case"NewExpression":if(t.callee?.type!=="Identifier"||"Error"!==t.callee.name)throw new uD("object construction is not available in Pine scripts");break;case"Identifier":{var a;let e=i?.type==="MemberExpression"&&"property"===r&&!i.computed,s=i?.type==="Property"&&"key"===r&&!i.computed;if(e||s)return void uO(t.name);if((a=t.name).length>=2&&(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))||"Error"===t.name&&i?.type==="NewExpression"&&"callee"===r)return;if(!n.has(t.name)&&!uC.has(t.name))throw new uD(`Undeclared identifier "${t.name}"`);return}case"MemberExpression":if(t.computed)if(t.property?.type==="Literal")uO(t.property.value);else throw new uD("dynamic computed member access is not allowed")}for(let i of Object.keys(t)){if(uP.has(i))continue;let r=t[i];if(Array.isArray(r))for(let a of r)e(a,t,i,n,s);else r&&"object"==typeof r&&"string"==typeof r.type&&e(r,t,i,n,s)}}}(d,null,null,e,new WeakSet)}let m="u">typeof h&&h?.env?.PINETS_DISABLE_LTF_SLICING==="1"?{}:function(e){let t={};if(!e||"Program"!==e.type||!Array.isArray(e.body)||0===e.body.length)return t;let i=e.body[0],r=null;if("ExpressionStatement"===i.type){let e=i.expression;e&&("ArrowFunctionExpression"===e.type||"FunctionExpression"===e.type)&&(r=e)}else"FunctionDeclaration"===i.type&&(r=i);if(!r||r.body?.type!=="BlockStatement")return t;for(let{call:e,path:i}of function(e){let t=[],i=new WeakSet;return function e(r,n){if(!r||"object"!=typeof r||i.has(r))return;i.add(r);let s=n.concat([r]);for(let i of(function(e){if(!e||"CallExpression"!==e.type)return!1;let t=e.callee;return!!t&&"MemberExpression"===t.type&&!t.computed&&t.object?.type==="Identifier"&&"request"===t.object.name&&t.property?.type==="Identifier"&&uT.has(t.property.name)}(r)&&t.push({call:r,path:s}),Object.keys(r))){if(uk.has(i))continue;let t=r[i];if(Array.isArray(t))for(let i of t)e(i,s);else t&&"object"==typeof t&&e(t,s)}}(e,[]),t}(r.body)){let n=function(e){let t=e?.arguments?.[2];return t?.type==="Identifier"&&"string"==typeof t.name?t.name:null}(e);if(!n||n in t)continue;let s=i.some(e=>uA(e)),a=null;if(s)a=function(e,t){let i=-1;for(let e=1;e<t.length;e++)if(uA(t[e])){i=e;break}if(i<0)return null;let r=t[i];for(let e=i+1;e<t.length;e++)if(uA(t[e]))return null;if("FunctionDeclaration"!==r.type||!r.id?.name)return null;let n=r.id.name,s=uI(r,t.slice(i),0),a=function(e,t,i){let r=e.body||[];for(let e=r.length-1;e>=0;e--){let n=r[e];if(n!==i&&function(e,t){let i=!1,r=new WeakSet;return function e(n){if(!(i||!n||"object"!=typeof n)&&!r.has(n)){if(r.add(n),function(e){if(!e||"CallExpression"!==e.type)return null;let t=e.callee;if(!t||"MemberExpression"!==t.type||t.computed||t.object?.type!=="Identifier"||"$"!==t.object.name||t.property?.type!=="Identifier"||"call"!==t.property.name)return null;let i=e.arguments?.[0];return i?.type==="Identifier"&&"string"==typeof i.name?i.name:null}(n)===t){i=!0;return}for(let t of Object.keys(n)){if(uk.has(t))continue;let i=n[t];if(Array.isArray(i))for(let t of i)e(t);else i&&"object"==typeof i&&e(i)}}}(e),i}(n,t))return e}return -1}(e,n,r);if(a<0)return null;let o=e.body||[],l=o.indexOf(r);if(l<0)return null;let h=[],c=Math.max(a,l);for(let e=0;e<=c;e++){let t=o[e];h.push(t===r?s:t)}return h}(r.body,i);else{let e=uI(r.body,i,0);a=e&&e.body?e.body:[]}if(!a||0===a.length)continue;let o=function(e,t){let i={type:"Program",sourceType:"module",body:[{type:"ExpressionStatement",expression:{type:"ArrowFunctionExpression",async:!!e.async,params:e.params,body:{type:"BlockStatement",body:t}}}]};return Function("",`var _r = ${hB(i)}
432
+ ; return _r;`)()}(r,a);t[n]=o}return t}(l),f=Function("",`var _r = ${u}
433
+ ; return _r;`)(this);if(f._pineVersion=s,m&&Object.keys(m).length>0){for(let e of Object.values(m))e._pineVersion=s;f._ltfSlices=m}return f}(this.source,{debug:!!e.debug,ln:e.ln,libraries:this._libraries??void 0}),i=function(e){let t=e.toString();return oO.some(e=>{let i=e.replace(/\./g,"\\.");return RegExp(`\\b${i}\\b`).test(t)})}(t),r=t._ltfSlices,n=this;return this._prepared={fn:t,get inputs(){return n.getRuntimeInputs()},usesVisibleRange:i,ltfSlices:r},this._prepared}async resolveImports(e){if("string"!=typeof this.source||this._libraries&&this._librariesResolver===e)return;let t=await uX(this.source,e);this._libraries&&!function(e,t){let i=Object.keys(e);return i.length===Object.keys(t).length&&i.every(i=>e[i]===t[i])}(this._libraries,t)&&(this._prepared=null),this._libraries=t,this._librariesResolver=e}usesVisibleRange(){return this.prepare().usesVisibleRange}getRuntimeInputs(){let e={...this.inputs??{}};if(this._inputMeta)for(let t of this._explicitOverrides){let i=this._inputValues[t],r=this._inputMetaByKey.get(t);r&&(e[r.id]=i),this._inputMeta.some(e=>e!==r&&(e.varId===t||e.title===t))||(e[t]=i)}return e}getInputsMeta(){return this._ensureInputsScanned(),this._inputMeta}getPropsMeta(){return this._ensurePropsScanned(),this._propMeta}getRuntimePropOverrides(){let e={};if(this._propMeta)for(let t of this._explicitPropOverrides)e[t]=this._propValues[t];return e}getDeclarationType(){return this._ensurePropsScanned(),this._declarationType}_ensureInputsScanned(){if(this._inputMeta)return;for(let e of(this._inputMeta=function(e,t){if("string"!=typeof e)return[];let i=uN(e,{libraries:t});if(!i.success||!i.inputs)return[];let r=[];for(let e of i.inputs){let t=function(e){let t=e.args,i=""===e.fn?function(e,t){switch(t){case"int":case"float":case"bool":case"string":case"color":case"source":return t}return"boolean"==typeof e?"bool":"number"==typeof e?Number.isInteger(e)?"int":"float":"string"==typeof e?tH.has(e)?"source":e.startsWith("#")?"color":"string":null}(t.defval,e.defvalType):uj[e.fn];if(!i)return null;let r={id:e.id,name:e.name,type:i,defval:t.defval};void 0!==e.varId&&(r.varId=e.varId),void 0!==t.title&&(r.title=String(t.title)),void 0!==t.tooltip&&""!==t.tooltip&&(r.tooltip=String(t.tooltip)),void 0!==t.group&&(r.group=String(t.group)),void 0!==t.inline&&(r.inline=String(t.inline)),void 0!==t.confirm&&(r.confirm=!!t.confirm),void 0!==t.active&&(r.active=!!t.active);let n="display"in t?function(e){if("string"!=typeof e)return;let t=e.startsWith("display.")?e.slice(8):e;if("none"===t||"data_window"===t||"status_line"===t||"all"===t)return t}(t.display):uV.has(i)?"none":"all";return void 0!==n&&(r.display=n),Array.isArray(t.options)?r.options=t.options:"source"===i&&(r.options=[...u$]),"number"==typeof t.minval&&(r.minval=t.minval),"number"==typeof t.maxval&&(r.maxval=t.maxval),"number"==typeof t.step&&(r.step=t.step),r}(e);t&&r.push(t)}return r}(this.source,this._libraries??void 0),this._inputMeta))"color"===e.type&&void 0!==e.defval&&(e.defval=function(e){let t=y(e);return t?_(t[0],t[1],t[2],t[3]):e}(e.defval));let e=function(e,t){let i=new Map,r=[],n=new Set(e.map(e=>e.id));for(let t of e){let e=[t.varId,t.title].find(e=>e&&!i.has(e)&&!n.has(e))??t.id,s=[t.title,t.id].filter(t=>!!t&&t!==e);i.set(e,t),r.push({key:e,type:t.type,defval:t.defval,options:"source"===t.type?void 0:t.options,minval:t.minval,maxval:t.maxval,aliases:s.length?s:void 0})}let{proxy:s,values:a}=uL(r,"Indicator.input",t,void 0,"input key");return{proxy:s,values:a,metaByKey:i}}(this._inputMeta,e=>this._explicitOverrides.add(e));this._inputValues=e.values,this._inputProxy=e.proxy,this._inputMetaByKey=e.metaByKey}_getInputProxy(){return this._ensureInputsScanned(),this._inputProxy}_ensurePropsScanned(){var e;if(this._propMeta)return;let t="string"==typeof(e=this.source)?function(e){let t=uN(e);if(!t.success||!t.ast)return{type:null,args:{}};let i=null;return uG(t.ast,e=>{if(i||"ExpressionStatement"!==e.type&&"VariableDeclaration"!==e.type)return;let t="ExpressionStatement"===e.type?e.expression:e.declarations?.[0]?.init;if(!t||"CallExpression"!==t.type)return;let r=t.callee;r?.type==="Identifier"&&("indicator"!==r.name&&"strategy"!==r.name||(i={type:r.name,args:uW(t.arguments??[],uU(r.name))}))}),i??{type:null,args:{}}}(e):"function"==typeof e?function(e){let t;try{t=hA(`(${e.toString()})`,{ecmaVersion:"latest"})}catch{return{type:null,args:{}}}let i=null;return uG(t,e=>{if(i||"CallExpression"!==e.type)return;let t=e.callee;t?.type==="Identifier"&&("indicator"!==t.name&&"strategy"!==t.name||(i={type:t.name,args:uW(e.arguments??[],uU(t.name))}))}),i??{type:null,args:{}}}(e):{type:null,args:{}};this._declarationType=t.type,this._sourcePropArgs=t.args,this._propMeta="strategy"===t.type?uz:uq;let i=function(e,t,i){let r=new Map,n=[];for(let t of e)r.set(t.name,t),t.mutable&&n.push({key:t.name,type:t.type,defval:t.defval,options:t.options,minval:t.minval,maxval:t.maxval});let{proxy:s,values:a}=uL(n,"Indicator.prop",i,t);return{proxy:s,values:a,propByName:r}}(this._propMeta,this._sourcePropArgs,e=>this._explicitPropOverrides.add(e));this._propValues=i.values,this._propProxy=i.proxy}_getPropProxy(){return this._ensurePropsScanned(),this._propProxy}}var u3=Object.defineProperty,u4=(e,t,i)=>((e,t,i)=>t in e?u3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function u6(e){let t=te(e);return t?1e3*tr(t):864e5}class u5{constructor(e,t,i,r,n,s){this.source=e,this.tickerId=t,this.timeframe=i,this.limit=r,this.sDate=n,this.eDate=s,u4(this,"data",[]),u4(this,"open",[]),u4(this,"high",[]),u4(this,"low",[]),u4(this,"close",[]),u4(this,"volume",[]),u4(this,"hl2",[]),u4(this,"hlc3",[]),u4(this,"ohlc4",[]),u4(this,"hlcc4",[]),u4(this,"openTime",[]),u4(this,"closeTime",[]),u4(this,"_readyPromise",null),u4(this,"_ready",!1),u4(this,"_debugSettings",{ln:!1,debug:!1}),u4(this,"_transpiledCode",null),u4(this,"_currentIndicator",null),u4(this,"_isSecondaryContext",!1),u4(this,"_syminfo"),u4(this,"_chartTimezone",null),u4(this,"_maxLoops",5e5),u4(this,"_fillsOnTickGrid",!0),u4(this,"_alertMode","realtime"),u4(this,"_importResolver",null),u4(this,"_viewportLeft"),u4(this,"_viewportRight"),u4(this,"_usesVisibleRange",!1),u4(this,"_lastRunViewport",{}),u4(this,"_lastResult",null),u4(this,"_lastPineTSCode",null),this._readyPromise=this._loadData(e,t,i,r,n,s),this._readyPromise.catch(()=>{})}get transpiledCode(){return this._transpiledCode}markAsSecondary(e){this._isSecondaryContext=!0,e&&(this._importResolver=e.importResolver)}setTimezone(e){this._chartTimezone=e}setMaxLoops(e){this._maxLoops=e}setFillsOnTickGrid(e){this._fillsOnTickGrid=e}setAlertMode(e){this._alertMode=e}setImportResolver(e){this._importResolver=null==e?null:uQ(e)}setVisibleRange(e,t){this._viewportLeft=e,this._viewportRight=t}usesVisibleRange(){return this._usesVisibleRange}get visibleRangeLeft(){return this._viewportLeft}get visibleRangeRight(){return this._viewportRight}async update(e){let t=e??this._lastPineTSCode;if(!t)throw Error("pine.update(): pineTSCode is required on the first call.");let i=null===this._lastResult,r=this._viewportLeft!==this._lastRunViewport.left||this._viewportRight!==this._lastRunViewport.right;return(i||this._usesVisibleRange&&r)&&(this._lastPineTSCode=t,this._lastRunViewport={left:this._viewportLeft,right:this._viewportRight},this._lastResult=await this.run(t)),this._lastResult}async _loadData(e,t,i,r,n,s){let a=await this.loadMarketData(e,t,i,r,n,s);this.data=a;let o=a.map(e=>e.open),l=a.map(e=>e.close),h=a.map(e=>e.high),c=a.map(e=>e.low),p=a.map(e=>e.volume),u=a.map(e=>(e.high+e.low+e.close)/3),d=a.map(e=>(e.high+e.low)/2),m=a.map(e=>(e.high+e.low+e.open+e.close)/4),f=a.map(e=>(e.high+e.low+e.close+e.close)/4),y=a.map(e=>e.openTime),_=u6(this.timeframe),g=a.map(e=>null!=e.closeTime?e.closeTime:e.openTime+_);if(this.open=o,this.close=l,this.high=h,this.low=c,this.volume=p,this.hl2=d,this.hlc3=u,this.ohlc4=m,this.hlcc4=f,this.openTime=y,this.closeTime=g,e&&e.getSymbolInfo)try{this._syminfo=await e.getSymbolInfo(t)}catch(e){console.warn("Failed to get symbol info, using default values:",e)}return this._ready=!0,!0}setDebugSettings({ln:e,debug:t}){this._debugSettings.ln=e,this._debugSettings.debug=t}async loadMarketData(e,t,i,r,n,s){return Array.isArray(e)?e:e.getMarketData(t,i,r,n,s)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw Error("PineTS is not ready");return this._readyPromise}run(e,t,i){let r=u2.from(e);if(this._currentIndicator=r,!i||!(i>0))return this._runComplete(r,t);{let e=typeof this.eDate>"u"&&!Array.isArray(this.source);return this._runPaginated(r,t,i,e)}}stream(e,t={}){let{live:i=!0,interval:r=1e3}=t,n=t.pageSize||this.data.length,s=u2.from(e);this._currentIndicator=s;let a={data:[],error:[],warning:[],alert:[]},o=!1,l=(e,...t)=>{a[e]&&a[e].forEach(e=>e(...t))};return(async()=>{try{i&&"u">typeof this.eDate&&(this.eDate=Math.max(this.eDate,Date.now()));let e=!Array.isArray(this.source)&&i;for await(let t of this._runPaginated(s,void 0,n,e)){if(o)break;if(null===t){await new Promise(e=>setTimeout(e,r));continue}if(l("data",t),t.warnings&&t.warnings.length>0){for(let e of t.warnings)l("warning",e);t.warnings.length=0}if(t.alerts&&t.alerts.length>0){for(let e of t.alerts)l("alert",e);t.alerts.length=0}if(e&&!o){let e=t.marketData[t.idx],i=e&&e.closeTime<Date.now(),n=t.idx>=t.marketData.length-1;(!i||n)&&await new Promise(e=>setTimeout(e,r))}}}catch(e){l("error",e)}})(),{on:(e,t)=>{a[e]||(a[e]=[]),a[e].push(t)},stop:()=>{o=!0}}}async runPretranspiled(e,t={},i){await this.ready(),i||(i=this.data.length);let r=this._initializeContext(null,t,this._isSecondaryContext);r.pineVersion=e._pineVersion??null,this._transpiledCode=e,r.transpiledFn=e;let n=e._ltfSlices;n&&(r._ltfTruncatedBodies=n);let s=this.data.length-i,a=this.data.length;return a-s>1?(await this._executeIterations(r,e,s,a-1),r._varSnapshot=this._snapshotVarState(r),await this._executeIterations(r,e,a-1,a)):await this._executeIterations(r,e,s,a),r}async _runComplete(e,t){await this.ready(),t||(t=this.data.length),await e.resolveImports(this._importResolver);let i=e.prepare(this._debugSettings);this._usesVisibleRange=i.usesVisibleRange;let r=this._initializeContext(e.source??null,i.inputs,this._isSecondaryContext);r.pineVersion=i.fn._pineVersion??null,this._transpiledCode=i.fn,r.transpiledFn=i.fn,i.ltfSlices&&(r._ltfTruncatedBodies=i.ltfSlices);let n=this.data.length-t,s=this.data.length;return s-n>1?(await this._executeIterations(r,i.fn,n,s-1),r._varSnapshot=this._snapshotVarState(r),await this._executeIterations(r,i.fn,s-1,s)):await this._executeIterations(r,i.fn,n,s),r}async *_runPaginated(e,t,i,r=!1){await this.ready(),t||(t=this.data.length),await e.resolveImports(this._importResolver);let n=e.prepare(this._debugSettings);this._usesVisibleRange=n.usesVisibleRange;let s=this._initializeContext(e.source??null,n.inputs,this._isSecondaryContext);s.pineVersion=n.fn._pineVersion??null,this._transpiledCode=n.fn,s.transpiledFn=n.fn,n.ltfSlices&&(s._ltfTruncatedBodies=n.ltfSlices);let a=this.data.length-t,o=null;for(;;){let e=this.data.length,t=e-a;if(t>0){let n=Math.min(t,i),l=this._getResultLength(s.result),h=a+n;r&&h>=e&&n>1?(await this._executeIterations(s,this._transpiledCode,a,h-1),o=this._snapshotVarState(s),await this._executeIterations(s,this._transpiledCode,h-1,h)):await this._executeIterations(s,this._transpiledCode,a,h),a+=n,yield this._createPageContext(s,l);continue}if(!r||Array.isArray(this.source))break;let n=Date.now(),{newCandles:l,updatedLastCandle:h}=await this._updateMarketData(),c=Date.now()-n;if(0===l&&!h){yield null;continue}if(0===l&&h&&c<1e3&&await new Promise(e=>setTimeout(e,1e3-c)),s.dataVersion++,s.length=this.data.length,this._restoreVarState(s,o),Array.isArray(s.result))s.result.pop();else if("object"==typeof s.result&&null!==s.result)for(let e in s.result)Array.isArray(s.result[e])&&s.result[e].pop();s.data.close.data.pop(),s.data.open.data.pop(),s.data.high.data.pop(),s.data.low.data.pop(),s.data.volume.data.pop(),s.data.hl2.data.pop(),s.data.hlc3.data.pop(),s.data.ohlc4.data.pop(),s.data.hlcc4.data.pop(),s.data.openTime.data.pop(),s.data.closeTime&&s.data.closeTime.data.pop(),s.data.bar_index.data.pop(),a=this.data.length-(l+1),s.rollbackDrawings(a),l>0&&(o=null),s.pine.barstate.setLive()}}_getResultLength(e){if(Array.isArray(e))return e.length;if("object"==typeof e&&null!==e){let t=Object.keys(e);if(t.length>0&&Array.isArray(e[t[0]]))return e[t[0]].length}return 0}_createPageContext(e,t){let i=new o5({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,fullContext:e,inputs:e.inputs});if(i.pineTSCode=e.pineTSCode,i.idx=e.idx,Array.isArray(e.result))i.result=e.result.slice(t);else if("object"==typeof e.result&&null!==e.result)for(let r in i.result={},e.result)Array.isArray(e.result[r])?i.result[r]=e.result[r].slice(t):i.result[r]=e.result[r];else i.result=e.result;return i.plots={...e.plots},i.warnings=e.warnings,i.alerts=e.alerts,i}async _updateMarketData(e){if(Array.isArray(this.source))return{newCandles:0,updatedLastCandle:!1};let t=this.source,i=this.data.length-1,r=this.data[i].openTime;try{let n=await t.getMarketData(this.tickerId,this.timeframe,void 0,r,e);if(!n||0===n.length)return{newCandles:0,updatedLastCandle:!1};let s=!1,a=0;for(let e=0;e<n.length;e++){let t=n[e];t.openTime===r?(this._replaceCandle(i,t),s=!0):t.openTime>r&&(this._appendCandle(t),a++)}return{newCandles:a,updatedLastCandle:s}}catch(e){return console.error("Error updating market data:",e),{newCandles:0,updatedLastCandle:!1}}}_replaceCandle(e,t){this.data[e]=t,this.open[e]=t.open,this.close[e]=t.close,this.high[e]=t.high,this.low[e]=t.low,this.volume[e]=t.volume,this.hl2[e]=(t.high+t.low)/2,this.hlc3[e]=(t.high+t.low+t.close)/3,this.ohlc4[e]=(t.high+t.low+t.open+t.close)/4,this.hlcc4[e]=(t.high+t.low+t.close+t.close)/4,this.openTime[e]=t.openTime,this.closeTime[e]=this._closeTimeOf(t)}_closeTimeOf(e){return null!=e.closeTime?e.closeTime:e.openTime+u6(this.timeframe)}_appendCandle(e){this.data.push(e),this.open.push(e.open),this.close.push(e.close),this.high.push(e.high),this.low.push(e.low),this.volume.push(e.volume),this.hl2.push((e.high+e.low)/2),this.hlc3.push((e.high+e.low+e.close)/3),this.ohlc4.push((e.high+e.low+e.open+e.close)/4),this.hlcc4.push((e.high+e.low+e.close+e.close)/4),this.openTime.push(e.openTime),this.closeTime.push(this._closeTimeOf(e))}async updateTail(e){if(0===this.data.length||Array.isArray(this.source))return!1;let{newCandles:t,updatedLastCandle:i}=await this._updateMarketData();if(0===t&&!i)return!1;let r=e._varSnapshot;r?(this._restoreVarState(e,r),this._popLastBar(e)):this._removeLastResult(e),e.dataVersion=(e.dataVersion||0)+1,e.length=this.data.length;let n=this.data.length-(t+1);e.rollbackDrawings(n);let s=this.data.length;return n<s-1?(await this._executeIterations(e,this._transpiledCode,n,s-1),e._varSnapshot=this._snapshotVarState(e),await this._executeIterations(e,this._transpiledCode,s-1,s)):await this._executeIterations(e,this._transpiledCode,n,s),!0}_popLastBar(e){if(Array.isArray(e.result))e.result.pop();else if("object"==typeof e.result&&null!==e.result)for(let t in e.result)Array.isArray(e.result[t])&&e.result[t].pop();e.data.close.data.pop(),e.data.open.data.pop(),e.data.high.data.pop(),e.data.low.data.pop(),e.data.volume.data.pop(),e.data.hl2.data.pop(),e.data.hlc3.data.pop(),e.data.ohlc4.data.pop(),e.data.hlcc4.data.pop(),e.data.openTime.data.pop(),e.data.closeTime&&e.data.closeTime.data.pop(),e.data.bar_index.data.pop()}_removeLastResult(e){this._popLastBar(e);let t=["const","var","let","params"],i=e=>{for(let i of t)if(e[i])for(let t in e[i]){let r=e[i][t];r instanceof m?r.data.pop():Array.isArray(r)&&r.pop()}};i(e),e.lctx&&e.lctx.forEach(e=>i(e))}_snapshotVarState(e){let t=["const","var","let","params"],i={main:{},lctx:[]},r=e=>{let i={};for(let r of t)if(e[r])for(let t in i[r]={},e[r]){let n=e[r][t];if(n instanceof m){let e=n.data.length,s=e>0?n.data[e-1]:void 0;i[r][t]={len:e,lastVal:s}}}return i};if(i.main=r(e),e.lctx){let t=[];e.lctx.forEach(e=>t.push(r(e))),i.lctx=t}return i.strategy=function(e){if(!e)return null;let t={};for(let i of Object.keys(e))"config"===i||"closedtrades"===i||(t[i]=n6(e[i]));return{fields:t,closedtradesLength:e.closedtrades.length}}(e.strategy),i.resultLength=this._getResultLength(e.result),i.dataLength=e.data.close?.data?.length??0,i}_restoreVarState(e,t){if(!t)return;let i=["const","var","let","params"],r=(e,t)=>{for(let r of i)if(!(!t[r]||!e[r]))for(let i in t[r]){let n=e[r][i],s=t[r][i];n instanceof m&&s&&"number"==typeof s.len&&(n.data.length>s.len&&(n.data.length=s.len),s.len>0&&void 0!==s.lastVal&&!n.varip&&(n.data[s.len-1]=s.lastVal))}};if(r(e,t.main),e.lctx&&t.lctx){let i=0;e.lctx.forEach(e=>{t.lctx[i]&&r(e,t.lctx[i]),i++})}var n=e.strategy,s=t.strategy;if(!(!n||!s)){for(let e of Object.keys(n))"config"===e||"closedtrades"===e||Object.prototype.hasOwnProperty.call(s.fields,e)||delete n[e];for(let e of(n.closedtrades.length>s.closedtradesLength&&(n.closedtrades.length=s.closedtradesLength),Object.keys(s.fields)))n[e]=n6(s.fields[e])}}_initializeContext(e,t={},i=!1){let r=new o5({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,inputs:t});r.pine.syminfo=o8(this._syminfo);let n=i3(String(this.tickerId??"")).modifier;return r.chartStyle="heikinashi"===n?"heikinashi":"standard",this._syminfo&&"heikinashi"===n&&(r.pine.syminfo=o8({...this._syminfo,tickerid:i5(String(this._syminfo.tickerid??this.tickerId),"heikinashi")})),this._chartTimezone&&(r.chartTimezone=this._chartTimezone),r.viewportLeft=this._viewportLeft,r.viewportRight=this._viewportRight,r.__maxLoops=this._maxLoops,r._alertMode=this._alertMode,r._fillsOnTickGrid=this._fillsOnTickGrid,r.importResolver=this._importResolver,r._propOverrides=this._currentIndicator?.getRuntimePropOverrides()??{},r.pineTSCode=e,r.isSecondaryContext=i,r.data.close=new m([]),r.data.open=new m([]),r.data.high=new m([]),r.data.low=new m([]),r.data.volume=new m([]),r.data.hl2=new m([]),r.data.hlc3=new m([]),r.data.ohlc4=new m([]),r.data.hlcc4=new m([]),r.data.openTime=new m([]),r.data.closeTime=new m([]),r.length=this.data.length,r}async _processBarWithOrderFills(e,t,i){let r=e.strategy,n=e.data,s=n.close.data.length-1,a={open:n.open.data[s],high:n.high.data[s],low:n.low.data[s],close:n.close.data[s]},o=i??a,l=(e,t,i,r)=>{n.open.data[s]=e,n.high.data[s]=t,n.low.data[s]=i,n.close.data[s]=r},h=nu(a.open,a.high,a.low,a.close),c=null;for(let i=0;i<h.length;i++){let n=0===i?h[0]:h[i-1],s=h[i];l(n,Math.max(n,s),Math.min(n,s),s);let a=r._fillCount??0;for(let t of(e._excSeg=0===i?{offset:0,scale:0}:{offset:i-1,scale:1/3},n4(e),e._excSeg=void 0,r.opentrades))t._intrabarEntry?.bar===e.idx&&(t._intrabarEntry=void 0);if(i===h.length-1||(r._fillCount??0)===a)continue;l(o.open,o.high,o.low,o.close),c||((c=this._snapshotVarState(e)).strategy=null);let p=new Map(Object.entries(e.plots??{}).map(([e,t])=>[e,t?.data?.length??0])),u=new Set(r.pending_orders);for(let i of(e._execTick=(e._execTick||0)+1,e._fillPointPrice=s,await t(e),e._fillPointPrice=void 0,r.pending_orders))u.has(i)||i.bar!==e.idx||(i.bar=e.idx-1);for(let t of Object.keys(e.plots??{})){let i=p.get(t);void 0===i?delete e.plots[t]:e.plots[t]?.data?.length>i&&(e.plots[t].data.length=i)}e.rollbackDrawings(e.idx),this._restoreVarState(e,c)}l(a.open,a.high,a.low,a.close),c&&(e._execTick=(e._execTick||0)+1)}_snapBarForBroker(e){if(!this._fillsOnTickGrid||!e.strategy)return null;let t=e.pine?.syminfo?.mintick;if(!t||t<=0)return null;let i=e.data,r=i.close.data.length-1,n={open:i.open.data[r],high:i.high.data[r],low:i.low.data[r],close:i.close.data[r]},s={open:r6(n.open,t),high:r6(n.high,t),low:r6(n.low,t),close:r6(n.close,t)};return s.open===n.open&&s.high===n.high&&s.low===n.low&&s.close===n.close?null:(this._setBar(e,s),e._rawBar=n,n)}_restoreRawBar(e,t){this._setBar(e,t),e._rawBar=void 0}_setBar(e,t){let i=e.data,r=i.close.data.length-1;i.open.data[r]=t.open,i.high.data[r]=t.high,i.low.data[r]=t.low,i.close.data[r]=t.close}async _executeIterations(e,t,i,r){let n=["const","var","let","params"];for(let s=i;s<r;s++){if(e.idx=s,e._execTick=(e._execTick||0)+1,e.data.close.data.push(this.close[s]),e.data.open.data.push(this.open[s]),e.data.high.data.push(this.high[s]),e.data.low.data.push(this.low[s]),e.data.volume.data.push(this.volume[s]),e.data.hl2.data.push(this.hl2[s]),e.data.hlc3.data.push(this.hlc3[s]),e.data.ohlc4.data.push(this.ohlc4[s]),e.data.hlcc4.data.push(this.hlcc4[s]),e.data.openTime.data.push(this.openTime[s]),e.data.closeTime.data.push(this.closeTime[s]),e.data.bar_index.data.push(s),e.strategy){let i=this._snapBarForBroker(e);nZ(e),function(e){let t=e.strategy,i=t?.risk_rules;if(!i||0===Object.keys(i).length)return;let r=nP(e),n=function(e){let t=m.from(e.data.openTime).get(0),i=m.from(e.data.closeTime).get(0);if(Number.isFinite(i)&&i-t>=86399e3)return String(t);let r=e.pine?.syminfo?.timezone||"UTC",n=nD.get(r);if(!n){try{n=new Intl.DateTimeFormat("en-CA",{timeZone:r,year:"numeric",month:"2-digit",day:"2-digit"})}catch{n=new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"})}nD.set(r,n)}return n.format(new Date(t))}(e);if(n!==r.day){if(void 0!==r.blockFrom&&void 0===r.blockTo&&(r.blockTo=e.idx-1),void 0!==r.day){let n=t.equity;i.max_cons_loss_days&&void 0===r.haltedFrom&&(r.consLossDays=n<r.prevDayEndEquity-1e-9?r.consLossDays+1:0,r.consLossDays>=i.max_cons_loss_days.count&&(0!==t.position_size&&t.pending_orders.push({id:nM.consDays,direction:-Math.sign(t.position_size),qty:Math.abs(t.position_size),type:"market",bar:e.idx-1,time:m.from(e.data.openTime).get(0),status:"pending",comment:nM.consDays,_risk:!0}),r.haltedFrom=e.idx)),r.prevDayEndEquity=n}r.day=n,r.dayStartEquity=t.equity,r.dayMaxEquity=t.equity,r.dayFills=0,r.dayStartBar=e.idx}}(e),function(e){let t=e.strategy;if(!t)return;let i=t._pending_close_mc;if(i&&(t._pending_close_mc=null,0!==t.opentrades.length&&Math.sign(t.position_size)===i.dir&&(nW(e,-1),nq(e,Math.min(i.qty,Math.abs(t.position_size)),nk(e,-i.dir,i.price),i.time,{exitId:n2,exitComment:"Margin call",forced:!0}),Math.abs(t.position_size)>1e-9))){for(let e of t.pending_orders)"pending"!==e.status||(e.category??"entry")!=="entry"||e._isReversalEntry||nN(e.direction)!==i.dir||(e.status="cancelled");t.pending_orders=t.pending_orders.filter(e=>"pending"===e.status)}}(e),e.strategy.config?.calc_on_order_fills?await this._processBarWithOrderFills(e,t,i):n4(e),function(e){if(!e.strategy)return;let t=e.strategy,i=m.from(e.data.close).get(0);nU(e,i),e._exc?.bar!==e.idx&&nZ(e),function(e){let t=e.strategy,i=e.pine?.syminfo?.pointvalue??1,r=e._exc,n=r?.bar===e.idx&&!r.finalized;for(let r of t.opentrades){let t=Math.sign(r.size);n&&nG(e,r,t,r._obsFrom??-.5,3,!0),r._obsFrom=3;let s=nH(r._fav,r._adv,Math.abs(r.size),i,r.commission??0);r.max_runup=s.runup,r.max_drawdown=s.drawdown}for(let i of t._ledger_entries??[])n&&nG(e,i,i._dir??Math.sign(t.position_size),i._obsFrom??-.5,3,!0),i._obsFrom=3}(e),function(e){let t=e.strategy,i=e._exc;if(!i||i.bar!==e.idx||i.finalized)return;let r=e.pine?.syminfo?.pointvalue??1,n=new Map;for(let e of i.start.lots)n.set(e.ref,{dir:e.dir,qty:e.qty,entry:e.entry,comm:e.comm});let s=i.start.netprofit,a=e=>{let i=0,a=0;for(let t of n.values())i+=(e-t.entry)*t.dir*t.qty*r,a+=t.comm;let o=t.initial_capital+s+i,l=t.initial_capital+s+a;t.equity_peak=Math.max(t.equity_peak,Math.min(l,o+a)),t.equity_trough=Math.min(t.equity_trough,Math.max(l-a,o));let h=t.equity_peak-o,c=o-t.equity_trough;h>t.max_drawdown&&(t.max_drawdown=h),c>t.max_runup&&(t.max_runup=c),t.equity_peak>0&&(t.max_drawdown_percent_value=Math.max(t.max_drawdown_percent_value,100*h/t.equity_peak)),o>0&&(t.max_runup_percent_value=Math.max(t.max_runup_percent_value,100*c/o))},o=e=>{if(e.add){let t=n.get(e.add.ref);t?(t.entry=(t.entry*t.qty+e.add.entry*e.add.qty)/(t.qty+e.add.qty),t.qty+=e.add.qty,t.comm+=e.add.comm):n.set(e.add.ref,{dir:e.add.dir,qty:e.add.qty,entry:e.add.entry,comm:e.add.comm})}if(e.remove){let t=n.get(e.remove.ref);t&&(t.qty-=e.remove.qty,t.comm-=e.remove.comm,t.qty<=1e-12&&n.delete(e.remove.ref))}s+=e.np};for(let e of i.pre)a(e);for(let e of[...i.path.map((e,t)=>({at:t,price:e,vertex:!0,seq:-1})),...i.events.map(e=>({...e,vertex:!1}))].sort((e,t)=>e.at-t.at||Number(e.vertex)-Number(t.vertex)||e.seq-t.seq))e.vertex||o(e),a(e.price)}(e),e._exc?.bar===e.idx&&(e._exc.finalized=!0);let r=m.from(e.data.openTime).get(0);if(Number.isFinite(r)){let e=new Date(r),i=12*e.getUTCFullYear()+e.getUTCMonth(),n=t._monthly_equity??(t._monthly_equity=[]);t._last_month_key===i&&n.length>0?n[n.length-1]=t.equity:(n.push(t.equity),t._last_month_key=i)}}(e),i&&this._restoreRawBar(e,i)}let i=await t(e);if(e.strategy){let t=this._snapBarForBroker(e);n$(e),e.strategy._pending_close_mc||n3(e,"close"),n$(e),function(e){let t=e.strategy;if(!t||0===t.pending_orders.length)return;let i=!0===t.config.process_orders_on_close,r=m.from(e.data.close).get(0),n=m.from(e.data.openTime).get(0);nW(e,3);let s=e=>"exit"===e.category&&"market"===e.type&&void 0===e.profit&&void 0===e.loss&&void 0===e.limit&&void 0===e.stop&&void 0===e.trail_price&&void 0===e.trail_points;for(let[a,o]of t.pending_orders.entries())if("pending"===o.status&&o.bar===e.idx)if(s(o)){if(!i&&!o.immediately)continue;let s=t.opentrades.filter(e=>!o.from_entry||e.entry_id===o.from_entry);if(o._intended_trade_ids){let e=new Set(o._intended_trade_ids);s=s.filter(t=>e.has(t.id))}if(0===s.length){o.status="cancelled";continue}if(!i){let i=Math.sign(s[0].size);if(t.pending_orders.slice(0,a).some(t=>"pending"===t.status&&t.bar===e.idx&&(t.category??"entry")==="entry"&&"market"===t.type&&nN(t.direction)===-i)){o.status="cancelled";continue}}let l=s.reduce((e,t)=>e+Math.abs(t.size),0),h=l;o.qty&&o.qty>0?h=Math.min(o.qty,l):o.qty_percent&&o.qty_percent>0&&(h=np(e,l,o.qty_percent));let c=nk(e,-Math.sign(s[0].size),r);nQ(e,o.from_entry,h,c,n,{exitId:o.id,exitComment:o.comment}),o.status="filled",o.fill_price=c,o.fill_bar=e.idx,o.fill_time=n,nj(e,c)}else i&&(o.category??"entry")==="entry"&&"market"===o.type||i&&(o.category??"entry")!=="exit"&&function(e,t){let i=nN(e.direction),r=void 0===e.limit||(1===i?t<=e.limit:t>=e.limit),n=void 0===e.stop||(1===i?t>=e.stop:t<=e.stop);return("limit"===e.type||"stop"===e.type||"stop-limit"===e.type)&&r&&n}(o,r)?(nU(e,r),nE(e,o,r,n,r)):i&&(o.category??"entry")==="exit"&&function(e,t,i,r){let n=e.strategy,s=e.pine?.syminfo?.mintick??.01,a=n.opentrades.filter(e=>!t.from_entry||e.entry_id===t.from_entry);if(0===a.length)return;let o=Math.sign(a[0].size),l=nX(e,t,a),h=l.total,c=!1;for(let p of a){if(h<=1e-9)break;if(p._exits_filled?.has(t.id)||!((l.perTrade.get(p)??0)>1e-9))continue;let{tp:a,sl:u}=nf(t,p._bracket_entry??p.entry_price,o,s),d=void 0!==u&&(1===o?i<=u:i>=u),m=!d&&void 0!==a&&(1===o?i>=a:i<=a);if(!d&&!m)continue;let f=Math.min(l.perTrade.get(p)??0,h),y=d?"loss":"profit",_="loss"===y?nk(e,-o,i):i,g="profit"===y?t.comment_profit??t.comment:t.comment_loss??t.comment;nQ(e,t.from_entry,f,_,r,{triggerKind:y,exitId:t.id,exitComment:g},p.id),t.oca_name&&"reduce"===t.oca_type&&nw(n,t,f),(p._exits_filled??(p._exits_filled=new Set)).add(t.id),h-=f,c=!0,nj(e,_)}let p=n.opentrades.some(e=>(!t.from_entry||e.entry_id===t.from_entry)&&!e._exits_filled?.has(t.id));c&&(!p||h<=1e-9)&&(t.status="filled",t.fill_bar=e.idx,t.fill_time=r)}(e,o,r,n);t.pending_orders=t.pending_orders.filter(e=>"pending"===e.status),nU(e,r),e.strategy}(e),t&&this._restoreRawBar(e,t)}if("object"==typeof i)for(let t in"object"!=typeof e.result&&(e.result={}),i){let r;void 0===e.result[t]&&(e.result[t]=[]),r=i[t]instanceof m?i[t].get(0):Array.isArray(i[t])?i[t][i[t].length-1]:i[t],e.result[t].push(r)}else Array.isArray(e.result)||(e.result=[]),e.result.push(i);for(let t of e._drawingHelpers)t.syncToPlot&&t.syncToPlot();let r=e=>{for(let t of n)if(e[t])for(let i in e[t]){let r=e[t][i];if(r instanceof m){let e=r.get(0);r.data.push(e)}else if(Array.isArray(r)){let e=r[r.length-1];r.push(e)}}};r(e),e.lctx&&e.lctx.forEach(e=>r(e))}e.strategy&&function(e){let t=e?.strategy;if(!t)return;t.cagr=function(e){let t=e?.strategy;if(!t)return NaN;let i=e?.marketData;if(!Array.isArray(i)||0===i.length)return NaN;let r=i[0]?.openTime,n=i[i.length-1]?.openTime;if(!Number.isFinite(r)||!Number.isFinite(n))return NaN;let s=t.initial_capital??0,a=s+(t.netprofit??0),o=(n-r)/864e5;return!(o<1)&&Number.isFinite(s)&&Number.isFinite(a)&&0!==s?100*(Math.pow(a/s,1/(o/365))-1):NaN}(e),function(e){let t=e?.strategy;if(!t)return;let i=t._first_entry_price,r=e?.marketData,n=Array.isArray(r)&&r.length>0?r[r.length-1]?.close:NaN;if(!Number.isFinite(i)||!Number.isFinite(n)||0===i){t.buy_and_hold_pnl=NaN,t.buy_and_hold_per_gain=NaN,t.strategy_outperformance=NaN;return}let s=(n-i)/i;t.buy_and_hold_per_gain=100*s,t.buy_and_hold_pnl=(t.initial_capital??0)*s,t.strategy_outperformance=(t.netprofit??0)-t.buy_and_hold_pnl}(e);let i=t._monthly_equity??[],r=[t.initial_capital,...i],n=[];for(let e=1;e<r.length;e++){let t=r[e-1];0!==t&&Number.isFinite(t)&&Number.isFinite(r[e])&&n.push(r[e]/t-1)}if(n.length<2){t.sharpe_ratio=0,t.sortino_ratio=0;return}let s=(t.config.risk_free_rate??2)/100/12,a=n.length,o=n.reduce((e,t)=>e+t,0)/a,l=o-s,h=Math.sqrt(n.reduce((e,t)=>e+(t-o)**2,0)/a),c=Math.sqrt(n.reduce((e,t)=>e+Math.min(0,t-s)**2,0)/a);t.sharpe_ratio=h>0?l/h:0,t.sortino_ratio=c>0?l/c:0}(e)}}let u9=e=>"D"===e.unit||"W"===e.unit||"M"===e.unit,u8=e=>u9(e)&&("D"!==e.unit||1!==e.multiplier);function u7(e,t){let i=te(e),r=te(t);return!i||!r||u8(i)?1/0:tr(i)/tr(r)}function de(e){let t=e[0],i=e[e.length-1],r=t.high,n=t.low,s=0,a=0,o=0,l=0,h=0;for(let t=0;t<e.length;t++){let i=e[t];i.high>r&&(r=i.high),i.low<n&&(n=i.low),s+=i.volume,a+=i.quoteAssetVolume,o+=i.numberOfTrades,l+=i.takerBuyBaseAssetVolume,h+=i.takerBuyQuoteAssetVolume}return{openTime:t.openTime,open:t.open,high:r,low:n,close:i.close,volume:s,closeTime:i.closeTime,quoteAssetVolume:a,numberOfTrades:o,takerBuyBaseAssetVolume:l,takerBuyQuoteAssetVolume:h,ignore:0}}var dt=Object.defineProperty,di=(e,t,i)=>((e,t,i)=>t in e?dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class dr{constructor(e){di(this,"_configured"),di(this,"_requiresApiKey"),di(this,"_providerName"),di(this,"_aggregationSubTimeframe",null),this._requiresApiKey=e.requiresApiKey,this._providerName=e.providerName,this._configured=!e.requiresApiKey}ensureConfigured(){if(!this._configured)throw Error(`${this._providerName} requires configuration before use. Call Provider.${this._providerName}.configure({ apiKey: '...' }) or instantiate directly: new ${this._providerName}Provider({ apiKey: '...' })`)}configure(e){this._configured=!0}get isConfigured(){return this._configured}normalizeCloseTime(e){for(let t=0;t<e.length-1;t++)e[t].closeTime=e[t+1].openTime;e.length>0&&(e[e.length-1].closeTime=e[e.length-1].closeTime+1)}setAggregationSubTimeframe(e){this._aggregationSubTimeframe=e}getSupportedTimeframes(){return new Set(["1S","5S","10S","15S","30S","1","3","5","15","30","45","60","120","180","240","D","W","M"])}aggregatesOnCalendarGrid(){return!1}async getMarketData(e,t,i,r,n){e=i6(e);let s=ti(t)??t,a=this.getSupportedTimeframes();if(a.has(s))return this._getMarketDataNative(e,s,i,r,n);let o=this._aggregationSubTimeframe,l=o&&a.has(o)?o:function(e,t){let i=te(e);if(!i)return null;if(u8(i))return t.has("D")?"D":null;let r=tr(i),n=null,s=0;for(let e of t){let t=te(e);if(!t||u9(t))continue;let i=tr(t);i<r&&r%i==0&&i>s&&(n=e,s=i)}return n}(s,a);if(!l)return console.error(`${this._providerName}: Timeframe '${t}' is not supported and no valid sub-timeframe found for aggregation.`),[];let h=this._computeSubLimit(s,l,i),c=this.aggregatesOnCalendarGrid(),p=te(s),u=c&&void 0!==r&&p?ts(r,p):r,d=await this._getMarketDataNative(e,l,h,u,n);if(0===d.length)return[];let m=function(e,t,i,r={}){if(0===e.length)return[];let n=te(t);return n?r.calendarGrid||u8(n)?function(e,t,i){let r=[],n=[],s=NaN,a=()=>{let e=de(n);i&&(e.openTime=s,e.closeTime=function(e,t){let i=t.multiplier,r=new Date(e),n=r.getUTCFullYear();switch(t.unit){case"S":case"":{let i=(Math.floor(e/864e5)+1)*864e5;return Math.min(e+1e3*tr(t),i)}case"D":return Math.min(e+864e5*i,Date.UTC(n+1,0,1));case"W":return Math.min(e+6048e5*i,tn(n+1));case"M":return Math.min(Date.UTC(n,r.getUTCMonth()+i,1),Date.UTC(n+1,0,1))}}(s,t)),r.push(e)};for(let i of e){let e=ts(i.openTime,t);n.length>0&&e!==s&&(a(),n=[]),s=e,n.push(i)}return n.length>0&&a(),r}(e,n,!!r.calendarGrid):function(e,t){if(0===e.length)return[];let i=[],r=[e[0]],n=function(e){if(e.length<2)return 0;let t=Math.min(e.length-1,20),i=1/0;for(let r=0;r<t;r++){let t=e[r+1].openTime-e[r].openTime;t>0&&t<i&&(i=t)}return i===1/0?0:i}(e),s=n>0?1.5*n:0;for(let n=1;n<e.length;n++){let a=e[n].openTime-e[n-1].openTime;(s>0&&a>s||r.length>=t)&&(i.push(de(r)),r=[]),r.push(e[n])}return r.length>0&&i.push(de(r)),i}(e,u7(t,i)):[]}(d,s,l,{calendarGrid:c});return i&&i>0&&m.length>i?m.slice(m.length-i):m}_computeSubLimit(e,t,i){if(!i)return;let r=u7(e,t);if(r===1/0){let r=function(e,t){let i=te(e),r=te(t);return i&&r?tr(i)/tr(r):1}(e,t);return Math.ceil(i*r)+2*Math.ceil(r)}return Math.ceil(i*r)+Math.ceil(r)}}var dn=Object.defineProperty,ds=(e,t,i)=>((e,t,i)=>t in e?dn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let da="https://api.binance.com/api/v3",dl="https://api.binance.us/api/v3",dh={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",45:null,60:"1h",120:"2h",180:null,240:"4h","4H":"4h","1D":"1d",D:"1d","1W":"1w",W:"1w","1M":"1M",M:"1M"};class dc{constructor(e=3e5){ds(this,"cache"),ds(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>`${e}:${t}`).join("|")}get(e){let t=this.generateKey(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.cacheDuration?(this.cache.delete(t),null):i.data:null}set(e,t){let i=this.generateKey(e);this.cache.set(i,{data:t,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())e-i.timestamp>this.cacheDuration&&this.cache.delete(t)}}class dp extends dr{constructor(){super({requiresApiKey:!1,providerName:"Binance"}),ds(this,"cacheManager"),ds(this,"activeApiUrl",null),this.cacheManager=new dc(3e5)}async getBaseUrl(){if(this.activeApiUrl)return this.activeApiUrl;try{let e=new AbortController,t=setTimeout(()=>e.abort(),5e3),i=await fetch(`${da}/ping`,{signal:e.signal});if(clearTimeout(t),i.ok)return this.activeApiUrl=da,this.activeApiUrl}catch{}try{let e=new AbortController,t=setTimeout(()=>e.abort(),5e3),i=await fetch(`${dl}/ping`,{signal:e.signal});if(clearTimeout(t),i.ok)return this.activeApiUrl=dl,this.activeApiUrl}catch{}return da}async _fetchRawChunk(e,t,i,r,n){let s=dh[t.toUpperCase()];if(!s)return console.error(`Unsupported timeframe: ${t}`),[];let a=`${await this.getBaseUrl()}/klines?symbol=${e}&interval=${s}`;i&&(a+=`&limit=${Math.min(i,1e3)}`),r&&(a+=`&startTime=${r}`),n&&(a+=`&endTime=${n}`);let o=await fetch(a);if(!o.ok)throw Error(`HTTP error! status: ${o.status}`);return(await o.json()).map(e=>({openTime:parseInt(e[0]),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),closeTime:parseInt(e[6]),quoteAssetVolume:parseFloat(e[7]),numberOfTrades:parseInt(e[8]),takerBuyBaseAssetVolume:parseFloat(e[9]),takerBuyQuoteAssetVolume:parseFloat(e[10]),ignore:e[11]}))}async getMarketDataInterval(e,t,i,r){try{let n=dh[t.toUpperCase()];if(!n)return console.error(`Unsupported timeframe: ${t}`),[];let s=[],a=i,o=ta[n];if(!o)return console.error(`Duration not defined for interval: ${n}`),[];for(;a<r;){let i=Math.min(a+1e3*o,r),n=await this._fetchRawChunk(e,t,1e3,a,i);if(0===n.length){let[i]=await this._fetchRawChunk(e,t,1,a);if(!i||i.openTime>=r||i.openTime<=a)break;a=i.openTime;continue}s=s.concat(n),a=n[n.length-1].closeTime+1}return this.normalizeCloseTime(s),s}catch(e){return console.error("Error in getMarketDataInterval:",e),[]}}async getMarketDataBackwards(e,t,i,r){let n=i,s=[],a=r,o=0,l=Math.ceil(i/1e3)+5;for(;n>0&&o<l;){o++;let i=Math.min(n,1e3),r=await this._fetchRawChunk(e,t,i,void 0,a);if(0===r.length||(s=r.concat(s),n-=r.length,a=r[0].openTime-1,r.length<i))break}return this.normalizeCloseTime(s),s}getSupportedTimeframes(){return new Set(["1","3","5","15","30","60","120","240","D","W","M"])}aggregatesOnCalendarGrid(){return!0}async _getMarketDataNative(e,t,i,r,n){try{let s=void 0!==n,a={tickerId:e,timeframe:t,limit:i,sDate:r,eDate:n};if(s){let e=this.cacheManager.get(a);if(e)return e}if(!dh[t.toUpperCase()])return console.error(`Unsupported timeframe: ${t}`),[];if(this.shouldPaginate(i,r,n)){if(r&&n){let s=await this.getMarketDataInterval(e,t,r,n),o=i?s.slice(0,i):s;return this.cacheManager.set(a,o),o}else if(i&&i>1e3){let r=await this.getMarketDataBackwards(e,t,i,n);return this.cacheManager.set(a,r),r}}let o=await this._fetchRawChunk(e,t,i,r,n);return this.normalizeCloseTime(o),s&&this.cacheManager.set(a,o),o}catch(e){return console.error("Error in binance.klines:",e),[]}}shouldPaginate(e,t,i){return!!e&&e>1e3||!!(t&&i)}async getSymbolInfo(e){e=i6(e);try{let t="crypto",i=await this.getBaseUrl(),r=e,n="";e.endsWith(".P")?(t="futures",r=e.replace(".P",""),i="https://fapi.binance.com/fapi/v1",n="Perpetual"):e.includes("_")&&(t="futures",r=e,i="https://dapi.binance.com/dapi/v1",n="Delivery");let s="crypto"===t?`${i}/exchangeInfo?symbol=${r}`:`${i}/exchangeInfo`,a=await fetch(s);if(!a.ok)throw Error(`HTTP error! status: ${a.status}`);let o=(await a.json()).symbols;if(!o||0===o.length)return console.error(`Symbol ${e} not found`),null;let l="futures"===t?o.find(e=>e.symbol===r):o[0];if(!l)return console.error(`Symbol ${r} not found in exchange info`),null;let h=l.filters?.find(e=>"PRICE_FILTER"===e.filterType),c=l.filters?.find(e=>"LOT_SIZE"===e.filterType),p=h?parseFloat(h.tickSize):.01,u=c?parseFloat(c.minQty):0,d=Math.round(1/p),m=l.baseAsset,f=l.quoteAsset,y=n?` ${n}`:"",_=`${m} / ${f}${y}`;return{ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",root:e,description:_,type:t,main_tickerid:`BINANCE:${e}`,current_contract:n,isin:"",basecurrency:m,currency:f,timezone:"Etc/UTC",country:"",mintick:p,pricescale:d,minmove:1,pointvalue:l.contractSize||1,mincontract:u,session:"regular",volumetype:"base",expiration_date:l.deliveryDate||NaN,employees:NaN,industry:"",sector:"",shareholders:NaN,shares_outstanding_float:NaN,shares_outstanding_total:NaN,recommendations_buy:NaN,recommendations_buy_strong:NaN,recommendations_date:NaN,recommendations_hold:NaN,recommendations_sell:NaN,recommendations_sell_strong:NaN,recommendations_total:NaN,target_price_average:NaN,target_price_date:NaN,target_price_estimates:NaN,target_price_high:NaN,target_price_low:NaN,target_price_median:NaN}}catch(e){return console.error("Error in binance.exchangeInfo:",e),null}}}var du=Object.defineProperty,dd=(e,t,i)=>((e,t,i)=>t in e?du(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let dm=new Set(["USD","EUR","GBP","JPY","CHF","AUD","CAD","NZD","SEK","NOK","DKK","SGD","HKD","KRW","MXN","ZAR","TRY","BRL","INR","CNY","PLN","CZK","HUF","ILS","THB","TWD","PHP","IDR","MYR","RUB","CLP","COP"]),df={"1D":{endpoint:"/stable/historical-price-eod/full",type:"daily"},D:{endpoint:"/stable/historical-price-eod/full",type:"daily"},1:{endpoint:"/stable/historical-chart/1min",interval:"1min",type:"intraday"},5:{endpoint:"/stable/historical-chart/5min",interval:"5min",type:"intraday"},15:{endpoint:"/stable/historical-chart/15min",interval:"15min",type:"intraday"},30:{endpoint:"/stable/historical-chart/30min",interval:"30min",type:"intraday"},60:{endpoint:"/stable/historical-chart/1hour",interval:"1hour",type:"intraday"},240:{endpoint:"/stable/historical-chart/4hour",interval:"4hour",type:"intraday"},"4H":{endpoint:"/stable/historical-chart/4hour",interval:"4hour",type:"intraday"}},dy={NASDAQ:"America/New_York",NYSE:"America/New_York",AMEX:"America/New_York",NYSEArca:"America/New_York",BATS:"America/New_York",OTC:"America/New_York",PNK:"America/New_York",TSX:"America/Toronto",TSXV:"America/Toronto",LSE:"Europe/London",EURONEXT:"Europe/Paris",XETRA:"Europe/Berlin",JPX:"Asia/Tokyo",HKSE:"Asia/Hong_Kong",SSE:"Asia/Shanghai",SHZ:"Asia/Shanghai",ASX:"Australia/Sydney",NSE:"Asia/Kolkata",BSE:"Asia/Kolkata",KRX:"Asia/Seoul",CRYPTO:"Etc/UTC"},d_={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",NYSEArca:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",PNK:"0930-1600",TSX:"0930-1600",TSXV:"0930-1600",LSE:"0800-1630",EURONEXT:"0900-1730",XETRA:"0900-1730",JPX:"0900-1530",HKSE:"0930-1600",SSE:"0930-1500",SHZ:"0930-1500",ASX:"1000-1600",NSE:"0915-1530",BSE:"0915-1530",KRX:"0900-1530",CRYPTO:"24x7"},dg={daily:{periodType:"day",multiplier:1},"1min":{periodType:"minute",multiplier:1},"5min":{periodType:"minute",multiplier:5},"15min":{periodType:"minute",multiplier:15},"30min":{periodType:"minute",multiplier:30},"1hour":{periodType:"hour",multiplier:1},"4hour":{periodType:"hour",multiplier:4}};class dx extends dr{constructor(e){super({requiresApiKey:!0,providerName:"FMP"}),dd(this,"_apiKey",null),dd(this,"_baseUrl","https://financialmodelingprep.com"),dd(this,"_profileCache",new Map),dd(this,"_symbolInfoCache",new Map),dd(this,"_mintickCache",new Map),e?.apiKey&&this.configure(e)}configure(e){super.configure(e),this._apiKey=e.apiKey,e.baseUrl&&(this._baseUrl=e.baseUrl)}getSupportedTimeframes(){return new Set(["1","5","15","30","60","240","D"])}async _getMarketDataNative(e,t,i,r,n){this.ensureConfigured();try{let s,a=df[t.toUpperCase()]||df[t];if(!a)return console.error(`FMP: Unsupported timeframe: ${t}`),[];if((s="intraday"===a.type?await this._fetchIntradayData(e,a.endpoint,a.interval,r,n,i):await this._fetchDailyData(e,r,n,i)).length>0&&!this._mintickCache.has(e)){let t=this._estimateMintick(s);void 0!==t&&this._mintickCache.set(e,t)}return s}catch(e){return console.error("Error in FMPProvider.getMarketData:",e),[]}}async _fetchDailyData(e,t,i,r){let n=`${this._baseUrl}/stable/historical-price-eod/full?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`;t&&(n+=`&from=${this._msToDateStr(t)}`),i&&(n+=`&to=${this._msToDateStr(i)}`);let s=await fetch(n);if(!s.ok){let e=await s.text();throw Error(`FMP HTTP ${s.status}: ${e}`)}let a=await s.json();if(!Array.isArray(a)||0===a.length)return[];a.reverse();let o=r&&r>0&&r<a.length?a.slice(a.length-r):a,{session:l,timezone:h}=await this._resolveSessionInfo(e);return o.map(e=>{let t=this._dateStrToMs(e.date),i=th(t,l,h,"day");return{openTime:t,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume,closeTime:i,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async _fetchIntradayData(e,t,i,r,n,s){let a=`${this._baseUrl}${t}?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`;r&&(a+=`&from=${this._msToDateStr(r)}`),n&&(a+=`&to=${this._msToDateStr(n)}`);let o=await fetch(a);if(!o.ok){let e=await o.text();if(403===o.status||e.includes("Restricted Endpoint"))return console.error(`FMP: Intraday data (${i}) requires a paid plan. Use daily timeframe ('D') with a free API key, or upgrade at https://financialmodelingprep.com/`),[];throw Error(`FMP HTTP ${o.status}: ${e}`)}let l=await o.json();if(!Array.isArray(l)||0===l.length)return[];l.reverse();let h=s&&s>0&&s<l.length?l.slice(l.length-s):l,{periodType:c,multiplier:p}=dg[i]||{periodType:"minute",multiplier:1},{session:u,timezone:d}=await this._resolveSessionInfo(e);return h.map(e=>{let t=this._dateTimeStrToMs(e.date),i=th(t,u,d,c,p);return{openTime:t,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume,closeTime:i,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async getSymbolInfo(e){if(this.ensureConfigured(),e=i6(e),this._symbolInfoCache.has(e))return this._symbolInfoCache.get(e);try{let t=await this._fetchProfile(e),i="stock";t?.isEtf?i="etf":t?.isFund?i="fund":this._isForex(e)?i="forex":this._isCrypto(e)&&(i="crypto");let r=t?.exchange||("crypto"===i?"CRYPTO":"forex"===i?"FX":""),n="crypto"===i||"forex"===i?"Etc/UTC":dy[r]||"America/New_York",s="crypto"===i?"24x7":"forex"===i?"0000-0000":d_[r]||"0930-1600",a=t?.currency||(this._isForex(e)?e.slice(3,6):"USD"),o=this._isForex(e)?e.slice(0,3):t?.currency||"USD",l=this._mintickCache.get(e)??.01,h=Math.round(1/l),c=Math.round(l*h),p={ticker:t?.symbol||e,tickerid:`${r}:${t?.symbol||e}`,prefix:r,root:t?.symbol||e,description:t?.companyName||e,type:i,main_tickerid:`${r}:${t?.symbol||e}`,current_contract:"",isin:t?.isin||"",basecurrency:o,currency:a,timezone:n,country:t?.country||"",mintick:l,pricescale:h,minmove:c,pointvalue:1,mincontract:0,session:s,volumetype:"base",expiration_date:0,employees:t&&parseInt(t.fullTimeEmployees)||0,industry:t?.industry||"",sector:t?.sector||"",shareholders:0,shares_outstanding_float:0,shares_outstanding_total:0,recommendations_buy:0,recommendations_buy_strong:0,recommendations_date:0,recommendations_hold:0,recommendations_sell:0,recommendations_sell_strong:0,recommendations_total:0,target_price_average:0,target_price_date:0,target_price_estimates:0,target_price_high:0,target_price_low:0,target_price_median:0};return this._mintickCache.has(e)&&this._symbolInfoCache.set(e,p),p}catch(e){return console.error("Error in FMPProvider.getSymbolInfo:",e),null}}_estimateMintick(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i],n=Math.abs(r.close-r.open),s=Math.abs(r.high-r.low);if(n>0&&t.push(n),s>0&&t.push(s),i>0){let n=Math.abs(r.close-e[i-1].close);n>0&&t.push(n)}}if(0===t.length)return;let i=Math.min(...t),r=Math.floor(Math.log10(i)),n=(5>Math.floor(i/10**r+1e-12)?1:10)*10**r;return n>=1?.01:n}async _fetchProfile(e){if(this._profileCache.has(e))return this._profileCache.get(e);let t=`${this._baseUrl}/stable/profile?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`,i=await fetch(t);if(!i.ok)return null;let r=await i.json();if(!Array.isArray(r)||0===r.length)return null;let n=r[0];return this._profileCache.set(e,n),n}async _resolveSessionInfo(e){try{let t=await this._fetchProfile(e);if(t){let i=t.exchange||"",r=this._isCrypto(e),n=r?"Etc/UTC":dy[i]||"America/New_York";return{session:r?"24x7":d_[i]||"0930-1600",timezone:n}}}catch{}return{session:"0930-1600",timezone:"America/New_York"}}_msToDateStr(e){return new Date(e).toISOString().split("T")[0]}_dateStrToMs(e){return new Date(e+"T00:00:00Z").getTime()}_dateTimeStrToMs(e){return new Date(e.replace(" ","T")+"Z").getTime()}_isForex(e){return/^[A-Z]{6}$/.test(e)&&dm.has(e.slice(0,3))&&dm.has(e.slice(3,6))}_isCrypto(e){return!this._isForex(e)&&/^[A-Z]+(USD|USDT|BTC|ETH)$/.test(e)&&e.length<=15}}var db=Object.defineProperty,dv=(e,t,i)=>((e,t,i)=>t in e?db(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let dw={1:"1Min",3:"3Min",5:"5Min",15:"15Min",30:"30Min",60:"1Hour",120:"2Hour",240:"4Hour","4H":"4Hour","1D":"1Day",D:"1Day","1W":"1Week",W:"1Week","1M":"1Month",M:"1Month"},dS={NASDAQ:"America/New_York",NYSE:"America/New_York",AMEX:"America/New_York",ARCA:"America/New_York",BATS:"America/New_York",OTC:"America/New_York",CRYPTO:"Etc/UTC"},dE={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",ARCA:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",CRYPTO:"24x7"},dN={Min:"minute",Hour:"hour",Day:"day",Week:"week",Month:"month"};class dT extends dr{constructor(e){super({requiresApiKey:!0,providerName:"Alpaca"}),dv(this,"_apiKey",null),dv(this,"_apiSecret",null),dv(this,"_dataUrl","https://data.alpaca.markets"),dv(this,"_tradingUrl","https://paper-api.alpaca.markets/v2"),dv(this,"_feed",null),dv(this,"_assetCache",new Map),dv(this,"_calendarCache",new Map),e?.apiKey&&e?.apiSecret&&this.configure(e)}configure(e){super.configure(e),this._apiKey=e.apiKey,this._apiSecret=e.apiSecret,e.feed&&(this._feed=e.feed),e.dataUrl&&(this._dataUrl=e.dataUrl),e.tradingUrl?this._tradingUrl=e.tradingUrl:!1===e.paper&&(this._tradingUrl="https://api.alpaca.markets/v2")}_headers(){return{"APCA-API-KEY-ID":this._apiKey,"APCA-API-SECRET-KEY":this._apiSecret}}getSupportedTimeframes(){return new Set(["1","3","5","15","30","45","60","120","180","240","D","W","M"])}async _getMarketDataNative(e,t,i,r,n){this.ensureConfigured();try{let s=this._resolveTimeframe(t);if(!s)return console.error(`Alpaca: Unsupported timeframe: ${t}`),[];let a=this._isCrypto(e),o=await this._fetchAllBars(e,s,a,r,n,i);if(0===o.length)return[];let{periodType:l,multiplier:h}=this._parseAlpacaTimeframe(s);if(a)return this._convertBarsCrypto(o,l,h);let c=o[0].t.slice(0,10),p=o[o.length-1].t.slice(0,10),u=this._addDaysToDate(p,40);return await this._ensureCalendar(c,u),this._convertBarsStock(o,l,h)}catch(e){return console.error("Error in AlpacaProvider.getMarketData:",e),[]}}async _fetchAllBars(e,t,i,r,n,s){let a=[],o=null,l=s||1/0,h=Math.min(s||1e4,1e4);do{let s=this._buildBarsUrl(e,t,i,r,n,h,o),c=await fetch(s,{headers:this._headers()});if(!c.ok){let e=await c.text();throw Error(`Alpaca HTTP ${c.status}: ${e}`)}let p=await c.json(),u=Object.keys(p.bars||{})[0];if(!u||!p.bars[u]||(a.push(...p.bars[u]),o=p.next_page_token,a.length>=l))break}while(o);return s&&s>0&&a.length>s?a.slice(0,s):a}_buildBarsUrl(e,t,i,r,n,s,a){let o=i?`${this._dataUrl}/v1beta3/crypto/us/bars`:`${this._dataUrl}/v2/stocks/bars`,l=new URLSearchParams;return l.set("symbols",e),l.set("timeframe",t),l.set("sort","asc"),r&&l.set("start",new Date(r).toISOString()),n&&l.set("end",new Date(n).toISOString()),s&&l.set("limit",String(Math.min(s,1e4))),a&&l.set("page_token",a),!i&&this._feed&&l.set("feed",this._feed),`${o}?${l.toString()}`}async getSymbolInfo(e){this.ensureConfigured(),e=i6(e);try{let t=await this._fetchAsset(e);if(!t)return console.error(`Alpaca: Symbol ${e} not found`),null;let i=t.exchange||"",r="crypto"===t.class,n=r?"Etc/UTC":dS[i]||"America/New_York",s=r?"24x7":dE[i]||"0930-1600",a="stock";r&&(a="crypto");let o=r&&e.split("/")[1]||"USD",l=r?e.split("/")[0]||e:o,h=t.price_increment?parseFloat(t.price_increment):.01,c=Math.round(1/h);return{ticker:t.symbol,tickerid:`${i}:${t.symbol}`,prefix:i,root:r?e.split("/")[0]:t.symbol,description:t.name||t.symbol,type:a,main_tickerid:`${i}:${t.symbol}`,current_contract:"",isin:"",basecurrency:l,currency:o,timezone:n,country:r?"":"US",mintick:h,pricescale:c,minmove:1,pointvalue:1,mincontract:t.min_order_size?parseFloat(t.min_order_size):0,session:s,volumetype:"base",expiration_date:0,employees:0,industry:"",sector:"",shareholders:0,shares_outstanding_float:0,shares_outstanding_total:0,recommendations_buy:0,recommendations_buy_strong:0,recommendations_date:0,recommendations_hold:0,recommendations_sell:0,recommendations_sell_strong:0,recommendations_total:0,target_price_average:0,target_price_date:0,target_price_estimates:0,target_price_high:0,target_price_low:0,target_price_median:0}}catch(e){return console.error("Error in AlpacaProvider.getSymbolInfo:",e),null}}_convertBarsCrypto(e,t,i){return e.map((e,r,n)=>{let s=new Date(e.t).getTime(),a=r<n.length-1?new Date(n[r+1].t).getTime():to(s,t,i);return this._toKline(e,s,a)})}_convertBarsStock(e,t,i){let r="America/New_York";return e.map(e=>{let n,s=new Date(e.t).getTime(),a=e.t.slice(0,10);if("day"===t){let e=this._calendarCache.get(a);n=tl(a,e?e.close:"16:00",r)}else if("minute"===t||"hour"===t){let e=s+i*({minute:6e4,hour:36e5})[t],o=this._calendarCache.get(a);n=Math.min(e,tl(a,o?o.close:"16:00",r))}else n="week"===t?this._weeklyCloseFromCalendar(a,r):"month"===t?this._monthlyCloseFromCalendar(a,r):to(s,t,i);return this._toKline(e,s,n)})}_toKline(e,t,i){return{openTime:t,open:e.o,high:e.h,low:e.l,close:e.c,volume:e.v,closeTime:i,quoteAssetVolume:0,numberOfTrades:e.n,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}}_weeklyCloseFromCalendar(e,t){let i=new Date(e+"T00:00:00Z"),r=i.getUTCDay(),n=r<=5?5-r:5-r+7;for(let e=n;e>=0;e--){let r=new Date(i.getTime()+864e5*e).toISOString().split("T")[0],n=this._calendarCache.get(r);if(n)return tl(r,n.close,t)}return tl(new Date(i.getTime()+864e5*n).toISOString().split("T")[0],"16:00",t)}_monthlyCloseFromCalendar(e,t){let[i,r]=e.split("-").map(Number),n=new Date(Date.UTC(i,r,0)).getUTCDate();for(let e=n;e>=1;e--){let n=`${i}-${String(r).padStart(2,"0")}-${String(e).padStart(2,"0")}`,s=this._calendarCache.get(n);if(s)return tl(n,s.close,t)}let s=new Date(Date.UTC(i,r,0));for(;0===s.getUTCDay()||6===s.getUTCDay();)s.setUTCDate(s.getUTCDate()-1);return tl(s.toISOString().split("T")[0],"16:00",t)}async _ensureCalendar(e,t){if(this._calendarCache.has(e)&&this._calendarCache.has(t))return;let i=`${this._tradingUrl}/calendar?start=${e}&end=${t}`,r=await fetch(i,{headers:this._headers()});if(!r.ok)return void console.warn(`Alpaca calendar API returned ${r.status}, falling back to defaults`);for(let e of(await r.json()))this._calendarCache.set(e.date,e)}async _fetchAsset(e){if(this._assetCache.has(e))return this._assetCache.get(e);let t=encodeURIComponent(e),i=`${this._tradingUrl}/assets/${t}`,r=await fetch(i,{headers:this._headers()});if(!r.ok)return null;let n=await r.json();return this._assetCache.set(e,n),n}_parseAlpacaTimeframe(e){let t=e.match(/^(\d+)(Min|Hour|Day|Week|Month)$/);if(t){let e=parseInt(t[1],10),i=dN[t[2]];if(i)return{periodType:i,multiplier:e}}return{periodType:"day",multiplier:1}}_resolveTimeframe(e){return dw[e.toUpperCase()]||dw[e]||null}_isCrypto(e){return e.includes("/")}_addDaysToDate(e,t){let i=new Date(e+"T00:00:00Z");return i.setUTCDate(i.getUTCDate()+t),i.toISOString().split("T")[0]}}class dk{async getMarketData(){return[]}}let dA="u">typeof h&&h.versions&&h.versions.node,dI=null;if(dA)try{dI=new dk}catch{dI=null}({Binance:new dp,FMP:new dx,Alpaca:new dT,...dI?{Mock:dI}:{}});var dC=Object.defineProperty;class dM extends uZ{constructor(e){super({requiresConfig:!1,resolverName:"Map",cached:!1}),((e,t,i)=>((e,t,i)=>t in e?dC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i))(this,"_libraries",{}),e&&this.configure(e)}configure(e){super.configure(e),e.libraries&&(this._libraries=e.libraries)}_resolveNative(e){return this._get(e.path)??this._get(`${e.user}/${e.name}`)??this._get(e.name)??null}_get(e){let t=this._libraries;return t instanceof Map?t.get(e):Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}}function dP(e,t){return e.replace(/\{(path|user|name|version)\}/g,(e,i)=>String(t[i]))}async function dD(e,t,i){let r=e??globalThis.fetch;if("function"!=typeof r)throw Error("No fetch implementation available: pass one in the resolver config");let n=await r(t,i?{headers:i}:void 0);if(404===n.status)return null;if(!n.ok)throw Error(`Failed to fetch ${t}: ${n.status} ${n.statusText??""}`.trim());return n.text()}var dR=Object.defineProperty,dO=(e,t,i)=>((e,t,i)=>t in e?dR(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class dj extends uZ{constructor(e){super({requiresConfig:!0,resolverName:"Url"}),dO(this,"_url",null),dO(this,"_headers"),dO(this,"_fetch"),e?.url&&this.configure(e)}configure(e){super.configure(e),void 0!==e.url&&(this._url=e.url),void 0!==e.headers&&(this._headers=e.headers),void 0!==e.fetch&&(this._fetch=e.fetch)}_resolveNative(e){let t=this._url;if(!t)throw Error('The Url import resolver has no "url" configured');return dD(this._fetch,"function"==typeof t?t(e):dP(t,e),this._headers)}}var dV=Object.defineProperty,d$=(e,t,i)=>((e,t,i)=>t in e?dV(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class dL extends uZ{constructor(e){super({requiresConfig:!0,resolverName:"GitHub"}),d$(this,"_location",null),d$(this,"_token"),d$(this,"_extensions",["",".pine"]),d$(this,"_fetch"),(e?.url||e?.owner)&&this.configure(e)}configure(e){super.configure(e),void 0!==e.url&&(this._location=function(e){let t=e.trim().match(/^(?:https?:\/\/)?(?:www\.)?(github\.com|raw\.githubusercontent\.com)\/([^/]+)\/([^/#?]+)(?:\/(.*?))?\/?(?:[?#].*)?$/i);if(!t)throw Error(`Not a GitHub repository URL: "${e}"`);let[,i,r,n,s=""]=t,a=n.replace(/\.git$/,""),o=s.split("/").filter(Boolean).map(decodeURIComponent);if("raw.githubusercontent.com"===i.toLowerCase()){if(o.length<2)throw Error(`A raw.githubusercontent.com URL must point to a file: "${e}"`);return{owner:r,repo:a,ref:o[0],file:o.slice(1).join("/")}}if(0===o.length)return{owner:r,repo:a};if(("tree"===o[0]||"blob"===o[0])&&o.length>=2){let e={owner:r,repo:a,ref:o[1]},t=o.slice(2).join("/");return"blob"===o[0]?e.file=t:t&&(e.path=t),e}throw Error(`Unsupported GitHub URL: "${e}". Use a repository, folder (/tree/...) or file (/blob/...) URL`)}(e.url)),(void 0!==e.owner||void 0!==e.repo)&&(this._location={...this._location??{owner:"",repo:""},file:void 0},void 0!==e.owner&&(this._location.owner=e.owner),void 0!==e.repo&&(this._location.repo=e.repo)),this._location&&(void 0!==e.ref&&(this._location.ref=e.ref),void 0!==e.path&&(this._location.path=e.path)),void 0!==e.token&&(this._token=e.token),e.extensions&&(this._extensions=e.extensions),void 0!==e.fetch&&(this._fetch=e.fetch)}_resolveNative(e){let t=this._location;if(!t?.owner||!t.repo)throw Error("The GitHub import resolver has no repository configured (url, or owner and repo)");if(t.file){let i=t.file.split("/").pop()?.replace(/\.[^.]*$/,"");return e.name===i?this._get(t,t.file):Promise.resolve(null)}let i=t.path?t.path.includes("{")?t.path:`${t.path.replace(/\/+$/,"")}/{name}`:"{name}";return this.firstFound(dP(i,e),this._extensions,e=>this._get(t,e))}_get(e,t){let i=t.split("/").map(encodeURIComponent).join("/");if(this._token){let t=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${i}${e.ref?`?ref=${encodeURIComponent(e.ref)}`:""}`;return dD(this._fetch,t,{Accept:"application/vnd.github.raw",Authorization:`Bearer ${this._token}`,"X-GitHub-Api-Version":"2022-11-28"})}return dD(this._fetch,`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref??"HEAD"}/${i}`)}}class dB{configure(){}async resolve(){throw Error("FileImportResolver is only available in Node.js")}}let dF="u">typeof h&&h.versions&&h.versions.node,dq=null;if(dF)try{dq=new dB}catch{dq=null}({Map:new dM,Url:new dj,GitHub:new dL,...dq?{File:dq}:{}})}}]);