@jetstreamapp/soql-parser-js 7.4.1 → 8.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.
package/dist/cli/index.js CHANGED
@@ -1,31 +1,11 @@
1
1
  /*!
2
- * @jetstreamapp/soql-parser-js v7.4.1
2
+ * @jetstreamapp/soql-parser-js v8.1.0
3
3
  * https://github.com/jetstreamapp/soql-parser-js
4
4
  * @license MIT
5
5
  */
6
- "use strict";var R=(r=>(r[r.AND=0]="AND",r[r.AS=1]="AS",r[r.ASC=2]="ASC",r[r.DESC=3]="DESC",r[r.CUBE=4]="CUBE",r[r.ELSE=5]="ELSE",r[r.EXCLUDES=6]="EXCLUDES",r[r.FALSE=7]="FALSE",r[r.FIRST=8]="FIRST",r[r.FROM=9]="FROM",r[r.GROUP_BY=10]="GROUP_BY",r[r.HAVING=11]="HAVING",r[r.IN=12]="IN",r[r.INCLUDES=13]="INCLUDES",r[r.LAST=14]="LAST",r[r.LIKE=15]="LIKE",r[r.LIMIT=16]="LIMIT",r[r.NOT=17]="NOT",r[r.NULL=18]="NULL",r[r.NULLS=19]="NULLS",r[r.OR=20]="OR",r[r.ORDER_BY=21]="ORDER_BY",r[r.ROLLUP=22]="ROLLUP",r[r.SELECT=23]="SELECT",r[r.TRUE=24]="TRUE",r[r.USING=25]="USING",r[r.WHERE=26]="WHERE",r[r.WITH=27]="WITH",r[r.FOR=28]="FOR",r[r.UPDATE=29]="UPDATE",r[r.ABOVE=30]="ABOVE",r[r.ABOVE_OR_BELOW=31]="ABOVE_OR_BELOW",r[r.APEX_NEW=32]="APEX_NEW",r[r.AT=33]="AT",r[r.BELOW=34]="BELOW",r[r.DATA_CATEGORY=35]="DATA_CATEGORY",r[r.END=36]="END",r[r.OFFSET=37]="OFFSET",r[r.REFERENCE=38]="REFERENCE",r[r.SCOPE=39]="SCOPE",r[r.TRACKING=40]="TRACKING",r[r.THEN=41]="THEN",r[r.TYPEOF=42]="TYPEOF",r[r.VIEW=43]="VIEW",r[r.VIEWSTAT=44]="VIEWSTAT",r[r.WHEN=45]="WHEN",r[r.SECURITY_ENFORCED=46]="SECURITY_ENFORCED",r[r.SYSTEM_MODE=47]="SYSTEM_MODE",r[r.USER_MODE=48]="USER_MODE",r[r.CALENDAR_MONTH=49]="CALENDAR_MONTH",r[r.CALENDAR_QUARTER=50]="CALENDAR_QUARTER",r[r.CALENDAR_YEAR=51]="CALENDAR_YEAR",r[r.DAY_IN_MONTH=52]="DAY_IN_MONTH",r[r.DAY_IN_WEEK=53]="DAY_IN_WEEK",r[r.DAY_IN_YEAR=54]="DAY_IN_YEAR",r[r.DAY_ONLY=55]="DAY_ONLY",r[r.FISCAL_MONTH=56]="FISCAL_MONTH",r[r.FISCAL_QUARTER=57]="FISCAL_QUARTER",r[r.FISCAL_YEAR=58]="FISCAL_YEAR",r[r.HOUR_IN_DAY=59]="HOUR_IN_DAY",r[r.WEEK_IN_MONTH=60]="WEEK_IN_MONTH",r[r.WEEK_IN_YEAR=61]="WEEK_IN_YEAR",r[r.AVG=62]="AVG",r[r.COUNT=63]="COUNT",r[r.COUNT_DISTINCT=64]="COUNT_DISTINCT",r[r.MIN=65]="MIN",r[r.MAX=66]="MAX",r[r.SUM=67]="SUM",r[r.DISTANCE=68]="DISTANCE",r[r.GEOLOCATION=69]="GEOLOCATION",r[r.FIELDS=70]="FIELDS",r[r.FORMAT=71]="FORMAT",r[r.TOLABEL=72]="TOLABEL",r[r.CONVERT_TIMEZONE=73]="CONVERT_TIMEZONE",r[r.CONVERT_CURRENCY=74]="CONVERT_CURRENCY",r[r.GROUPING=75]="GROUPING",r[r.ALL=76]="ALL",r[r.CUSTOM=77]="CUSTOM",r[r.STANDARD=78]="STANDARD",r[r.YESTERDAY=79]="YESTERDAY",r[r.TODAY=80]="TODAY",r[r.TOMORROW=81]="TOMORROW",r[r.LAST_WEEK=82]="LAST_WEEK",r[r.THIS_WEEK=83]="THIS_WEEK",r[r.NEXT_WEEK=84]="NEXT_WEEK",r[r.LAST_MONTH=85]="LAST_MONTH",r[r.THIS_MONTH=86]="THIS_MONTH",r[r.NEXT_MONTH=87]="NEXT_MONTH",r[r.LAST_90_DAYS=88]="LAST_90_DAYS",r[r.NEXT_90_DAYS=89]="NEXT_90_DAYS",r[r.THIS_QUARTER=90]="THIS_QUARTER",r[r.LAST_QUARTER=91]="LAST_QUARTER",r[r.NEXT_QUARTER=92]="NEXT_QUARTER",r[r.THIS_YEAR=93]="THIS_YEAR",r[r.LAST_YEAR=94]="LAST_YEAR",r[r.NEXT_YEAR=95]="NEXT_YEAR",r[r.THIS_FISCAL_QUARTER=96]="THIS_FISCAL_QUARTER",r[r.LAST_FISCAL_QUARTER=97]="LAST_FISCAL_QUARTER",r[r.NEXT_FISCAL_QUARTER=98]="NEXT_FISCAL_QUARTER",r[r.THIS_FISCAL_YEAR=99]="THIS_FISCAL_YEAR",r[r.LAST_FISCAL_YEAR=100]="LAST_FISCAL_YEAR",r[r.NEXT_FISCAL_YEAR=101]="NEXT_FISCAL_YEAR",r[r.NEXT_N_DAYS=102]="NEXT_N_DAYS",r[r.LAST_N_DAYS=103]="LAST_N_DAYS",r[r.N_DAYS_AGO=104]="N_DAYS_AGO",r[r.NEXT_N_WEEKS=105]="NEXT_N_WEEKS",r[r.LAST_N_WEEKS=106]="LAST_N_WEEKS",r[r.N_WEEKS_AGO=107]="N_WEEKS_AGO",r[r.NEXT_N_MONTHS=108]="NEXT_N_MONTHS",r[r.LAST_N_MONTHS=109]="LAST_N_MONTHS",r[r.N_MONTHS_AGO=110]="N_MONTHS_AGO",r[r.NEXT_N_QUARTERS=111]="NEXT_N_QUARTERS",r[r.LAST_N_QUARTERS=112]="LAST_N_QUARTERS",r[r.N_QUARTERS_AGO=113]="N_QUARTERS_AGO",r[r.NEXT_N_YEARS=114]="NEXT_N_YEARS",r[r.LAST_N_YEARS=115]="LAST_N_YEARS",r[r.N_YEARS_AGO=116]="N_YEARS_AGO",r[r.NEXT_N_FISCAL_QUARTERS=117]="NEXT_N_FISCAL_QUARTERS",r[r.LAST_N_FISCAL_QUARTERS=118]="LAST_N_FISCAL_QUARTERS",r[r.N_FISCAL_QUARTERS_AGO=119]="N_FISCAL_QUARTERS_AGO",r[r.NEXT_N_FISCAL_YEARS=120]="NEXT_N_FISCAL_YEARS",r[r.LAST_N_FISCAL_YEARS=121]="LAST_N_FISCAL_YEARS",r[r.N_FISCAL_YEARS_AGO=122]="N_FISCAL_YEARS_AGO",r[r.DELEGATED=123]="DELEGATED",r[r.EVERYTHING=124]="EVERYTHING",r[r.MINE_AND_MY_GROUPS=125]="MINE_AND_MY_GROUPS",r[r.MINE=126]="MINE",r[r.MY_TERRITORY=127]="MY_TERRITORY",r[r.MY_TEAM_TERRITORY=128]="MY_TEAM_TERRITORY",r[r.TEAM=129]="TEAM",r[r.ALL_PRIVATE=130]="ALL_PRIVATE",r[r.MRU=131]="MRU",r[r.EQUAL=132]="EQUAL",r[r.NOT_EQUAL=133]="NOT_EQUAL",r[r.LESS_THAN=134]="LESS_THAN",r[r.LESS_THAN_OR_EQUAL=135]="LESS_THAN_OR_EQUAL",r[r.GREATER_THAN=136]="GREATER_THAN",r[r.GREATER_THAN_OR_EQUAL=137]="GREATER_THAN_OR_EQUAL",r[r.L_PAREN=138]="L_PAREN",r[r.R_PAREN=139]="R_PAREN",r[r.L_SQUARE_BRACKET=140]="L_SQUARE_BRACKET",r[r.R_SQUARE_BRACKET=141]="R_SQUARE_BRACKET",r[r.DOT=142]="DOT",r[r.COMMA=143]="COMMA",r[r.COLON=144]="COLON",r[r.SEMICOLON=145]="SEMICOLON",r[r.ASTERISK=146]="ASTERISK",r[r.PLUS=147]="PLUS",r[r.MINUS=148]="MINUS",r[r.DATETIME=149]="DATETIME",r[r.DATE_TOKEN=150]="DATE_TOKEN",r[r.CURRENCY_PREFIXED_DECIMAL=151]="CURRENCY_PREFIXED_DECIMAL",r[r.CURRENCY_PREFIXED_INTEGER=152]="CURRENCY_PREFIXED_INTEGER",r[r.SIGNED_DECIMAL=153]="SIGNED_DECIMAL",r[r.UNSIGNED_DECIMAL=154]="UNSIGNED_DECIMAL",r[r.SIGNED_INTEGER=155]="SIGNED_INTEGER",r[r.UNSIGNED_INTEGER=156]="UNSIGNED_INTEGER",r[r.STRING_LITERAL=157]="STRING_LITERAL",r[r.GEOLOCATION_UNIT=158]="GEOLOCATION_UNIT",r[r.IDENTIFIER=159]="IDENTIFIER",r[r.EOF=160]="EOF",r))(R||{});function y(s){return s>=49&&s<=61}function F(s){return s>=62&&s<=67}function B(s){return s>=68&&s<=69}function H(s){return s===70}function b(s){return s>=71&&s<=75}function ne(s){return s>=76&&s<=78}function M(s){return s>=79&&s<=101}function w(s){return s>=102&&s<=122}function ae(s){return s>=123&&s<=131}function m(s){return s===159||s>=30&&s<=48||s>=49&&s<=61||s>=62&&s<=67||s>=68&&s<=69||s===70||s>=71&&s<=75||s>=76&&s<=78||s>=79&&s<=101||s>=102&&s<=122||s>=123&&s<=131||s===158||s===152}function Q(s){return s===153||s===154||s===155||s===156}function oe(s){return s>=132&&s<=137}var fe=new Map([["AND",0],["AS",1],["ASC",2],["DESC",3],["CUBE",4],["ELSE",5],["EXCLUDES",6],["FALSE",7],["FIRST",8],["FROM",9],["HAVING",11],["IN",12],["INCLUDES",13],["LAST",14],["LIKE",15],["LIMIT",16],["NOT",17],["NULL",18],["NULLS",19],["OR",20],["ROLLUP",22],["SELECT",23],["TRUE",24],["USING",25],["WHERE",26],["WITH",27],["FOR",28],["UPDATE",29],["ABOVE_OR_BELOW",31],["ABOVE",30],["NEW",32],["AT",33],["BELOW",34],["END",36],["OFFSET",37],["REFERENCE",38],["SCOPE",39],["TRACKING",40],["THEN",41],["TYPEOF",42],["VIEW",43],["VIEWSTAT",44],["WHEN",45],["SECURITY_ENFORCED",46],["SYSTEM_MODE",47],["USER_MODE",48],["CALENDAR_MONTH",49],["CALENDAR_QUARTER",50],["CALENDAR_YEAR",51],["DAY_IN_MONTH",52],["DAY_IN_WEEK",53],["DAY_IN_YEAR",54],["DAY_ONLY",55],["FISCAL_MONTH",56],["FISCAL_QUARTER",57],["FISCAL_YEAR",58],["HOUR_IN_DAY",59],["WEEK_IN_MONTH",60],["WEEK_IN_YEAR",61],["AVG",62],["COUNT_DISTINCT",64],["COUNT",63],["MIN",65],["MAX",66],["SUM",67],["DISTANCE",68],["GEOLOCATION",69],["FIELDS",70],["FORMAT",71],["TOLABEL",72],["CONVERTTIMEZONE",73],["CONVERTCURRENCY",74],["GROUPING",75],["ALL",76],["CUSTOM",77],["STANDARD",78],["YESTERDAY",79],["TODAY",80],["TOMORROW",81],["LAST_WEEK",82],["THIS_WEEK",83],["NEXT_WEEK",84],["LAST_MONTH",85],["THIS_MONTH",86],["NEXT_MONTH",87],["LAST_90_DAYS",88],["NEXT_90_DAYS",89],["THIS_QUARTER",90],["LAST_QUARTER",91],["NEXT_QUARTER",92],["THIS_YEAR",93],["LAST_YEAR",94],["NEXT_YEAR",95],["THIS_FISCAL_QUARTER",96],["LAST_FISCAL_QUARTER",97],["NEXT_FISCAL_QUARTER",98],["THIS_FISCAL_YEAR",99],["LAST_FISCAL_YEAR",100],["NEXT_FISCAL_YEAR",101],["NEXT_N_DAYS",102],["LAST_N_DAYS",103],["N_DAYS_AGO",104],["NEXT_N_WEEKS",105],["LAST_N_WEEKS",106],["N_WEEKS_AGO",107],["NEXT_N_MONTHS",108],["LAST_N_MONTHS",109],["N_MONTHS_AGO",110],["NEXT_N_QUARTERS",111],["LAST_N_QUARTERS",112],["N_QUARTERS_AGO",113],["NEXT_N_YEARS",114],["LAST_N_YEARS",115],["N_YEARS_AGO",116],["NEXT_N_FISCAL_QUARTERS",117],["LAST_N_FISCAL_QUARTERS",118],["N_FISCAL_QUARTERS_AGO",119],["NEXT_N_FISCAL_YEARS",120],["LAST_N_FISCAL_YEARS",121],["N_FISCAL_YEARS_AGO",122],["DELEGATED",123],["EVERYTHING",124],["MINEANDMYGROUPS",125],["MINE",126],["MY_TERRITORY",127],["MY_TEAM_TERRITORY",128],["TEAM",129],["ALLPRIVATE",130],["MRU",131]]),p=[];(function(){for(let e of Object.keys(R)){let i=R[e];typeof i=="number"&&(p[i]=e)}p[72]="toLabel",p[73]="convertTimezone",p[74]="convertCurrency",p[157]="StringIdentifier",p[150]="DATE",p[32]="new",p[125]="MineAndMyGroups",p[127]="MyTerritory",p[128]="MyTeamTerritory",p[130]="AllPrivate",p[123]="Delegated",p[124]="Everything",p[126]="Mine",p[129]="Team",p[131]="Mru",p[159]="Identifier",p[132]="EQUAL",p[156]="UNSIGNED_INTEGER",p[155]="SIGNED_INTEGER",p[154]="UNSIGNED_DECIMAL",p[153]="SIGNED_DECIMAL",p[151]="CURRENCY_PREFIXED_DECIMAL",p[152]="CURRENCY_PREFIXED_INTEGER"})();function f(s){return p[s]||R[s]}function V(s){return s>=65&&s<=90||s>=97&&s<=122}function h(s){return s>=48&&s<=57}function $(s){return V(s)||h(s)||s===95}function G(s){return s===32||s===9||s===10||s===13||s===12}function le(s){let e=[],i=s.length,t=0;for(;t<i;){let n=s.charCodeAt(t);if(G(n)){for(t++;t<i&&G(s.charCodeAt(t));)t++;continue}if(n===47){let a=t+1<i?s.charCodeAt(t+1):0;if(a===47){for(t+=2;t<i;){let o=s.charCodeAt(t);if(o===10||o===13)break;t++}continue}if(a===42){let o=t;t+=2;let l=!1;for(;t<i;){if(s.charCodeAt(t)===42&&t+1<i&&s.charCodeAt(t+1)===47){t+=2,l=!0;break}t++}if(!l)throw new Error(`Unterminated comment at position ${o}`);continue}}if(n===39){let a=t;for(t++;t<i;){let c=s.charCodeAt(t);if(c===92){t+=2;continue}if(c===39){t++;break}t++}let o=s.substring(a,t),u=o.substring(1,o.length-1).toUpperCase();u==="MI"||u==="KM"?e.push({kind:158,text:o,start:a}):e.push({kind:157,text:o,start:a});continue}if(h(n)){if(t+9<i&&s.charCodeAt(t+4)===45&&s.charCodeAt(t+7)===45){let o=!0;for(let l of[0,1,2,3,5,6,8,9])if(!h(s.charCodeAt(t+l))){o=!1;break}if(o)if(t+10<i&&(s.charCodeAt(t+10)===84||s.charCodeAt(t+10)===116)){let l=t;for(t+=11;t<i;){let u=s.charCodeAt(t);if(h(u)||u===58)t++;else break}if(t<i&&s.charCodeAt(t)===46)for(t++;t<i&&h(s.charCodeAt(t));)t++;if(t<i){let u=s.charCodeAt(t);if(u===90||u===122)t++;else if(u===46){for(t++;t<i&&h(s.charCodeAt(t));)t++;t<i&&(s.charCodeAt(t)===90||s.charCodeAt(t)===122)&&t++}else if(u===43||u===45)for(t++;t<i;){let c=s.charCodeAt(t);if(h(c)||c===58)t++;else break}}e.push({kind:149,text:s.substring(l,t),start:l});continue}else{let l=t;t+=10,e.push({kind:150,text:s.substring(l,t),start:l});continue}}let a=t;for(;t<i&&h(s.charCodeAt(t));)t++;if(t<i&&s.charCodeAt(t)===46&&t+1<i&&h(s.charCodeAt(t+1))){for(t++;t<i&&h(s.charCodeAt(t));)t++;e.push({kind:154,text:s.substring(a,t),start:a});continue}e.push({kind:156,text:s.substring(a,t),start:a});continue}if(n===33){if(t+1<i&&s.charCodeAt(t+1)===61){e.push({kind:133,text:"!=",start:t}),t+=2;continue}throw new Error(`Unexpected character '!' at position ${t}`)}if(n===60){if(t+1<i){let a=s.charCodeAt(t+1);if(a===61){e.push({kind:135,text:"<=",start:t}),t+=2;continue}if(a===62){e.push({kind:133,text:"<>",start:t}),t+=2;continue}}e.push({kind:134,text:"<",start:t}),t++;continue}if(n===62){if(t+1<i&&s.charCodeAt(t+1)===61){e.push({kind:137,text:">=",start:t}),t+=2;continue}e.push({kind:136,text:">",start:t}),t++;continue}if(n===61){e.push({kind:132,text:"=",start:t}),t++;continue}if(n===40){e.push({kind:138,text:"(",start:t}),t++;continue}if(n===41){e.push({kind:139,text:")",start:t}),t++;continue}if(n===91){e.push({kind:140,text:"[",start:t}),t++;continue}if(n===93){e.push({kind:141,text:"]",start:t}),t++;continue}if(n===44){e.push({kind:143,text:",",start:t}),t++;continue}if(n===58){e.push({kind:144,text:":",start:t}),t++;continue}if(n===59){e.push({kind:145,text:";",start:t}),t++;continue}if(n===42){e.push({kind:146,text:"*",start:t}),t++;continue}if(n===43||n===45){if(t+1<i){let a=s.charCodeAt(t+1);if(h(a)){let o=t;for(t++;t<i&&h(s.charCodeAt(t));)t++;if(t<i&&s.charCodeAt(t)===46&&t+1<i&&h(s.charCodeAt(t+1))){for(t++;t<i&&h(s.charCodeAt(t));)t++;e.push({kind:153,text:s.substring(o,t),start:o});continue}e.push({kind:155,text:s.substring(o,t),start:o});continue}if(a===46&&t+2<i&&h(s.charCodeAt(t+2))){let o=t;for(t+=2;t<i&&h(s.charCodeAt(t));)t++;e.push({kind:153,text:s.substring(o,t),start:o});continue}}e.push({kind:n===43?147:148,text:s[t],start:t}),t++;continue}if(n===46){if(t+1<i&&h(s.charCodeAt(t+1))){let a=t;for(t++;t<i&&h(s.charCodeAt(t));)t++;e.push({kind:154,text:s.substring(a,t),start:a});continue}e.push({kind:142,text:".",start:t}),t++;continue}if(V(n)){let a=t;for(t++;t<i;){let c=s.charCodeAt(t);if($(c)||c===46)t++;else break}let o=s.substring(a,t);if(o.includes(".."))throw new Error(`Invalid identifier with consecutive dots at position ${a}: "${o}"`);let l=o.toUpperCase();if(l==="ORDER"&&!o.includes(".")){let c=W(s,t,"BY");if(c!==-1){let E=s.substring(a,c);e.push({kind:21,text:E,start:a}),t=c;continue}}if(l==="GROUP"&&!o.includes(".")){let c=W(s,t,"BY");if(c!==-1){let E=s.substring(a,c);e.push({kind:10,text:E,start:a}),t=c;continue}}if(l==="DATA"&&!o.includes(".")){let c=W(s,t,"CATEGORY");if(c!==-1){let E=s.substring(a,c);e.push({kind:35,text:E,start:a}),t=c;continue}}if(o.length>=4){let c=o.substring(0,3);if(se(c)){let E=o.substring(3);if(Ae(E)){E.includes(".")?e.push({kind:151,text:o,start:a}):e.push({kind:152,text:o,start:a});continue}}}if(o.length===3&&se(o)){let c=t,E=t,T=!1;if(E<i&&s.charCodeAt(E)===45&&(T=!0,E++),T&&E<i&&h(s.charCodeAt(E))){for(;E<i&&h(s.charCodeAt(E));)E++;if(E<i&&s.charCodeAt(E)===46&&E+1<i&&h(s.charCodeAt(E+1))){for(E++;E<i&&h(s.charCodeAt(E));)E++;let d=s.substring(a,E);e.push({kind:151,text:d,start:a}),t=E;continue}if(E>=i||!$(s.charCodeAt(E))&&s.charCodeAt(E)!==46){let d=s.substring(a,E);e.push({kind:152,text:d,start:a}),t=E;continue}t=c}}if(o.includes(".")){e.push({kind:159,text:o,start:a});continue}let u=fe.get(l);if(u!==void 0){e.push({kind:u,text:o,start:a});continue}e.push({kind:159,text:o,start:a});continue}throw new Error(`Unexpected character '${s[t]}' (code ${n}) at position ${t}`)}return e.push({kind:160,text:"",start:t}),e}function W(s,e,i){let t=s.length,n=e;if(n>=t||!G(s.charCodeAt(n)))return-1;for(;n<t&&G(s.charCodeAt(n));)n++;let a=i.length;if(n+a>t)return-1;for(let l=0;l<a;l++){let u=s.charCodeAt(n+l),c=i.charCodeAt(l);if((u>=97&&u<=122?u-32:u)!==c)return-1}let o=n+a;if(o<t){let l=s.charCodeAt(o);if($(l)||l===46)return-1}return o}function se(s){for(let e=0;e<s.length;e++)if(!V(s.charCodeAt(e)))return!1;return!0}function Ae(s){if(s.length===0)return!1;let e=0;if(s.charCodeAt(e)===45&&e++,e>=s.length||!h(s.charCodeAt(e)))return!1;for(;e<s.length&&h(s.charCodeAt(e));)e++;if(e<s.length&&s.charCodeAt(e)===46){if(e++,e>=s.length||!h(s.charCodeAt(e)))return!1;for(;e<s.length&&h(s.charCodeAt(e));)e++}return e===s.length}var de=new Set([23,9,26,21,10,11,16,27,28,29,25,19,2,3,0,20,17,45,41,5,36,42,143,139,160]),j=class s{constructor(e,i){this.pos=0;this.tokens=e,this.config=i}getPos(){return this.pos}peek(){return this.tokens[this.pos]}peekAt(e){let i=this.pos+e;return i>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[i]}advance(){let e=this.tokens[this.pos];return e.kind!==160&&this.pos++,e}expect(e){let i=this.peek();if(i.kind!==e)throw this.error(`Expected ${R[e]} but found ${R[i.kind]} ("${i.text}") at position ${i.start}`);return this.advance()}match(e){return this.peek().kind===e?(this.advance(),!0):!1}check(e){return this.peek().kind===e}isAtEnd(){return this.peek().kind===160}error(e){return this.config.logErrors&&console.log(e),new Error(e)}static{this.CLAUSE_BOUNDARY_KINDS=new Set([26,21,10,11,16,37,27,28,29,25,160])}isAtClauseBoundary(){let e=this.peek().kind;return s.CLAUSE_BOUNDARY_KINDS.has(e)||e===139}synchronize(){for(;!this.isAtEnd();){if(this.isAtClauseBoundary())return;this.advance()}}consumeIdentifier(){let e=this.peek();if(m(e.kind))return this.advance();throw this.error(`Expected identifier but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}checkIdentifier(){return m(this.peek().kind)}isFunctionCall(){let e=this.peek(),i=this.peekAt(1);return(y(e.kind)||F(e.kind)||B(e.kind)||H(e.kind)||b(e.kind))&&i.kind===138}canBeAlias(){let e=this.peek();return!(!m(e.kind)||de.has(e.kind)||e.kind===37&&this.peekAt(1).kind===156)}getLiteralType(e){let i=f(e);return i==="UNSIGNED_INTEGER"||i==="SIGNED_INTEGER"?"INTEGER":i==="UNSIGNED_DECIMAL"||i==="SIGNED_DECIMAL"?"DECIMAL":i==="CURRENCY_PREFIXED_DECIMAL"?"DECIMAL_WITH_CURRENCY_PREFIX":i==="CURRENCY_PREFIXED_INTEGER"?"INTEGER_WITH_CURRENCY_PREFIX":i==="DATETIME"?"DATETIME":i==="DATE"?"DATE":i==="NULL"?"NULL":i==="StringIdentifier"||i==="Identifier"?"STRING":i==="TRUE"||i==="FALSE"?"BOOLEAN":M(e)?"DATE_LITERAL":w(e)?"DATE_N_LITERAL":"STRING"}parseSelectStatement(e=!1){let i=this.parseSelectClause(),t=this.parseFromClause(),n;e?(n={fields:i,relationshipName:t.sObject},t.sObjectPrefix&&(n.sObjectPrefix=t.sObjectPrefix)):n={fields:i,sObject:t.sObject},t.alias&&(n.sObjectAlias=t.alias),this.applySObjectAlias(n);let a=this.parseClauseStatements();return Object.assign(n,a),n}parseSelectStatementPartial(){let e,i;this.check(23)&&(e=this.parseSelectClause()),this.check(9)&&(i=this.parseFromClause());let t={};e&&(t.fields=e),i&&(t.sObject=i.sObject,i.alias&&(t.sObjectAlias=i.alias)),t.fields&&this.applySObjectAlias(t);let n=this.parseClauseStatements();return Object.assign(t,n),t}applySObjectAlias(e){if(!e.sObjectAlias||!Array.isArray(e.fields))return;let i=e.sObjectAlias;e.fields.forEach(t=>{t.relationships&&t.relationships[0]===i&&(t.relationships=t.relationships.slice(1),t.objectPrefix=i,t.relationships.length===0&&(delete t.relationships,t.type="Field"))})}parseSelectClause(){this.expect(23);let e=[];for(e.push(this.parseSelectField());this.match(143);)e.push(this.parseSelectField());return e}parseSelectField(){let e=this.peek(),i=this.peekAt(1);return e.kind===138&&i.kind===23?this.parseSelectClauseSubqueryIdentifier():e.kind===42?this.parseSelectClauseTypeOf():this.isFunctionCall()?this.parseSelectClauseFunctionIdentifier():this.parseSelectClauseIdentifier()}parseSelectClauseFunctionIdentifier(){let e=this.parseAnyFunction(!0);return this.canBeAlias()&&(e.alias=this.consumeIdentifier().text),e}parseSelectClauseSubqueryIdentifier(){this.expect(138);let e=this.parseSelectStatement(!0);return this.expect(139),{type:"FieldSubquery",subquery:e}}parseSelectClauseTypeOf(){this.expect(42);let e=this.consumeIdentifier().text,i=[];for(;this.check(45);){this.advance();let t=this.consumeIdentifier().text;this.expect(41);let n=[];for(n.push(this.consumeIdentifier().text);this.match(143);)n.push(this.consumeIdentifier().text);i.push({type:"WHEN",objectType:t,fieldList:n})}if(this.check(5)){this.advance();let t=[];for(t.push(this.consumeIdentifier().text);this.match(143);)t.push(this.consumeIdentifier().text);i.push({type:"ELSE",fieldList:t})}return this.expect(36),{type:"FieldTypeof",field:e,conditions:i}}parseSelectClauseIdentifier(){let i=this.consumeIdentifier().text,t;if(!i.includes("."))t={type:"Field",field:i};else{let n=i.split(".");t={type:"FieldRelationship",field:n[n.length-1],relationships:n.slice(0,n.length-1),rawValue:i}}return this.canBeAlias()&&(t.alias=this.consumeIdentifier().text),t}parseFromClause(){this.expect(9);let i=this.consumeIdentifier().text,t;if(i.includes(".")){let n=i.split(".");t={sObjectPrefix:n.slice(0,n.length-1),sObject:n[n.length-1]}}else t={sObject:i};return this.canBeAlias()&&(t.alias=this.consumeIdentifier().text),t}parseClauseStatements(){let e={},i=(t,n)=>{if(this.config.ignoreParseErrors)try{t(),this.isAtClauseBoundary()||(n&&n(),this.synchronize())}catch(a){this.config.logErrors&&console.log(a),n&&n(),this.synchronize()}else t()};for(this.check(25)&&i(()=>{e.usingScope=this.parseUsingScope()}),this.check(26)&&i(()=>{e.where=this.parseWhereClause()},()=>{delete e.where});this.check(27);)i(()=>{let t=this.parseWithClause();t.withSecurityEnforced&&(e.withSecurityEnforced=!0),t.withAccessLevel&&(e.withAccessLevel=t.withAccessLevel),t.withDataCategory&&(e.withDataCategory=t.withDataCategory)});return this.check(10)&&(i(()=>{e.groupBy=this.parseGroupByClause()}),this.check(11)&&i(()=>{e.having=this.parseHavingClause()})),this.check(21)&&i(()=>{e.orderBy=this.parseOrderByClause()}),this.check(16)&&i(()=>{this.advance(),e.limit=Number(this.expect(156).text)}),this.check(37)&&i(()=>{this.advance(),e.offset=Number(this.expect(156).text)}),this.check(28)&&i(()=>{this.advance();let t=this.peek();if(t.kind===43||t.kind===38||t.kind===29)e.for=f(this.advance().kind);else throw this.error(`Expected VIEW, REFERENCE, or UPDATE after FOR at position ${t.start}`)}),this.check(29)&&i(()=>{this.advance();let t=this.peek();if(t.kind===40||t.kind===44)e.update=f(this.advance().kind);else throw this.error(`Expected TRACKING or VIEWSTAT after UPDATE at position ${t.start}`)}),e}parseUsingScope(){this.expect(25),this.expect(39);let e=this.peek();if(ae(e.kind))return this.advance().text;if(m(e.kind))return this.advance().text;throw this.error(`Expected scope enumeration value at position ${e.start}`)}parseWhereClause(){return this.expect(26),this.parseConditionExpressions(!0,!0)}parseConditionExpressions(e,i){let t,n,a={left:0,right:0};for(;;){let o;if(t)if(this.check(0))o="AND",this.advance();else if(this.check(20))o="OR",this.advance();else break;let l={},u=l,c=null;for(;this.hasNegationPrefix();){let d=0;for(;this.check(138)&&this.isNegationAhead();)this.advance(),d++,a.left++;if(this.check(17)){this.advance();let I={left:d>0?{openParen:d}:null,operator:"NOT",right:{left:{}}};c?c.right=I:l=I,c=I,u=I.right}else break}u.left=this.parseExpression(e,i,a),t?o&&(n.operator=o,n.right=l):(t=l,n=l);let E=l;for(;E.right&&E.right.left!==void 0;){let d=E.right;if(d.right&&d.right.left!==void 0)E=d;else{E=d;break}}if(n=E,this.isAtEnd())break;let T=this.peek().kind;if(T!==0&&T!==20)break}if(a.left!==a.right)throw this.error(`Mismatched parentheses in WHERE/HAVING clause: ${a.left} open vs ${a.right} close`);return t}hasNegationPrefix(){let e=0;for(;this.peekAt(e).kind===138;)e++;return this.peekAt(e).kind===17}isNegationAhead(){let e=1;for(;this.peekAt(e).kind===138;)e++;return this.peekAt(e).kind===17}parseExpression(e,i,t){let n=0;for(;this.check(138)&&!this.isSubqueryStart()&&!this.isArrayExpressionStart();)this.advance(),n++,t&&t.left++;let a,o=!1;e&&F(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseAggregateFunction(!1),o=!0):i&&B(this.peek().kind)&&this.peek().kind===68&&this.peekAt(1).kind===138?(a=this.parseLocationFunction(!1),o=!0):y(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseDateFunction(!1),o=!0):b(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseOtherFunction(!1),o=!0):a=this.consumeIdentifier().text;let l=this.parseOperator(),u=l.operator,c=l.isSet,E,T,d;if(c)if(this.check(138)&&this.peekAt(1).kind===23)this.expect(138),E=this.parseSelectStatement(!1),this.expect(139),T="SUBQUERY";else if(this.config.allowApexBindVariables&&this.check(144))E=this.parseApexBindVariable().value,T="APEX_BIND_VARIABLE";else{let g=this.parseArrayExpression();E=g.values,T=g.literalType,d=g.dateLiteralVariable}else{let g=this.parseAtomicValue();E=g.value,T=g.literalType,d=g.dateLiteralVariable}let I=0;for(;this.check(139)&&(!t||t.left>t.right);)this.advance(),I++,t&&t.right++;let _={};return o?_.fn=a:_.field=a,_.operator=u,T==="SUBQUERY"?_.valueQuery=E:_.value=E,_.literalType=T,d!==void 0&&(_.dateLiteralVariable=d),n>0&&(_.openParen=n),I>0&&(_.closeParen=I),_}isSubqueryStart(){return this.check(138)&&this.peekAt(1).kind===23}isArrayExpressionStart(){return!1}parseOperator(){let e=this.peek();if(oe(e.kind))return{operator:this.advance().text,isSet:!1};if(e.kind===15)return this.advance(),{operator:"LIKE",isSet:!1};if(e.kind===12)return this.advance(),{operator:"IN",isSet:!0};if(e.kind===17&&this.peekAt(1).kind===12)return this.advance(),this.advance(),{operator:"NOT IN",isSet:!0};if(e.kind===13)return this.advance(),{operator:"INCLUDES",isSet:!0};if(e.kind===6)return this.advance(),{operator:"EXCLUDES",isSet:!0};throw this.error(`Expected operator but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseAtomicValue(){let e=this.peek();if(this.config.allowApexBindVariables&&e.kind===144)return{value:this.parseApexBindVariable().value,literalType:"APEX_BIND_VARIABLE"};if(e.kind===157)return{value:this.advance().text,literalType:"STRING"};if(e.kind===158)return{value:this.advance().text,literalType:"STRING"};if(e.kind===156)return{value:this.advance().text,literalType:"INTEGER"};if(e.kind===155)return{value:this.advance().text,literalType:"INTEGER"};if(e.kind===154)return{value:this.advance().text,literalType:"DECIMAL"};if(e.kind===153)return{value:this.advance().text,literalType:"DECIMAL"};if(e.kind===151)return{value:this.advance().text,literalType:"DECIMAL_WITH_CURRENCY_PREFIX"};if(e.kind===152)return{value:this.advance().text,literalType:"INTEGER_WITH_CURRENCY_PREFIX"};if(e.kind===149)return{value:this.advance().text,literalType:"DATETIME"};if(e.kind===150)return{value:this.advance().text,literalType:"DATE"};if(e.kind===18)return this.advance(),{value:"NULL",literalType:"NULL"};if(e.kind===24||e.kind===7)return{value:f(this.advance().kind),literalType:"BOOLEAN"};if(M(e.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(w(e.kind)){let i=this.advance();this.expect(144);let t=this.peek(),n;if(t.kind===156||t.kind===155)n=Number(this.advance().text);else throw this.error(`Expected integer after date N literal colon at position ${t.start}`);return{value:`${i.text}:${n}`,literalType:"DATE_N_LITERAL",dateLiteralVariable:n}}throw this.error(`Expected value but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseArrayExpression(){this.expect(138);let e=[];for(e.push(this.parseArrayItem());this.match(143);)e.push(this.parseArrayItem());this.expect(139);let i=e.map(u=>u.value),t=e.map(u=>u.type),n=e.map(u=>u.variable!==void 0?u.variable:null),a=n.some(u=>u!==null),o;new Set(t).size===1?o=this.getLiteralType(this.tokenKindFromTypeName(t[0])):o=t.map(u=>this.getLiteralType(this.tokenKindFromTypeName(u)));let l={values:i,literalType:o};return a&&(l.dateLiteralVariable=n),l}tokenKindFromTypeName(e){for(let i=0;i<=160;i++)if(f(i)===e)return i;return 159}parseArrayItem(){let e=this.peek();if(e.kind===157)return{value:this.advance().text,type:f(157)};if(e.kind===158)return{value:this.advance().text,type:f(158)};if(e.kind===151)return{value:this.advance().text,type:f(151)};if(e.kind===152)return{value:this.advance().text,type:f(152)};if(Q(e.kind)){let i=this.advance();return{value:i.text,type:f(i.kind)}}if(e.kind===149)return{value:this.advance().text,type:f(149)};if(e.kind===150)return{value:this.advance().text,type:f(150)};if(e.kind===18)return this.advance(),{value:"NULL",type:"NULL"};if(e.kind===24)return{value:this.advance().text,type:"TRUE"};if(e.kind===7)return{value:this.advance().text,type:"FALSE"};if(M(e.kind))return{value:this.advance().text,type:f(e.kind)};if(w(e.kind)){let i=this.advance();this.expect(144);let t=this.peek(),n;if(t.kind===156||t.kind===155)n=Number(this.advance().text);else throw this.error(`Expected integer after date N literal colon at position ${t.start}`);return{value:`${i.text}:${n}`,type:f(i.kind),variable:n}}throw this.error(`Expected array value but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseApexBindVariable(){this.expect(144);let e=[];for(this.check(32)?e.push(this.parseApexBindNewInstantiation()):this.checkIdentifier()&&(this.peekAt(1).kind===138?e.push(this.parseApexBindFunctionCall()):e.push(this.parseApexBindIdentifier()));this.check(142);)this.advance(),this.checkIdentifier()&&this.peekAt(1).kind===138?e.push(this.parseApexBindFunctionCall()):this.checkIdentifier()&&e.push(this.parseApexBindIdentifier());return{value:e.join(".")}}parseApexBindIdentifier(){let e=this.consumeIdentifier().text;return this.check(140)&&(e+=this.parseApexBindArrayAccessor()),e}parseApexBindNewInstantiation(){this.expect(32);let i=`new ${this.consumeIdentifier().text}`;if(this.check(134)){this.advance();let t=[];for(t.push(this.consumeIdentifier().text);this.match(143);)t.push(this.consumeIdentifier().text);this.expect(136),i+=`<${t.join(", ")}>`}return i+=this.parseApexBindFunctionParams(),this.check(140)&&(i+=this.parseApexBindArrayAccessor()),i}parseApexBindFunctionCall(){let i=this.consumeIdentifier().text+this.parseApexBindFunctionParams();return this.check(140)&&(i+=this.parseApexBindArrayAccessor()),i}parseApexBindFunctionParams(){this.expect(138);let e=[];if(!this.check(139))for(e.push(this.consumeIdentifier().text);this.match(143);)e.push(this.consumeIdentifier().text);return this.expect(139),`(${e.join(", ")})`}parseApexBindArrayAccessor(){this.expect(140);let e=this.peek(),i;if(e.kind===156)i=this.advance().text;else if(m(e.kind))i=this.advance().text;else throw this.error(`Expected integer or identifier in array accessor at position ${e.start}`);return this.expect(141),`[${i}]`}parseAnyFunction(e){let i=this.peek();if(y(i.kind))return this.parseDateFunction(e);if(F(i.kind))return this.parseAggregateFunction(e);if(i.kind===68)return this.parseLocationFunction(e);if(H(i.kind))return this.parseFieldsFunction(e);if(b(i.kind))return this.parseOtherFunction(e);throw this.error(`Expected function name but found ${R[i.kind]} at position ${i.start}`)}parseDateFunction(e){let i=this.advance(),t=f(i.kind),n=this.parseFunctionExpression(!1,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=t,a.parameters=n,e&&(a.isAggregateFn=!0),a.rawValue=`${i.text}(${n.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseAggregateFunction(e){let i=this.advance(),t=f(i.kind),n=this.parseFunctionExpression(!0,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=t,a.parameters=n,e&&(a.isAggregateFn=!0),a.rawValue=`${i.text}(${n.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseFieldsFunction(e){this.advance(),this.expect(138);let i=this.peek(),t;if(ne(i.kind))t=this.advance().text;else if(m(i.kind))t=this.advance().text;else throw this.error(`Expected FIELDS function parameter at position ${i.start}`);this.expect(139);let n={};return e&&(n.type="FieldFunctionExpression"),n.functionName="FIELDS",n.parameters=[t],n.rawValue=`FIELDS(${t})`,n}parseOtherFunction(e){let i=this.advance(),t=f(i.kind),n=this.parseFunctionExpression(!1,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=t,a.parameters=n,a.rawValue=`${i.text}(${n.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseLocationFunction(e){this.advance(),this.expect(138);let i=this.consumeIdentifier().text;this.expect(143);let t;this.check(69)&&this.peekAt(1).kind===138?t=this.parseGeolocationFunction(e):t=this.consumeIdentifier().text,this.expect(143);let n=this.expect(158).text;this.expect(139);let a={};e&&(a.type="FieldFunctionExpression"),a.functionName="DISTANCE",a.parameters=[i,t,n],e&&(a.isAggregateFn=!0);let o=typeof t=="string"?t:t.rawValue;return a.rawValue=`DISTANCE(${i}, ${o}, ${n})`,a}parseGeolocationFunction(e){this.advance(),this.expect(138);let i=this.parseNumberValue();this.expect(143);let t=this.parseNumberValue();this.expect(139);let n={};return e&&(n.type="FieldFunctionExpression"),n.functionName="GEOLOCATION",n.parameters=[i,t],n.rawValue=`GEOLOCATION(${i}, ${t})`,n}parseNumberValue(){let e=this.peek();if(e.kind===156||e.kind===155||e.kind===154||e.kind===153)return this.advance().text;throw this.error(`Expected number but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseFunctionExpression(e,i=!0){this.expect(138);let t=[];if(!this.check(139))for(t.push(this.parseFunctionParam(e,i));this.match(143);)t.push(this.parseFunctionParam(e,i));return this.expect(139),t}parseFunctionParam(e,i){let t=this.peek(),n=this.peekAt(1);if(!e&&F(t.kind)&&n.kind===138)return this.parseAggregateFunction(i);if(b(t.kind)&&n.kind===138)return this.parseOtherFunction(i);if(t.kind===157)return this.advance().text;if(Q(t.kind))return this.advance().text;if(m(t.kind))return this.advance().text;throw this.error(`Expected function parameter but found ${R[t.kind]} ("${t.text}") at position ${t.start}`)}parseGroupByClause(){this.expect(10);let e=[];for(e.push(this.parseGroupByItem());this.match(143);)e.push(this.parseGroupByItem());return e}parseGroupByItem(){let e=this.peek();return e.kind===4&&this.peekAt(1).kind===138?{fn:this.parseCubeOrRollupFunction("CUBE")}:e.kind===22&&this.peekAt(1).kind===138?{fn:this.parseCubeOrRollupFunction("ROLLUP")}:y(e.kind)&&this.peekAt(1).kind===138?{fn:this.parseDateFunction(!1)}:{field:this.consumeIdentifier().text}}parseCubeOrRollupFunction(e){let i=this.advance(),t=this.parseFunctionExpression(!1);return{functionName:e,parameters:t,rawValue:`${e}(${t.join(", ")})`}}parseHavingClause(){return this.expect(11),this.parseConditionExpressions(!0,!1)}parseOrderByClause(){this.expect(21);let e=[];for(e.push(this.parseOrderByItem());this.match(143);)e.push(this.parseOrderByItem());return e}parseOrderByItem(){let e=this.peek(),i=this.peekAt(1),t;if(e.kind===75&&i.kind===138){let n=this.advance(),a=this.parseFunctionExpression(!1);t={fn:{functionName:f(n.kind),parameters:a,rawValue:`${n.text}(${a.join(", ")})`}}}else F(e.kind)&&i.kind===138?t={fn:this.parseAggregateFunction(!1)}:y(e.kind)&&i.kind===138?t={fn:this.parseDateFunction(!1)}:e.kind===68&&i.kind===138?t={fn:this.parseLocationFunction(!1)}:t={field:this.consumeIdentifier().text};if(this.check(2)?t.order=f(this.advance().kind):this.check(3)&&(t.order=f(this.advance().kind)),this.check(19))if(this.advance(),this.check(8))t.nulls=f(this.advance().kind);else if(this.check(14))t.nulls=f(this.advance().kind);else throw this.error(`Expected FIRST or LAST after NULLS at position ${this.peek().start}`);return t}parseWithClause(){this.expect(27);let e=this.peek();if(e.kind===46)return this.advance(),{withSecurityEnforced:!0};if(e.kind===48)return this.advance(),{withAccessLevel:"USER_MODE"};if(e.kind===47)return this.advance(),{withAccessLevel:"SYSTEM_MODE"};if(e.kind===35)return{withDataCategory:this.parseWithDataCategory()};throw this.error(`Expected SECURITY_ENFORCED, USER_MODE, SYSTEM_MODE, or DATA CATEGORY after WITH at position ${e.start}`)}parseWithDataCategory(){this.expect(35);let e=[];for(e.push(this.parseDataCategoryCondition());this.check(0);)this.advance(),e.push(this.parseDataCategoryCondition());return{conditions:e}}parseDataCategoryCondition(){let e=this.consumeIdentifier().text,i=this.peek(),t;if(i.kind===33||i.kind===30||i.kind===34||i.kind===31)t=this.advance().text;else throw this.error(`Expected data category selector (AT, ABOVE, BELOW, ABOVE_OR_BELOW) at position ${i.start}`);let n=this.match(138),a=[];for(a.push(this.consumeIdentifier().text);this.match(143);)a.push(this.consumeIdentifier().text);return n&&this.expect(139),{groupName:e,selector:t,parameters:a}}};function x(s,e){let i=e||{},t=le(s),n=new j(t,i),a;if(i.allowPartialQuery?a=n.parseSelectStatementPartial():a=n.parseSelectStatement(!1),!n.isAtEnd()&&!i.ignoreParseErrors){let o=t[n.getPos()];throw new Error(`Unexpected token "${o.text}" at position ${o.start}. Expected end of query.`)}return a}function X(s,e){try{return x(s,e),!0}catch{return!1}}function S(s){return typeof s=="string"}function L(s){return Number.isFinite(s)}function C(s){return s==null}function O(s,e,i){return C(s)?"":`${i||""}${s}${e||""}`}function ue(s,e=!1){return Array.isArray(s)?s.length>0?`(${s.join(", ")})`:e?"()":"":e?`(${s||""})`:s||""}function Ee(s,e,i=""){return L(s)&&s>0?new Array(s).fill(e).join(i):""}function K(s){return s&&!C(s.alias)}function D(s){return S(s.relationshipName)}function J(s){return!!s&&!!s.operator&&!!s.right}function z(s){return s&&!C(s.fn)&&S(s.operator)&&!C(s.value)}function k(s){return s&&L(s.openParen)&&C(s.operator)&&C(s.field)&&C(s.fn)&&C(s.closeParen)}function Z(s){return s&&S(s.field)&&S(s.operator)&&!C(s.valueQuery)&&C(s.value)}function ee(s){return s&&!C(s.field)}function te(s){return s&&!C(s.field)}function Ne(s){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(s)}function ce(s,e,i){if(C(e))return s;if(i&&e!=="APEX_BIND_VARIABLE"&&Ne(i)&&!Array.isArray(s)&&(s=[s],e=Array.isArray(e)?e:[e]),Array.isArray(e)&&Array.isArray(s))return s.map((t,n)=>Re(t,e?.[n]));switch(Array.isArray(e)&&(e=e[0]),e){case"STRING":return Array.isArray(s)?s.filter(Boolean).map(t=>q(t)):q(s);case"APEX_BIND_VARIABLE":return`:${s}`;default:return s}}function Re(s,e){switch(e){case"STRING":return q(s);case"NULL":return"null";default:return s}}function q(s){if(S(s)&&s.startsWith("'")&&s.endsWith("'")&&s.length>=2)return s;let e=String(s??"");return`'${_e(e)}'`}var Ce=/[nNrRtTbBfF"'\\_%]/,Te=/^[0-9a-fA-F]{4}$/;function _e(s){let e="";for(let i=0;i<s.length;i++){let t=s[i];if(t==="\\"){let n=s[i+1];n!==void 0&&Ce.test(n)?(e+=t+n,i++):n==="u"&&Te.test(s.substr(i+2,4))?(e+=s.substr(i,6),i+=5):e+="\\\\"}else t==="'"?e+="\\'":e+=t}return e}var P=class{constructor(e,i){this.currIndent=1;this.enabled=e,this.options={numIndent:i.numIndent??1,fieldMaxLineLength:i.fieldMaxLineLength??60,fieldSubqueryParensOnOwnLine:i.fieldSubqueryParensOnOwnLine??!0,whereClauseOperatorsIndented:!0,newLineAfterKeywords:i.newLineAfterKeywords??!1,logging:i.logging??!1},this.options.newLineAfterKeywords&&(this.options.fieldSubqueryParensOnOwnLine=!0)}log(e){this.options.logging&&console.log(e)}getIndent(e=0){return this.repeatChar((this.currIndent+e)*(this.options.numIndent||1)," ")}repeatChar(e,i){return new Array(e).fill(i).join("")}setSubquery(e){this.currIndent=e?this.currIndent+=1:this.currIndent-=1}stepCurrIndex(e){this.currIndent+=e}formatFields(e){function i(t){e.fields[t-1]&&(e.fields[t-1].suffix=e.fields[t-1].suffix.trim())}if(e.fields.forEach((t,n)=>{t.suffix=e.fields.length-1===n?"":", "}),this.enabled){let t=0,n=!1;e.fields.forEach((a,o)=>{a.isSubquery?(i(o),a.prefix=`
7
- ${this.getIndent()}`,a.suffix=e.fields.length-1===o?"":", ",t=0,n=!0):Array.isArray(a.typeOfClause)?(i(o),a.prefix=`
8
- ${this.getIndent()}`,n=!0):L(this.options.fieldMaxLineLength)&&(t+=a.text.length+a.suffix.length,(t>this.options.fieldMaxLineLength||n)&&(i(o),(!this.options.newLineAfterKeywords||o>0)&&(a.prefix+=`
9
- ${this.getIndent()}`),t=0,n=!1)),this.log(a)})}}formatTyeOfField(e,i){return this.enabled&&this.options.newLineAfterKeywords?i.map((t,n)=>n===0?t:n===i.length-1?`${this.getIndent()}${t}`:`${this.getIndent()} ${t}`).join(`
10
- `):e}formatTypeofFieldCondition(e){let i="",t=e.fieldList.join(", ");if(this.enabled&&this.options.newLineAfterKeywords){let n=this.getIndent();i=`${e.type}`,e.objectType?i+=`
11
- ${n} ${e.objectType}
12
- ${n} THEN
13
- ${n} ${t}`:i+=`
14
- ${n} ${t}`}else i=e.type,e.objectType?i+=` ${e.objectType} THEN ${t}`:i+=` ${t}`;return i}formatSubquery(e,i=2,t=!1){t&&i++;let n="(",a=")";return this.enabled&&(this.options.fieldSubqueryParensOnOwnLine||this.options.newLineAfterKeywords?(e=e.replace(/\n/g,`
15
- ${this.repeatChar(i," ")}`),n=`(
16
- ${this.repeatChar(i," ")}`,a=`
17
- ${this.repeatChar(i-1," ")})`):e=e.replace(/\n/g,`
18
- `)),`${n}${e}${a}`}formatClause(e){return this.enabled?this.options.newLineAfterKeywords?`
19
- ${e}
20
- ${this.getIndent()}`:`
21
- ${e}`:` ${e}`}formatText(e){return this.enabled&&(this.options.newLineAfterKeywords||e.startsWith(`
22
- `))?e:` ${e}`}formatWithIndent(e){return this.enabled?`${this.getIndent()}${e}`:e}formatOrderByArray(e){if(this.enabled){let i=0,t="";return e.forEach((n,a)=>{let o=e[a+1];i+=n.length,o&&(i+o.length>(this.options.fieldMaxLineLength||0)||this.options.newLineAfterKeywords)?(t+=`${n},
23
- `,i=0):t+=`${n}${o?", ":""}`}),t}else return e.join(", ")}formatParens(e,i,t=!1){let n="";if(L(e)&&e>0)if(this.enabled)if(i==="("){for(let a=0;a<e;a++)t&&a===e-1?n+="(":a===0?n+=`(
24
- `:(this.currIndent++,n+=`${this.getIndent()}(
25
- `);(!t||e>1)&&this.currIndent++}else for(let a=e-1;a>=0;a--)t&&a===e-1?n+=")":(this.currIndent--,n+=`
26
- ${this.getIndent()})`);else n+=Ee(e,i);return n}formatWhereClauseOperators(e,i,t=0){let n=e==="NOT";return this.enabled&&!n?`
27
- ${this.getIndent(t)}${e} ${i}`:`${n?"":" "}${e} ${i}`}formatAddNewLine(e=" ",i){return this.enabled&&!i?`
28
- `:e}};function he(s,e,i){return re(x(s,i),{format:!0,formatOptions:e})}function re(s,e={}){if(!s)return"";e=e||{},e.format=!!e.format,e.logging&&(console.time("composer"),console.log("Composing Query:",s),console.log("Format output:",e.format));let i=new ie(s,e).query;return e.logging&&console.timeEnd("composer"),i}var ie=class{constructor(e,i={}){this.soql=e;this.logging=!1;this.format=!1;i={autoCompose:!0,...i};let{logging:t,format:n}=i;this.logging=!!t,this.format=!!n,this.query="",this.formatter=new P(this.format,{logging:this.logging,...i.formatOptions}),i.autoCompose&&this.start()}start(){this.query=this.parseQuery(this.soql)}log(e){this.logging&&console.log("Current SOQL:",e)}parseFn(e){let i;return e.rawValue?i=e.rawValue:(i=e.functionName,i+=`(${(e.parameters||[]).map(t=>S(t)?t:this.parseFn(t)).join(", ")})`),e.alias&&(i+=` ${e.alias}`),i}parseQuery(e){let i={fields:this.parseFields(e.fields||[]).map(a=>({text:a.text,typeOfClause:a.typeOfClause,isSubquery:a.text.startsWith("("),prefix:"",suffix:""})),isSubquery:D(e),lineBreaks:[]},t="";e.fields&&(t+=this.formatter.formatClause("SELECT").trimStart()),this.formatter.formatFields(i);let n="";if(i.fields.forEach(a=>{Array.isArray(a.typeOfClause)?n+=`${a.prefix}${this.formatter.formatTyeOfField(a.text,a.typeOfClause)}${a.suffix}`:n+=`${a.prefix}${a.text}${a.suffix}`}),t+=this.formatter.formatText(n),(D(e)?e.relationshipName:e.sObject)&&(t+=this.formatter.formatClause("FROM")),D(e)){let a=e.sObjectPrefix||[];a.push(e.relationshipName),t+=this.formatter.formatText(`${a.join(".")}${O(e.sObjectAlias,""," ")}`)}else e.sObject&&(t+=this.formatter.formatText(`${e.sObject}${O(e.sObjectAlias,""," ")}`));return this.log(t),e.usingScope&&(t+=this.formatter.formatClause("USING SCOPE"),t+=this.formatter.formatText(e.usingScope),this.log(t)),e.where&&(t+=this.formatter.formatClause("WHERE"),t+=this.formatter.formatText(this.parseWhereOrHavingClause(e.where)),this.log(t)),e.groupBy&&(t+=this.formatter.formatClause("GROUP BY"),t+=this.formatter.formatText(this.parseGroupByClause(e.groupBy)),this.log(t),e.having&&(t+=this.formatter.formatClause("HAVING"),t+=this.formatter.formatText(this.parseWhereOrHavingClause(e.having)),this.log(t))),e.orderBy&&(!Array.isArray(e.orderBy)||e.orderBy.length>0)&&(t+=this.formatter.formatClause("ORDER BY"),t+=this.formatter.formatText(this.parseOrderBy(e.orderBy)),this.log(t)),L(e.limit)&&(t+=this.formatter.formatClause("LIMIT"),t+=this.formatter.formatText(`${e.limit}`),this.log(t)),L(e.offset)&&(t+=this.formatter.formatClause("OFFSET"),t+=this.formatter.formatText(`${e.offset}`),this.log(t)),e.withDataCategory&&(t+=this.formatter.formatClause("WITH DATA CATEGORY"),t+=this.formatter.formatText(this.parseWithDataCategory(e.withDataCategory)),this.log(t)),e.withSecurityEnforced&&(t+=this.formatter.formatClause("WITH SECURITY_ENFORCED"),this.log(t)),e.withAccessLevel&&(t+=this.formatter.formatClause(`WITH ${e.withAccessLevel}`),this.log(t)),e.for&&(t+=this.formatter.formatClause("FOR"),t+=this.formatter.formatText(e.for),this.log(t)),e.update&&(t+=this.formatter.formatClause("UPDATE"),t+=this.formatter.formatText(e.update),this.log(t)),t.trim()}parseFields(e){return e.map(i=>{let t="",n,a=i.objectPrefix?`${i.objectPrefix}.`:"";switch(i.type){case"Field":{t=`${a}${i.field}${i.alias?` ${i.alias}`:""}`;break}case"FieldFunctionExpression":{let o="";i.parameters&&(o=i.parameters.map(l=>S(l)?l:this.parseFields([l]).map(u=>u.text)).join(", ")),t=`${i.functionName}(${o})${i.alias?` ${i.alias}`:""}`;break}case"FieldRelationship":{t=`${a}${i.relationships.join(".")}.${i.field}${K(i)?` ${i.alias}`:""}`;break}case"FieldSubquery":{t=this.formatter.formatSubquery(this.parseQuery(i.subquery));break}case"FieldTypeof":{n=this.parseTypeOfField(i),t=n.join(" ");break}default:break}return{text:t,typeOfClause:n}})}parseTypeOfField(e){let i=[`TYPEOF ${e.field}`].concat(e.conditions.map(t=>this.formatter.formatTypeofFieldCondition(t)));return i.push("END"),i}parseWhereOrHavingClause(e,i=0,t=!1){let n="",a=e.left,o=!1;if(a&&(n+=this.formatter.formatParens(a.openParen,"(",k(a)),!k(a))){i=i+(a.openParen||0)-(a.closeParen||0),t&&i++;let l="";l+=z(a)?this.parseFn(a.fn):a.field,l+=` ${a.operator} `,Z(a)?l+=this.formatter.formatSubquery(this.parseQuery(a.valueQuery),1,!0):l+=ue(ce(a.value,a.literalType,a.operator)),n+=this.formatter.formatWithIndent(l),n+=this.formatter.formatParens(a.closeParen,")",t)}if(J(e)){let l=O(e.operator);o=l==="NOT";let u=this.formatter.formatWhereClauseOperators(l,this.parseWhereOrHavingClause(e.right,i,k(a)),i);return`${o?n.trimRight():n}${u}`.trim()}else return n.trim()}parseGroupByClause(e){return(Array.isArray(e)?e:[e]).map(i=>te(i)?i.field:this.parseFn(i.fn)).join(", ")}parseOrderBy(e){if(Array.isArray(e))return this.formatter.formatOrderByArray(e.map(i=>this.parseOrderBy(i)));{let i="";return ee(e)?i=`${O(e.field," ")}`:i+=`${this.parseFn(e.fn)} `,i+=`${O(e.order," ")}${O(e.nulls,"","NULLS ")}`,i.trim()}}parseWithDataCategory(e){return e.conditions.map(i=>{let t=i.parameters.length>1?`(${i.parameters.join(", ")})`:`${i.parameters.join(", ")}`;return`${i.groupName} ${i.selector} ${t}`}).join(" AND ")}};function Ie(s){let e=s.slice(2),i=e[0]??"",t=e[1]??"",n={};for(let a=2;a<e.length;a++){let o=e[a];if(o.startsWith("--")){let l=o.slice(2),u=e[a+1];u&&!u.startsWith("-")?(n[l]=u,a++):n[l]=!0}else if(o.startsWith("-")&&o.length===2){let l=o.slice(1),u=e[a+1];u&&!u.startsWith("-")?(n[l]=u,a++):n[l]=!0}}return{command:i,query:t,flags:n}}function N(s,e,i){return s[e]===!0||s[i]===!0}function v(s,e,i){let t=s[e]??s[i];return typeof t=="string"?t:void 0}function pe(){console.log(`Usage: soql-parser-js <command> <query> [options]
6
+ "use strict";function S(t){return typeof t=="string"}function I(t){return Number.isFinite(t)}function N(t){return t==null}function F(t,e,r){return N(t)?"":`${r||""}${t}${e||""}`}function Ne(t,e=!1){return Array.isArray(t)?t.length>0?`(${t.join(", ")})`:e?"()":"":e?`(${t||""})`:t||""}function $(t,e,r=""){return I(t)&&t>0?Array.from({length:t},()=>e).join(r):""}function Re(t){return t&&!N(t.alias)}function Te(t){return S(t.relationshipName)}function b(t){return!!t&&!!t.operator&&!!t.right}function Ce(t){return t&&!N(t.fn)&&S(t.operator)&&!N(t.value)}function k(t){return t&&I(t.openParen)&&N(t.operator)&&N(t.field)&&N(t.fn)&&N(t.closeParen)}function W(t){return t&&S(t.field)&&S(t.operator)&&!N(t.valueQuery)&&N(t.value)}function _e(t){return t&&!N(t.field)}function Se(t){return t&&!N(t.field)}function we(t){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(t)}function ye(t,e,r){if(N(e))return t;if(r&&e!=="APEX_BIND_VARIABLE"&&we(r)&&!Array.isArray(t)&&(t=[t],e=Array.isArray(e)?e:[e]),Array.isArray(e)&&Array.isArray(t))return t.map((i,s)=>Ge(i,e?.[s]));switch(Array.isArray(e)&&(e=e[0]),e){case"STRING":return Array.isArray(t)?t.filter(Boolean).map(i=>J(i)):J(t);case"APEX_BIND_VARIABLE":return`:${t}`;default:return t}}function Ge(t,e){switch(e){case"STRING":return J(t);case"NULL":return"null";default:return t}}function J(t){if(S(t)&&t.startsWith("'")&&t.endsWith("'")&&t.length>=2)return t;let e=String(t??"");return`'${Ye(e)}'`}var Me=/[nNrRtTbBfF"'\\_%]/,Pe=/^[0-9a-fA-F]{4}$/;function Ye(t){let e="";for(let r=0;r<t.length;r++){let i=t[r];if(i==="\\"){let s=t[r+1];s!==void 0&&Me.test(s)?(e+=i+s,r++):s==="u"&&Pe.test(t.substr(r+2,4))?(e+=t.substr(r,6),r+=5):e+="\\\\"}else i==="'"?e+="\\'":e+=i}return e}var ee="[A-Za-z][A-Za-z0-9_]*",Ie=`${ee}(?:\\.${ee})*`,$e=new RegExp(`^\\s*(${Ie})\\s*([+-])\\s*(${Ie})\\s*$`),We=new RegExp(`^${ee}$`);function ge(t){return t?.functionName==="FORMULA"&&!N(t.formula)}function Le(t){return{type:"FieldReference",parts:t.split(".")}}function Fe(t){let e=$e.exec(t);if(e)return{type:"BinaryExpression",operator:e[2],left:Le(e[1]),right:Le(e[3])}}function Oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="string"&&We.test(e))}function B(t){let e=t?.left?.parts,r=t?.right?.parts,i=t?.operator;if(i!=="+"&&i!=="-"||!Oe(e)||!Oe(r))throw new Error("Invalid FORMULA expression. Expected two field references separated by + or -.");return`${e.join(".")} ${i} ${r.join(".")}`}var R=(n=>(n[n.AND=0]="AND",n[n.AS=1]="AS",n[n.ASC=2]="ASC",n[n.DESC=3]="DESC",n[n.CUBE=4]="CUBE",n[n.ELSE=5]="ELSE",n[n.EXCLUDES=6]="EXCLUDES",n[n.FALSE=7]="FALSE",n[n.FIRST=8]="FIRST",n[n.FROM=9]="FROM",n[n.GROUP_BY=10]="GROUP_BY",n[n.HAVING=11]="HAVING",n[n.IN=12]="IN",n[n.INCLUDES=13]="INCLUDES",n[n.LAST=14]="LAST",n[n.LIKE=15]="LIKE",n[n.LIMIT=16]="LIMIT",n[n.NOT=17]="NOT",n[n.NULL=18]="NULL",n[n.NULLS=19]="NULLS",n[n.OR=20]="OR",n[n.ORDER_BY=21]="ORDER_BY",n[n.ROLLUP=22]="ROLLUP",n[n.SELECT=23]="SELECT",n[n.TRUE=24]="TRUE",n[n.USING=25]="USING",n[n.WHERE=26]="WHERE",n[n.WITH=27]="WITH",n[n.FOR=28]="FOR",n[n.UPDATE=29]="UPDATE",n[n.ABOVE=30]="ABOVE",n[n.ABOVE_OR_BELOW=31]="ABOVE_OR_BELOW",n[n.APEX_NEW=32]="APEX_NEW",n[n.AT=33]="AT",n[n.BELOW=34]="BELOW",n[n.DATA_CATEGORY=35]="DATA_CATEGORY",n[n.END=36]="END",n[n.OFFSET=37]="OFFSET",n[n.REFERENCE=38]="REFERENCE",n[n.SCOPE=39]="SCOPE",n[n.TRACKING=40]="TRACKING",n[n.THEN=41]="THEN",n[n.TYPEOF=42]="TYPEOF",n[n.VIEW=43]="VIEW",n[n.VIEWSTAT=44]="VIEWSTAT",n[n.WHEN=45]="WHEN",n[n.SECURITY_ENFORCED=46]="SECURITY_ENFORCED",n[n.SYSTEM_MODE=47]="SYSTEM_MODE",n[n.USER_MODE=48]="USER_MODE",n[n.CALENDAR_MONTH=49]="CALENDAR_MONTH",n[n.CALENDAR_QUARTER=50]="CALENDAR_QUARTER",n[n.CALENDAR_YEAR=51]="CALENDAR_YEAR",n[n.DAY_IN_MONTH=52]="DAY_IN_MONTH",n[n.DAY_IN_WEEK=53]="DAY_IN_WEEK",n[n.DAY_IN_YEAR=54]="DAY_IN_YEAR",n[n.DAY_ONLY=55]="DAY_ONLY",n[n.FISCAL_MONTH=56]="FISCAL_MONTH",n[n.FISCAL_QUARTER=57]="FISCAL_QUARTER",n[n.FISCAL_YEAR=58]="FISCAL_YEAR",n[n.HOUR_IN_DAY=59]="HOUR_IN_DAY",n[n.WEEK_IN_MONTH=60]="WEEK_IN_MONTH",n[n.WEEK_IN_YEAR=61]="WEEK_IN_YEAR",n[n.AVG=62]="AVG",n[n.COUNT=63]="COUNT",n[n.COUNT_DISTINCT=64]="COUNT_DISTINCT",n[n.MIN=65]="MIN",n[n.MAX=66]="MAX",n[n.SUM=67]="SUM",n[n.DISTANCE=68]="DISTANCE",n[n.GEOLOCATION=69]="GEOLOCATION",n[n.FIELDS=70]="FIELDS",n[n.FORMAT=71]="FORMAT",n[n.TOLABEL=72]="TOLABEL",n[n.CONVERT_TIMEZONE=73]="CONVERT_TIMEZONE",n[n.CONVERT_CURRENCY=74]="CONVERT_CURRENCY",n[n.GROUPING=75]="GROUPING",n[n.FORMULA=76]="FORMULA",n[n.ALL=77]="ALL",n[n.CUSTOM=78]="CUSTOM",n[n.STANDARD=79]="STANDARD",n[n.YESTERDAY=80]="YESTERDAY",n[n.TODAY=81]="TODAY",n[n.TOMORROW=82]="TOMORROW",n[n.LAST_WEEK=83]="LAST_WEEK",n[n.THIS_WEEK=84]="THIS_WEEK",n[n.NEXT_WEEK=85]="NEXT_WEEK",n[n.LAST_MONTH=86]="LAST_MONTH",n[n.THIS_MONTH=87]="THIS_MONTH",n[n.NEXT_MONTH=88]="NEXT_MONTH",n[n.LAST_90_DAYS=89]="LAST_90_DAYS",n[n.NEXT_90_DAYS=90]="NEXT_90_DAYS",n[n.THIS_QUARTER=91]="THIS_QUARTER",n[n.LAST_QUARTER=92]="LAST_QUARTER",n[n.NEXT_QUARTER=93]="NEXT_QUARTER",n[n.THIS_YEAR=94]="THIS_YEAR",n[n.LAST_YEAR=95]="LAST_YEAR",n[n.NEXT_YEAR=96]="NEXT_YEAR",n[n.THIS_FISCAL_QUARTER=97]="THIS_FISCAL_QUARTER",n[n.LAST_FISCAL_QUARTER=98]="LAST_FISCAL_QUARTER",n[n.NEXT_FISCAL_QUARTER=99]="NEXT_FISCAL_QUARTER",n[n.THIS_FISCAL_YEAR=100]="THIS_FISCAL_YEAR",n[n.LAST_FISCAL_YEAR=101]="LAST_FISCAL_YEAR",n[n.NEXT_FISCAL_YEAR=102]="NEXT_FISCAL_YEAR",n[n.NEXT_N_DAYS=103]="NEXT_N_DAYS",n[n.LAST_N_DAYS=104]="LAST_N_DAYS",n[n.N_DAYS_AGO=105]="N_DAYS_AGO",n[n.NEXT_N_WEEKS=106]="NEXT_N_WEEKS",n[n.LAST_N_WEEKS=107]="LAST_N_WEEKS",n[n.N_WEEKS_AGO=108]="N_WEEKS_AGO",n[n.NEXT_N_MONTHS=109]="NEXT_N_MONTHS",n[n.LAST_N_MONTHS=110]="LAST_N_MONTHS",n[n.N_MONTHS_AGO=111]="N_MONTHS_AGO",n[n.NEXT_N_QUARTERS=112]="NEXT_N_QUARTERS",n[n.LAST_N_QUARTERS=113]="LAST_N_QUARTERS",n[n.N_QUARTERS_AGO=114]="N_QUARTERS_AGO",n[n.NEXT_N_YEARS=115]="NEXT_N_YEARS",n[n.LAST_N_YEARS=116]="LAST_N_YEARS",n[n.N_YEARS_AGO=117]="N_YEARS_AGO",n[n.NEXT_N_FISCAL_QUARTERS=118]="NEXT_N_FISCAL_QUARTERS",n[n.LAST_N_FISCAL_QUARTERS=119]="LAST_N_FISCAL_QUARTERS",n[n.N_FISCAL_QUARTERS_AGO=120]="N_FISCAL_QUARTERS_AGO",n[n.NEXT_N_FISCAL_YEARS=121]="NEXT_N_FISCAL_YEARS",n[n.LAST_N_FISCAL_YEARS=122]="LAST_N_FISCAL_YEARS",n[n.N_FISCAL_YEARS_AGO=123]="N_FISCAL_YEARS_AGO",n[n.DELEGATED=124]="DELEGATED",n[n.EVERYTHING=125]="EVERYTHING",n[n.MINE_AND_MY_GROUPS=126]="MINE_AND_MY_GROUPS",n[n.MINE=127]="MINE",n[n.MY_TERRITORY=128]="MY_TERRITORY",n[n.MY_TEAM_TERRITORY=129]="MY_TEAM_TERRITORY",n[n.TEAM=130]="TEAM",n[n.ALL_PRIVATE=131]="ALL_PRIVATE",n[n.MRU=132]="MRU",n[n.EQUAL=133]="EQUAL",n[n.NOT_EQUAL=134]="NOT_EQUAL",n[n.LESS_THAN=135]="LESS_THAN",n[n.LESS_THAN_OR_EQUAL=136]="LESS_THAN_OR_EQUAL",n[n.GREATER_THAN=137]="GREATER_THAN",n[n.GREATER_THAN_OR_EQUAL=138]="GREATER_THAN_OR_EQUAL",n[n.L_PAREN=139]="L_PAREN",n[n.R_PAREN=140]="R_PAREN",n[n.L_SQUARE_BRACKET=141]="L_SQUARE_BRACKET",n[n.R_SQUARE_BRACKET=142]="R_SQUARE_BRACKET",n[n.DOT=143]="DOT",n[n.COMMA=144]="COMMA",n[n.COLON=145]="COLON",n[n.SEMICOLON=146]="SEMICOLON",n[n.ASTERISK=147]="ASTERISK",n[n.PLUS=148]="PLUS",n[n.MINUS=149]="MINUS",n[n.DATETIME=150]="DATETIME",n[n.DATE_TOKEN=151]="DATE_TOKEN",n[n.CURRENCY_PREFIXED_DECIMAL=152]="CURRENCY_PREFIXED_DECIMAL",n[n.CURRENCY_PREFIXED_INTEGER=153]="CURRENCY_PREFIXED_INTEGER",n[n.SIGNED_DECIMAL=154]="SIGNED_DECIMAL",n[n.UNSIGNED_DECIMAL=155]="UNSIGNED_DECIMAL",n[n.SIGNED_INTEGER=156]="SIGNED_INTEGER",n[n.UNSIGNED_INTEGER=157]="UNSIGNED_INTEGER",n[n.STRING_LITERAL=158]="STRING_LITERAL",n[n.GEOLOCATION_UNIT=159]="GEOLOCATION_UNIT",n[n.IDENTIFIER=160]="IDENTIFIER",n[n.EOF=161]="EOF",n))(R||{});function m(t){return t>=49&&t<=61}function x(t){return t>=62&&t<=67}function re(t){return t>=68&&t<=69}function ne(t){return t===70}function U(t){return t>=71&&t<=75}function xe(t){return t>=77&&t<=79}function Q(t){return t>=80&&t<=102}function V(t){return t>=103&&t<=123}function De(t){return t>=124&&t<=132}function L(t){return t===160||t>=30&&t<=48||t>=49&&t<=61||t>=62&&t<=67||t>=68&&t<=69||t===70||t>=71&&t<=75||t===76||t>=77&&t<=79||t>=80&&t<=102||t>=103&&t<=123||t>=124&&t<=132||t===159||t===153}function se(t){return t===154||t===155||t===156||t===157}function ae(t){return t>=133&&t<=138}var Be=new Map([["AND",0],["AS",1],["ASC",2],["DESC",3],["CUBE",4],["ELSE",5],["EXCLUDES",6],["FALSE",7],["FIRST",8],["FROM",9],["HAVING",11],["IN",12],["INCLUDES",13],["LAST",14],["LIKE",15],["LIMIT",16],["NOT",17],["NULL",18],["NULLS",19],["OR",20],["ROLLUP",22],["SELECT",23],["TRUE",24],["USING",25],["WHERE",26],["WITH",27],["FOR",28],["UPDATE",29],["ABOVE_OR_BELOW",31],["ABOVE",30],["NEW",32],["AT",33],["BELOW",34],["END",36],["OFFSET",37],["REFERENCE",38],["SCOPE",39],["TRACKING",40],["THEN",41],["TYPEOF",42],["VIEW",43],["VIEWSTAT",44],["WHEN",45],["SECURITY_ENFORCED",46],["SYSTEM_MODE",47],["USER_MODE",48],["CALENDAR_MONTH",49],["CALENDAR_QUARTER",50],["CALENDAR_YEAR",51],["DAY_IN_MONTH",52],["DAY_IN_WEEK",53],["DAY_IN_YEAR",54],["DAY_ONLY",55],["FISCAL_MONTH",56],["FISCAL_QUARTER",57],["FISCAL_YEAR",58],["HOUR_IN_DAY",59],["WEEK_IN_MONTH",60],["WEEK_IN_YEAR",61],["AVG",62],["COUNT_DISTINCT",64],["COUNT",63],["MIN",65],["MAX",66],["SUM",67],["DISTANCE",68],["GEOLOCATION",69],["FIELDS",70],["FORMAT",71],["TOLABEL",72],["CONVERTTIMEZONE",73],["CONVERTCURRENCY",74],["GROUPING",75],["FORMULA",76],["ALL",77],["CUSTOM",78],["STANDARD",79],["YESTERDAY",80],["TODAY",81],["TOMORROW",82],["LAST_WEEK",83],["THIS_WEEK",84],["NEXT_WEEK",85],["LAST_MONTH",86],["THIS_MONTH",87],["NEXT_MONTH",88],["LAST_90_DAYS",89],["NEXT_90_DAYS",90],["THIS_QUARTER",91],["LAST_QUARTER",92],["NEXT_QUARTER",93],["THIS_YEAR",94],["LAST_YEAR",95],["NEXT_YEAR",96],["THIS_FISCAL_QUARTER",97],["LAST_FISCAL_QUARTER",98],["NEXT_FISCAL_QUARTER",99],["THIS_FISCAL_YEAR",100],["LAST_FISCAL_YEAR",101],["NEXT_FISCAL_YEAR",102],["NEXT_N_DAYS",103],["LAST_N_DAYS",104],["N_DAYS_AGO",105],["NEXT_N_WEEKS",106],["LAST_N_WEEKS",107],["N_WEEKS_AGO",108],["NEXT_N_MONTHS",109],["LAST_N_MONTHS",110],["N_MONTHS_AGO",111],["NEXT_N_QUARTERS",112],["LAST_N_QUARTERS",113],["N_QUARTERS_AGO",114],["NEXT_N_YEARS",115],["LAST_N_YEARS",116],["N_YEARS_AGO",117],["NEXT_N_FISCAL_QUARTERS",118],["LAST_N_FISCAL_QUARTERS",119],["N_FISCAL_QUARTERS_AGO",120],["NEXT_N_FISCAL_YEARS",121],["LAST_N_FISCAL_YEARS",122],["N_FISCAL_YEARS_AGO",123],["DELEGATED",124],["EVERYTHING",125],["MINEANDMYGROUPS",126],["MINE",127],["MY_TERRITORY",128],["MY_TEAM_TERRITORY",129],["TEAM",130],["ALLPRIVATE",131],["MRU",132]]),f=[];(function(){for(let e of Object.keys(R)){let r=R[e];typeof r=="number"&&(f[r]=e)}f[72]="toLabel",f[73]="convertTimezone",f[74]="convertCurrency",f[158]="StringIdentifier",f[151]="DATE",f[32]="new",f[126]="MineAndMyGroups",f[128]="MyTerritory",f[129]="MyTeamTerritory",f[131]="AllPrivate",f[124]="Delegated",f[125]="Everything",f[127]="Mine",f[130]="Team",f[132]="Mru",f[160]="Identifier",f[133]="EQUAL",f[157]="UNSIGNED_INTEGER",f[156]="SIGNED_INTEGER",f[155]="UNSIGNED_DECIMAL",f[154]="SIGNED_DECIMAL",f[152]="CURRENCY_PREFIXED_DECIMAL",f[153]="CURRENCY_PREFIXED_INTEGER"})();function A(t){return f[t]||R[t]}function oe(t){return t>=65&&t<=90||t>=97&&t<=122}function h(t){return t>=48&&t<=57}function ie(t){return oe(t)||h(t)||t===95}function H(t){return t===32||t===9||t===10||t===13||t===12}function be(t){let e=[],r=t.length,i=0;for(;i<r;){let s=t.charCodeAt(i);if(H(s)){for(i++;i<r&&H(t.charCodeAt(i));)i++;continue}if(s===47){let a=i+1<r?t.charCodeAt(i+1):0;if(a===47){for(i+=2;i<r;){let o=t.charCodeAt(i);if(o===10||o===13)break;i++}continue}if(a===42){let o=i;i+=2;let l=!1;for(;i<r;){if(t.charCodeAt(i)===42&&i+1<r&&t.charCodeAt(i+1)===47){i+=2,l=!0;break}i++}if(!l)throw new Error(`Unterminated comment at position ${o}`);continue}}if(s===39){let a=i;for(i++;i<r;){let c=t.charCodeAt(i);if(c===92){i+=2;continue}if(c===39){i++;break}i++}let o=t.substring(a,i),p=o.substring(1,o.length-1).toUpperCase();p==="MI"||p==="KM"?e.push({kind:159,text:o,start:a}):e.push({kind:158,text:o,start:a});continue}if(h(s)){if(i+9<r&&t.charCodeAt(i+4)===45&&t.charCodeAt(i+7)===45){let o=!0;for(let l of[0,1,2,3,5,6,8,9])if(!h(t.charCodeAt(i+l))){o=!1;break}if(o)if(i+10<r&&(t.charCodeAt(i+10)===84||t.charCodeAt(i+10)===116)){let l=i;for(i+=11;i<r;){let p=t.charCodeAt(i);if(h(p)||p===58)i++;else break}if(i<r&&t.charCodeAt(i)===46)for(i++;i<r&&h(t.charCodeAt(i));)i++;if(i<r){let p=t.charCodeAt(i);if(p===90||p===122)i++;else if(p===46){for(i++;i<r&&h(t.charCodeAt(i));)i++;i<r&&(t.charCodeAt(i)===90||t.charCodeAt(i)===122)&&i++}else if(p===43||p===45)for(i++;i<r;){let c=t.charCodeAt(i);if(h(c)||c===58)i++;else break}}e.push({kind:150,text:t.substring(l,i),start:l});continue}else{let l=i;i+=10,e.push({kind:151,text:t.substring(l,i),start:l});continue}}let a=i;for(;i<r&&h(t.charCodeAt(i));)i++;if(i<r&&t.charCodeAt(i)===46&&i+1<r&&h(t.charCodeAt(i+1))){for(i++;i<r&&h(t.charCodeAt(i));)i++;e.push({kind:155,text:t.substring(a,i),start:a});continue}e.push({kind:157,text:t.substring(a,i),start:a});continue}if(s===33){if(i+1<r&&t.charCodeAt(i+1)===61){e.push({kind:134,text:"!=",start:i}),i+=2;continue}throw new Error(`Unexpected character '!' at position ${i}`)}if(s===60){if(i+1<r){let a=t.charCodeAt(i+1);if(a===61){e.push({kind:136,text:"<=",start:i}),i+=2;continue}if(a===62){e.push({kind:134,text:"<>",start:i}),i+=2;continue}}e.push({kind:135,text:"<",start:i}),i++;continue}if(s===62){if(i+1<r&&t.charCodeAt(i+1)===61){e.push({kind:138,text:">=",start:i}),i+=2;continue}e.push({kind:137,text:">",start:i}),i++;continue}if(s===61){e.push({kind:133,text:"=",start:i}),i++;continue}if(s===40){e.push({kind:139,text:"(",start:i}),i++;continue}if(s===41){e.push({kind:140,text:")",start:i}),i++;continue}if(s===91){e.push({kind:141,text:"[",start:i}),i++;continue}if(s===93){e.push({kind:142,text:"]",start:i}),i++;continue}if(s===44){e.push({kind:144,text:",",start:i}),i++;continue}if(s===58){e.push({kind:145,text:":",start:i}),i++;continue}if(s===59){e.push({kind:146,text:";",start:i}),i++;continue}if(s===42){e.push({kind:147,text:"*",start:i}),i++;continue}if(s===43||s===45){if(i+1<r){let a=t.charCodeAt(i+1);if(h(a)){let o=i;for(i++;i<r&&h(t.charCodeAt(i));)i++;if(i<r&&t.charCodeAt(i)===46&&i+1<r&&h(t.charCodeAt(i+1))){for(i++;i<r&&h(t.charCodeAt(i));)i++;e.push({kind:154,text:t.substring(o,i),start:o});continue}e.push({kind:156,text:t.substring(o,i),start:o});continue}if(a===46&&i+2<r&&h(t.charCodeAt(i+2))){let o=i;for(i+=2;i<r&&h(t.charCodeAt(i));)i++;e.push({kind:154,text:t.substring(o,i),start:o});continue}}e.push({kind:s===43?148:149,text:t[i],start:i}),i++;continue}if(s===46){if(i+1<r&&h(t.charCodeAt(i+1))){let a=i;for(i++;i<r&&h(t.charCodeAt(i));)i++;e.push({kind:155,text:t.substring(a,i),start:a});continue}e.push({kind:143,text:".",start:i}),i++;continue}if(oe(s)){let a=i;for(i++;i<r;){let c=t.charCodeAt(i);if(ie(c)||c===46)i++;else break}let o=t.substring(a,i);if(o.includes(".."))throw new Error(`Invalid identifier with consecutive dots at position ${a}: "${o}"`);let l=o.toUpperCase();if(l==="ORDER"&&!o.includes(".")){let c=te(t,i,"BY");if(c!==-1){let u=t.substring(a,c);e.push({kind:21,text:u,start:a}),i=c;continue}}if(l==="GROUP"&&!o.includes(".")){let c=te(t,i,"BY");if(c!==-1){let u=t.substring(a,c);e.push({kind:10,text:u,start:a}),i=c;continue}}if(l==="DATA"&&!o.includes(".")){let c=te(t,i,"CATEGORY");if(c!==-1){let u=t.substring(a,c);e.push({kind:35,text:u,start:a}),i=c;continue}}if(o.length>=4){let c=o.substring(0,3);if(me(c)){let u=o.substring(3);if(He(u)){u.includes(".")?e.push({kind:152,text:o,start:a}):e.push({kind:153,text:o,start:a});continue}}}if(o.length===3&&me(o)){let c=i,u=i,E=!1;if(u<r&&t.charCodeAt(u)===45&&(E=!0,u++),E&&u<r&&h(t.charCodeAt(u))){for(;u<r&&h(t.charCodeAt(u));)u++;if(u<r&&t.charCodeAt(u)===46&&u+1<r&&h(t.charCodeAt(u+1))){for(u++;u<r&&h(t.charCodeAt(u));)u++;let d=t.substring(a,u);e.push({kind:152,text:d,start:a}),i=u;continue}if(u>=r||!ie(t.charCodeAt(u))&&t.charCodeAt(u)!==46){let d=t.substring(a,u);e.push({kind:153,text:d,start:a}),i=u;continue}i=c}}if(o.includes(".")){e.push({kind:160,text:o,start:a});continue}let p=Be.get(l);if(p!==void 0){e.push({kind:p,text:o,start:a});continue}e.push({kind:160,text:o,start:a});continue}throw new Error(`Unexpected character '${t[i]}' (code ${s}) at position ${i}`)}return e.push({kind:161,text:"",start:i}),e}function te(t,e,r){let i=t.length,s=e;if(s>=i||!H(t.charCodeAt(s)))return-1;for(;s<i&&H(t.charCodeAt(s));)s++;let a=r.length;if(s+a>i)return-1;for(let l=0;l<a;l++){let p=t.charCodeAt(s+l),c=r.charCodeAt(l);if((p>=97&&p<=122?p-32:p)!==c)return-1}let o=s+a;if(o<i){let l=t.charCodeAt(o);if(ie(l)||l===46)return-1}return o}function me(t){for(let e=0;e<t.length;e++)if(!oe(t.charCodeAt(e)))return!1;return!0}function He(t){if(t.length===0)return!1;let e=0;if(t.charCodeAt(e)===45&&e++,e>=t.length||!h(t.charCodeAt(e)))return!1;for(;e<t.length&&h(t.charCodeAt(e));)e++;if(e<t.length&&t.charCodeAt(e)===46){if(e++,e>=t.length||!h(t.charCodeAt(e)))return!1;for(;e<t.length&&h(t.charCodeAt(e));)e++}return e===t.length}var Qe=new Set([23,9,26,21,10,11,16,27,28,29,25,19,2,3,0,20,17,45,41,5,36,42,144,140,161]),ue=class t{tokens;pos=0;config;constructor(e,r){this.tokens=e,this.config=r}getPos(){return this.pos}peek(){return this.tokens[this.pos]}peekAt(e){let r=this.pos+e;return r>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[r]}advance(){let e=this.tokens[this.pos];return e.kind!==161&&this.pos++,e}expect(e){let r=this.peek();if(r.kind!==e)throw this.error(`Expected ${R[e]} but found ${R[r.kind]} ("${r.text}") at position ${r.start}`);return this.advance()}match(e){return this.peek().kind===e?(this.advance(),!0):!1}check(e){return this.peek().kind===e}isAtEnd(){return this.peek().kind===161}error(e){return this.config.logErrors&&console.log(e),new Error(e)}static CLAUSE_BOUNDARY_KINDS=new Set([26,21,10,11,16,37,27,28,29,25,161]);isAtClauseBoundary(){let e=this.peek().kind;return t.CLAUSE_BOUNDARY_KINDS.has(e)||e===140}synchronize(){for(;!this.isAtEnd();){if(this.isAtClauseBoundary())return;this.advance()}}consumeIdentifier(){let e=this.peek();if(L(e.kind))return this.advance();throw this.error(`Expected identifier but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}checkIdentifier(){return L(this.peek().kind)}isFunctionCall(){let e=this.peek(),r=this.peekAt(1);return(m(e.kind)||x(e.kind)||re(e.kind)||ne(e.kind)||U(e.kind))&&r.kind===139}canBeAlias(){let e=this.peek();return!(!L(e.kind)||Qe.has(e.kind)||e.kind===37&&this.peekAt(1).kind===157)}getLiteralType(e){let r=A(e);return r==="UNSIGNED_INTEGER"||r==="SIGNED_INTEGER"?"INTEGER":r==="UNSIGNED_DECIMAL"||r==="SIGNED_DECIMAL"?"DECIMAL":r==="CURRENCY_PREFIXED_DECIMAL"?"DECIMAL_WITH_CURRENCY_PREFIX":r==="CURRENCY_PREFIXED_INTEGER"?"INTEGER_WITH_CURRENCY_PREFIX":r==="DATETIME"?"DATETIME":r==="DATE"?"DATE":r==="NULL"?"NULL":r==="StringIdentifier"||r==="Identifier"?"STRING":r==="TRUE"||r==="FALSE"?"BOOLEAN":Q(e)?"DATE_LITERAL":V(e)?"DATE_N_LITERAL":"STRING"}parseSelectStatement(e=!1){let r=this.parseSelectClause(),i=this.parseFromClause(),s;e?(s={fields:r,relationshipName:i.sObject},i.sObjectPrefix&&(s.sObjectPrefix=i.sObjectPrefix)):s={fields:r,sObject:i.sObject},i.alias&&(s.sObjectAlias=i.alias),this.applySObjectAlias(s);let a=this.parseClauseStatements();return Object.assign(s,a),s}parseSelectStatementPartial(){let e,r;this.check(23)&&(e=this.parseSelectClause()),this.check(9)&&(r=this.parseFromClause());let i={};e&&(i.fields=e),r&&(i.sObject=r.sObject,r.alias&&(i.sObjectAlias=r.alias)),i.fields&&this.applySObjectAlias(i);let s=this.parseClauseStatements();return Object.assign(i,s),i}applySObjectAlias(e){if(!e.sObjectAlias||!Array.isArray(e.fields))return;let r=e.sObjectAlias;e.fields.forEach(i=>{i.relationships&&i.relationships[0]===r&&(i.relationships=i.relationships.slice(1),i.objectPrefix=r,i.relationships.length===0&&(delete i.relationships,i.type="Field"))})}parseSelectClause(){this.expect(23);let e=[];for(e.push(this.parseSelectField());this.match(144);)e.push(this.parseSelectField());return e}parseSelectField(){let e=this.peek(),r=this.peekAt(1);return e.kind===139&&r.kind===23?this.parseSelectClauseSubqueryIdentifier():e.kind===42?this.parseSelectClauseTypeOf():this.isFunctionCall()?this.parseSelectClauseFunctionIdentifier():this.parseSelectClauseIdentifier()}parseSelectClauseFunctionIdentifier(){let e=this.parseAnyFunction(!0);return this.canBeAlias()&&(e.alias=this.consumeIdentifier().text),e}parseSelectClauseSubqueryIdentifier(){this.expect(139);let e=this.parseSelectStatement(!0);return this.expect(140),{type:"FieldSubquery",subquery:e}}parseSelectClauseTypeOf(){this.expect(42);let e=this.consumeIdentifier().text,r=[];for(;this.check(45);){this.advance();let i=this.consumeIdentifier().text;this.expect(41);let s=[];for(s.push(this.consumeIdentifier().text);this.match(144);)s.push(this.consumeIdentifier().text);r.push({type:"WHEN",objectType:i,fieldList:s})}if(this.check(5)){this.advance();let i=[];for(i.push(this.consumeIdentifier().text);this.match(144);)i.push(this.consumeIdentifier().text);r.push({type:"ELSE",fieldList:i})}return this.expect(36),{type:"FieldTypeof",field:e,conditions:r}}parseSelectClauseIdentifier(){let r=this.consumeIdentifier().text,i;if(!r.includes("."))i={type:"Field",field:r};else{let s=r.split(".");i={type:"FieldRelationship",field:s[s.length-1],relationships:s.slice(0,s.length-1),rawValue:r}}return this.canBeAlias()&&(i.alias=this.consumeIdentifier().text),i}parseFromClause(){this.expect(9);let r=this.consumeIdentifier().text,i;if(r.includes(".")){let s=r.split(".");i={sObjectPrefix:s.slice(0,s.length-1),sObject:s[s.length-1]}}else i={sObject:r};return this.canBeAlias()&&(i.alias=this.consumeIdentifier().text),i}parseClauseStatements(){let e={},r=(i,s)=>{if(this.config.ignoreParseErrors)try{i(),this.isAtClauseBoundary()||(s&&s(),this.synchronize())}catch(a){this.config.logErrors&&console.log(a),s&&s(),this.synchronize()}else i()};for(this.check(25)&&r(()=>{e.usingScope=this.parseUsingScope()}),this.check(26)&&r(()=>{e.where=this.parseWhereClause()},()=>{delete e.where});this.check(27);)r(()=>{let i=this.parseWithClause();i.withSecurityEnforced&&(e.withSecurityEnforced=!0),i.withAccessLevel&&(e.withAccessLevel=i.withAccessLevel),i.withDataCategory&&(e.withDataCategory=i.withDataCategory)});return this.check(10)&&(r(()=>{e.groupBy=this.parseGroupByClause()}),this.check(11)&&r(()=>{e.having=this.parseHavingClause()})),this.check(21)&&r(()=>{e.orderBy=this.parseOrderByClause()}),this.check(16)&&r(()=>{this.advance(),e.limit=Number(this.expect(157).text)}),this.check(37)&&r(()=>{this.advance(),e.offset=Number(this.expect(157).text)}),this.check(28)&&r(()=>{this.advance();let i=this.peek();if(i.kind===43||i.kind===38||i.kind===29)e.for=A(this.advance().kind);else throw this.error(`Expected VIEW, REFERENCE, or UPDATE after FOR at position ${i.start}`)}),this.check(29)&&r(()=>{this.advance();let i=this.peek();if(i.kind===40||i.kind===44)e.update=A(this.advance().kind);else throw this.error(`Expected TRACKING or VIEWSTAT after UPDATE at position ${i.start}`)}),e}parseUsingScope(){this.expect(25),this.expect(39);let e=this.peek();if(De(e.kind))return this.advance().text;if(L(e.kind))return this.advance().text;throw this.error(`Expected scope enumeration value at position ${e.start}`)}parseWhereClause(){return this.expect(26),this.parseConditionExpressions("WHERE")}parseConditionExpressions(e){let r,i,s={left:0,right:0};for(;;){let a;if(r)if(this.check(0))a="AND",this.advance();else if(this.check(20))a="OR",this.advance();else break;let o={},l=o,p=null;for(;this.hasNegationPrefix();){let E=0;for(;this.check(139)&&this.isNegationAhead();)this.advance(),E++,s.left++;if(this.check(17)){this.advance();let d={left:E>0?{openParen:E}:null,operator:"NOT",right:{left:{}}};p?p.right=d:o=d,p=d,l=d.right}else break}l.left=this.parseExpression(e,s),r?a&&(i.operator=a,i.right=o):(r=o,i=o);let c=o;for(;c.right&&c.right.left!==void 0;){let E=c.right;if(E.right&&E.right.left!==void 0)c=E;else{c=E;break}}if(i=c,this.isAtEnd())break;let u=this.peek().kind;if(u!==0&&u!==20)break}if(s.left!==s.right)throw this.error(`Mismatched parentheses in WHERE/HAVING clause: ${s.left} open vs ${s.right} close`);return r}hasNegationPrefix(){let e=0;for(;this.peekAt(e).kind===139;)e++;return this.peekAt(e).kind===17}isNegationAhead(){let e=1;for(;this.peekAt(e).kind===139;)e++;return this.peekAt(e).kind===17}parseExpression(e,r){let i=0;for(;this.check(139)&&!this.isSubqueryStart()&&!this.isArrayExpressionStart();)this.advance(),i++,r&&r.left++;let s=e==="WHERE",a,o=!1;s&&this.peek().kind===76&&this.peekAt(1).kind===139?(a=this.parseFormulaFunction(),o=!0):x(this.peek().kind)&&this.peekAt(1).kind===139?(a=this.parseAggregateFunction(!1),o=!0):s&&re(this.peek().kind)&&this.peek().kind===68&&this.peekAt(1).kind===139?(a=this.parseLocationFunction(!1),o=!0):m(this.peek().kind)&&this.peekAt(1).kind===139?(a=this.parseDateFunction(!1),o=!0):U(this.peek().kind)&&this.peekAt(1).kind===139?(a=this.parseOtherFunction(!1),o=!0):a=this.consumeIdentifier().text;let l=this.parseOperator(),p=l.operator,c=l.isSet,u,E,d;if(c)if(this.check(139)&&this.peekAt(1).kind===23)this.expect(139),u=this.parseSelectStatement(!1),this.expect(140),E="SUBQUERY";else if(this.config.allowApexBindVariables&&this.check(145))u=this.parseApexBindVariable().value,E="APEX_BIND_VARIABLE";else{let y=this.parseArrayExpression();u=y.values,E=y.literalType,d=y.dateLiteralVariable}else{let y=this.parseAtomicValue();u=y.value,E=y.literalType,d=y.dateLiteralVariable}let g=0;for(;this.check(140)&&(!r||r.left>r.right);)this.advance(),g++,r&&r.right++;let T={};return o?T.fn=a:T.field=a,T.operator=p,E==="SUBQUERY"?T.valueQuery=u:T.value=u,T.literalType=E,d!==void 0&&(T.dateLiteralVariable=d),i>0&&(T.openParen=i),g>0&&(T.closeParen=g),T}isSubqueryStart(){return this.check(139)&&this.peekAt(1).kind===23}isArrayExpressionStart(){return!1}parseOperator(){let e=this.peek();if(ae(e.kind))return{operator:this.advance().text,isSet:!1};if(e.kind===15)return this.advance(),{operator:"LIKE",isSet:!1};if(e.kind===12)return this.advance(),{operator:"IN",isSet:!0};if(e.kind===17&&this.peekAt(1).kind===12)return this.advance(),this.advance(),{operator:"NOT IN",isSet:!0};if(e.kind===13)return this.advance(),{operator:"INCLUDES",isSet:!0};if(e.kind===6)return this.advance(),{operator:"EXCLUDES",isSet:!0};throw this.error(`Expected operator but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseAtomicValue(){let e=this.peek();if(this.config.allowApexBindVariables&&e.kind===145)return{value:this.parseApexBindVariable().value,literalType:"APEX_BIND_VARIABLE"};if(e.kind===158)return{value:this.advance().text,literalType:"STRING"};if(e.kind===159)return{value:this.advance().text,literalType:"STRING"};if(e.kind===157)return{value:this.advance().text,literalType:"INTEGER"};if(e.kind===156)return{value:this.advance().text,literalType:"INTEGER"};if(e.kind===155)return{value:this.advance().text,literalType:"DECIMAL"};if(e.kind===154)return{value:this.advance().text,literalType:"DECIMAL"};if(e.kind===152)return{value:this.advance().text,literalType:"DECIMAL_WITH_CURRENCY_PREFIX"};if(e.kind===153)return{value:this.advance().text,literalType:"INTEGER_WITH_CURRENCY_PREFIX"};if(e.kind===150)return{value:this.advance().text,literalType:"DATETIME"};if(e.kind===151)return{value:this.advance().text,literalType:"DATE"};if(e.kind===18)return this.advance(),{value:"NULL",literalType:"NULL"};if(e.kind===24||e.kind===7)return{value:A(this.advance().kind),literalType:"BOOLEAN"};if(Q(e.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(V(e.kind)){let r=this.advance();this.expect(145);let i=this.peek(),s;if(i.kind===157||i.kind===156)s=Number(this.advance().text);else throw this.error(`Expected integer after date N literal colon at position ${i.start}`);return{value:`${r.text}:${s}`,literalType:"DATE_N_LITERAL",dateLiteralVariable:s}}throw this.error(`Expected value but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseArrayExpression(){this.expect(139);let e=[];for(e.push(this.parseArrayItem());this.match(144);)e.push(this.parseArrayItem());this.expect(140);let r=e.map(p=>p.value),i=e.map(p=>p.type),s=e.map(p=>p.variable!==void 0?p.variable:null),a=s.some(p=>p!==null),o;new Set(i).size===1?o=this.getLiteralType(this.tokenKindFromTypeName(i[0])):o=i.map(p=>this.getLiteralType(this.tokenKindFromTypeName(p)));let l={values:r,literalType:o};return a&&(l.dateLiteralVariable=s),l}tokenKindFromTypeName(e){for(let r=0;r<=161;r++)if(A(r)===e)return r;return 160}parseArrayItem(){let e=this.peek();if(e.kind===158)return{value:this.advance().text,type:A(158)};if(e.kind===159)return{value:this.advance().text,type:A(159)};if(e.kind===152)return{value:this.advance().text,type:A(152)};if(e.kind===153)return{value:this.advance().text,type:A(153)};if(se(e.kind)){let r=this.advance();return{value:r.text,type:A(r.kind)}}if(e.kind===150)return{value:this.advance().text,type:A(150)};if(e.kind===151)return{value:this.advance().text,type:A(151)};if(e.kind===18)return this.advance(),{value:"NULL",type:"NULL"};if(e.kind===24)return{value:this.advance().text,type:"TRUE"};if(e.kind===7)return{value:this.advance().text,type:"FALSE"};if(Q(e.kind))return{value:this.advance().text,type:A(e.kind)};if(V(e.kind)){let r=this.advance();this.expect(145);let i=this.peek(),s;if(i.kind===157||i.kind===156)s=Number(this.advance().text);else throw this.error(`Expected integer after date N literal colon at position ${i.start}`);return{value:`${r.text}:${s}`,type:A(r.kind),variable:s}}throw this.error(`Expected array value but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseApexBindVariable(){this.expect(145);let e=[];for(this.check(32)?e.push(this.parseApexBindNewInstantiation()):this.checkIdentifier()&&(this.peekAt(1).kind===139?e.push(this.parseApexBindFunctionCall()):e.push(this.parseApexBindIdentifier()));this.check(143);)this.advance(),this.checkIdentifier()&&this.peekAt(1).kind===139?e.push(this.parseApexBindFunctionCall()):this.checkIdentifier()&&e.push(this.parseApexBindIdentifier());return{value:e.join(".")}}parseApexBindIdentifier(){let e=this.consumeIdentifier().text;return this.check(141)&&(e+=this.parseApexBindArrayAccessor()),e}parseApexBindNewInstantiation(){this.expect(32);let r=`new ${this.consumeIdentifier().text}`;if(this.check(135)){this.advance();let i=[];for(i.push(this.consumeIdentifier().text);this.match(144);)i.push(this.consumeIdentifier().text);this.expect(137),r+=`<${i.join(", ")}>`}return r+=this.parseApexBindFunctionParams(),this.check(141)&&(r+=this.parseApexBindArrayAccessor()),r}parseApexBindFunctionCall(){let r=this.consumeIdentifier().text+this.parseApexBindFunctionParams();return this.check(141)&&(r+=this.parseApexBindArrayAccessor()),r}parseApexBindFunctionParams(){this.expect(139);let e=[];if(!this.check(140))for(e.push(this.consumeIdentifier().text);this.match(144);)e.push(this.consumeIdentifier().text);return this.expect(140),`(${e.join(", ")})`}parseApexBindArrayAccessor(){this.expect(141);let e=this.peek(),r;if(e.kind===157)r=this.advance().text;else if(L(e.kind))r=this.advance().text;else throw this.error(`Expected integer or identifier in array accessor at position ${e.start}`);return this.expect(142),`[${r}]`}parseFormulaFunction(){let e=this.expect(76);this.expect(139);let r=this.expect(158);this.expect(140);let i=Fe(r.text.slice(1,-1));if(!i)throw this.error(`Invalid FORMULA expression at position ${r.start+1}. Expected two field references separated by + or -.`);let s=this.peek();if(!ae(s.kind))throw this.error(`Expected comparison operator after FORMULA but found ${R[s.kind]} ("${s.text}") at position ${s.start}`);let a=this.peekAt(1);if(a.kind===145)throw this.error(`Expected value after FORMULA comparison but found COLON (":") at position ${a.start}`);return{functionName:"FORMULA",parameters:[`'${B(i)}'`],rawValue:`${e.text}(${r.text})`,formula:i}}parseAnyFunction(e){let r=this.peek();if(m(r.kind))return this.parseDateFunction(e);if(x(r.kind))return this.parseAggregateFunction(e);if(r.kind===68)return this.parseLocationFunction(e);if(ne(r.kind))return this.parseFieldsFunction(e);if(U(r.kind))return this.parseOtherFunction(e);throw this.error(`Expected function name but found ${R[r.kind]} at position ${r.start}`)}parseDateFunction(e){let r=this.advance(),i=A(r.kind),s=this.parseFunctionExpression(!1,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=i,a.parameters=s,e&&(a.isAggregateFn=!0),a.rawValue=`${r.text}(${s.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseAggregateFunction(e){let r=this.advance(),i=A(r.kind),s=this.parseFunctionExpression(!0,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=i,a.parameters=s,e&&(a.isAggregateFn=!0),a.rawValue=`${r.text}(${s.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseFieldsFunction(e){this.advance(),this.expect(139);let r=this.peek(),i;if(xe(r.kind))i=this.advance().text;else if(L(r.kind))i=this.advance().text;else throw this.error(`Expected FIELDS function parameter at position ${r.start}`);this.expect(140);let s={};return e&&(s.type="FieldFunctionExpression"),s.functionName="FIELDS",s.parameters=[i],s.rawValue=`FIELDS(${i})`,s}parseOtherFunction(e){let r=this.advance(),i=A(r.kind),s=this.parseFunctionExpression(!1,e),a={};return e&&(a.type="FieldFunctionExpression"),a.functionName=i,a.parameters=s,a.rawValue=`${r.text}(${s.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseLocationFunction(e){this.advance(),this.expect(139);let r=this.consumeIdentifier().text;this.expect(144);let i;this.check(69)&&this.peekAt(1).kind===139?i=this.parseGeolocationFunction(e):i=this.consumeIdentifier().text,this.expect(144);let s=this.expect(159).text;this.expect(140);let a={};e&&(a.type="FieldFunctionExpression"),a.functionName="DISTANCE",a.parameters=[r,i,s],e&&(a.isAggregateFn=!0);let o=typeof i=="string"?i:i.rawValue;return a.rawValue=`DISTANCE(${r}, ${o}, ${s})`,a}parseGeolocationFunction(e){this.advance(),this.expect(139);let r=this.parseNumberValue();this.expect(144);let i=this.parseNumberValue();this.expect(140);let s={};return e&&(s.type="FieldFunctionExpression"),s.functionName="GEOLOCATION",s.parameters=[r,i],s.rawValue=`GEOLOCATION(${r}, ${i})`,s}parseNumberValue(){let e=this.peek();if(e.kind===157||e.kind===156||e.kind===155||e.kind===154)return this.advance().text;throw this.error(`Expected number but found ${R[e.kind]} ("${e.text}") at position ${e.start}`)}parseFunctionExpression(e,r=!0){this.expect(139);let i=[];if(!this.check(140))for(i.push(this.parseFunctionParam(e,r));this.match(144);)i.push(this.parseFunctionParam(e,r));return this.expect(140),i}parseFunctionParam(e,r){let i=this.peek(),s=this.peekAt(1);if(!e&&x(i.kind)&&s.kind===139)return this.parseAggregateFunction(r);if(U(i.kind)&&s.kind===139)return this.parseOtherFunction(r);if(i.kind===158)return this.advance().text;if(se(i.kind))return this.advance().text;if(L(i.kind))return this.advance().text;throw this.error(`Expected function parameter but found ${R[i.kind]} ("${i.text}") at position ${i.start}`)}parseGroupByClause(){this.expect(10);let e=[];for(e.push(this.parseGroupByItem());this.match(144);)e.push(this.parseGroupByItem());return e}parseGroupByItem(){let e=this.peek();return e.kind===4&&this.peekAt(1).kind===139?{fn:this.parseCubeOrRollupFunction("CUBE")}:e.kind===22&&this.peekAt(1).kind===139?{fn:this.parseCubeOrRollupFunction("ROLLUP")}:m(e.kind)&&this.peekAt(1).kind===139?{fn:this.parseDateFunction(!1)}:{field:this.consumeIdentifier().text}}parseCubeOrRollupFunction(e){this.advance();let r=this.parseFunctionExpression(!1);return{functionName:e,parameters:r,rawValue:`${e}(${r.join(", ")})`}}parseHavingClause(){return this.expect(11),this.parseConditionExpressions("HAVING")}parseOrderByClause(){this.expect(21);let e=[];for(e.push(this.parseOrderByItem());this.match(144);)e.push(this.parseOrderByItem());return e}parseOrderByItem(){let e=this.peek(),r=this.peekAt(1),i;if(e.kind===75&&r.kind===139){let s=this.advance(),a=this.parseFunctionExpression(!1);i={fn:{functionName:A(s.kind),parameters:a,rawValue:`${s.text}(${a.join(", ")})`}}}else x(e.kind)&&r.kind===139?i={fn:this.parseAggregateFunction(!1)}:m(e.kind)&&r.kind===139?i={fn:this.parseDateFunction(!1)}:e.kind===68&&r.kind===139?i={fn:this.parseLocationFunction(!1)}:i={field:this.consumeIdentifier().text};if(this.check(2)?i.order=A(this.advance().kind):this.check(3)&&(i.order=A(this.advance().kind)),this.check(19))if(this.advance(),this.check(8))i.nulls=A(this.advance().kind);else if(this.check(14))i.nulls=A(this.advance().kind);else throw this.error(`Expected FIRST or LAST after NULLS at position ${this.peek().start}`);return i}parseWithClause(){this.expect(27);let e=this.peek();if(e.kind===46)return this.advance(),{withSecurityEnforced:!0};if(e.kind===48)return this.advance(),{withAccessLevel:"USER_MODE"};if(e.kind===47)return this.advance(),{withAccessLevel:"SYSTEM_MODE"};if(e.kind===35)return{withDataCategory:this.parseWithDataCategory()};throw this.error(`Expected SECURITY_ENFORCED, USER_MODE, SYSTEM_MODE, or DATA CATEGORY after WITH at position ${e.start}`)}parseWithDataCategory(){this.expect(35);let e=[];for(e.push(this.parseDataCategoryCondition());this.check(0);)this.advance(),e.push(this.parseDataCategoryCondition());return{conditions:e}}parseDataCategoryCondition(){let e=this.consumeIdentifier().text,r=this.peek(),i;if(r.kind===33||r.kind===30||r.kind===34||r.kind===31)i=this.advance().text;else throw this.error(`Expected data category selector (AT, ABOVE, BELOW, ABOVE_OR_BELOW) at position ${r.start}`);let s=this.match(139),a=[];for(a.push(this.consumeIdentifier().text);this.match(144);)a.push(this.consumeIdentifier().text);return s&&this.expect(140),{groupName:e,selector:i,parameters:a}}};function D(t,e){let r=e||{},i=be(t),s=new ue(i,r),a;if(r.allowPartialQuery?a=s.parseSelectStatementPartial():a=s.parseSelectStatement(!1),!s.isAtEnd()&&!r.ignoreParseErrors){let o=i[s.getPos()];throw new Error(`Unexpected token "${o.text}" at position ${o.start}. Expected end of query.`)}return a}function le(t,e){try{return D(t,e),!0}catch{return!1}}function X(t){if(ge(t))return`FORMULA('${B(t.formula)}')`;let e;return t.rawValue?e=t.rawValue:e=`${t.functionName}(${(t.parameters||[]).map(r=>S(r)?r:X(r)).join(", ")})`,t.alias&&(e+=` ${t.alias}`),e}function O(t){let e=t.objectPrefix?`${t.objectPrefix}.`:"";switch(t.type){case"Field":return`${e}${t.field}${t.alias?` ${t.alias}`:""}`;case"FieldFunctionExpression":return`${t.functionName}(${Ve(t)})${t.alias?` ${t.alias}`:""}`;case"FieldRelationship":return`${e}${t.relationships.join(".")}.${t.field}${Re(t)?` ${t.alias}`:""}`;case"FieldTypeof":return w(t).join(" ");default:return""}}function Ve(t){return t.parameters?t.parameters.map(e=>S(e)?e:O(e)).join(", "):""}function w(t){return[`TYPEOF ${t.field}`,...t.conditions.map(Xe),"END"]}function Xe(t){let e=t.fieldList.join(", ");return t.objectType?`${t.type} ${t.objectType} THEN ${e}`:`${t.type} ${e}`}function je(t){return Te(t)?t.relationshipName?`${[...t.sObjectPrefix||[],t.relationshipName].join(".")}${F(t.sObjectAlias,""," ")}`:"":t.sObject?`${t.sObject}${F(t.sObjectAlias,""," ")}`:""}function G(t){return`${Ce(t)?X(t.fn):t.field} ${t.operator}`}function j(t){return Ne(ye(t.value,t.literalType,t.operator))}function pe(t){return Se(t)?t.field:X(t.fn)}function ce(t){let e=_e(t)?`${F(t.field," ")}`:`${X(t.fn)} `;return e+=`${F(t.order," ")}${F(t.nulls,"","NULLS ")}`,e.trim()}function Ee(t){return t.conditions.map(e=>{let r=e.parameters.length>1?`(${e.parameters.join(", ")})`:`${e.parameters.join(", ")}`;return`${e.groupName} ${e.selector} ${r}`}).join(" AND ")}function qe(t){return!!t.groupBy&&(!Array.isArray(t.groupBy)||t.groupBy.length>0)}function Ke(t){return!!t.orderBy&&(!Array.isArray(t.orderBy)||t.orderBy.length>0)}function v(t){return Array.isArray(t)?t:[t]}function*q(t){t.fields&&(yield{kind:"select",fields:t.fields});let e=je(t);e&&(yield{kind:"value",keyword:"FROM",value:e}),t.usingScope&&(yield{kind:"value",keyword:"USING SCOPE",value:t.usingScope}),t.where&&(yield{kind:"conditions",keyword:"WHERE",clause:t.where}),t.withDataCategory&&(yield{kind:"value",keyword:"WITH DATA CATEGORY",value:Ee(t.withDataCategory)}),t.withSecurityEnforced&&(yield{kind:"bare",keyword:"WITH SECURITY_ENFORCED"}),t.withAccessLevel&&(yield{kind:"bare",keyword:`WITH ${t.withAccessLevel}`}),qe(t)&&(yield{kind:"list",keyword:"GROUP BY",items:v(t.groupBy).map(pe)},t.having&&(yield{kind:"conditions",keyword:"HAVING",clause:t.having})),Ke(t)&&(yield{kind:"list",keyword:"ORDER BY",items:v(t.orderBy).map(ce)}),I(t.limit)&&(yield{kind:"value",keyword:"LIMIT",value:`${t.limit}`}),I(t.offset)&&(yield{kind:"value",keyword:"OFFSET",value:`${t.offset}`}),t.for&&(yield{kind:"value",keyword:"FOR",value:t.for}),t.update&&(yield{kind:"value",keyword:"UPDATE",value:t.update})}function ze(t={}){let e=t.newLineAfterKeywords??!1;return{numIndent:I(t.numIndent)&&t.numIndent>=1?Math.floor(t.numIndent):1,indentString:S(t.indentString)&&/^[ \t]*$/.test(t.indentString)?t.indentString:" ",fieldMaxLineLength:I(t.fieldMaxLineLength)?t.fieldMaxLineLength:60,fieldSubqueryParensOnOwnLine:e||(t.fieldSubqueryParensOnOwnLine??!0),newLineAfterKeywords:e}}var M=class{lines=[];push(e,r=""){this.lines.push({indent:e,text:r})}append(e,r){if(this.lines.length===0){this.push(e,r);return}this.lines[this.lines.length-1].text+=r}concat(e){this.lines.push(...e)}},K=class{options;constructor(e={}){this.options=ze(e)}formatQuery(e){return this.render(this.query(e,0))}formatWhereOrHavingClause(e,r=0){return this.renderFragment(this.conditions(e,r))}formatSubqueryField(e){let r=new M;return this.selectSubquery(r,e,0,""),this.render(r.lines)}formatList(e){return this.renderFragment(this.listRows(e).map(r=>({indent:1,text:r})))}render(e){return e.map(r=>`${this.indent(r.indent)}${r.text}`).join(`
7
+ `)}renderFragment(e){return e.map((r,i)=>i===0?r.text:`${this.indent(r.indent)}${r.text}`).join(`
8
+ `)}indent(e){return this.options.indentString.repeat(this.options.numIndent*Math.max(e,0))}query(e,r){let i=new M;for(let s of q(e))switch(s.kind){case"select":this.selectClause(i,s.fields,r);break;case"value":this.clause(i,r,s.keyword,s.value);break;case"bare":i.push(r,s.keyword);break;case"list":this.listClause(i,r,s.keyword,s.items);break;case"conditions":this.keywordThen(i,r,s.keyword,this.conditions(s.clause,r));break}return i.lines}clause(e,r,i,s){this.options.newLineAfterKeywords?(e.push(r,i),e.push(r+1,s)):e.push(r,`${i} ${s}`)}keywordThen(e,r,i,s){let[a,...o]=s;this.options.newLineAfterKeywords||!a?(e.push(r,i),e.concat(s)):(e.push(r,`${i} ${a.text}`),e.concat(o))}selectClause(e,r,i){let{newLineAfterKeywords:s}=this.options;e.push(i,"SELECT");let a=this.wrapper(!1),o=[],l=!1,p=!s,c=u=>{if(o.length>0){let E=`${o.join(", ")}${u?",":""}`;p?e.append(i,` ${E}`):e.push(i+1,E),o=[]}p=!1};r.forEach((u,E)=>{let d=E===r.length-1,g=d?"":",";if(u.type==="FieldSubquery")c(!0),a.reset(),this.selectSubquery(e,u.subquery,i+1,g),l=!0;else if(u.type==="FieldTypeof")c(!0),a.reset(),this.typeOfField(e,u,i+1,g),l=!0;else{let T=O(u);(a.startsNewRow(T,d)||l)&&(c(!0),l=!1),o.push(T)}}),c(!1)}wrapper(e){let{fieldMaxLineLength:r}=this.options,i=0;return{startsNewRow(s,a){let o=s.length+(a?0:2);return e||i+o>r?(i=o,!0):(i+=o,!1)},reset(){i=0}}}selectSubquery(e,r,i,s){if(this.options.fieldSubqueryParensOnOwnLine)e.push(i,"("),e.concat(this.query(r,i+1)),e.push(i,`)${s}`);else{let a=this.query(r,i);if(a.length===0){e.push(i,`()${s}`);return}a[0]={...a[0],text:`(${a[0].text}`};let o=a.length-1;a[o]={...a[o],text:`${a[o].text})${s}`},e.concat(a)}}typeOfField(e,r,i,s){if(!this.options.newLineAfterKeywords){e.push(i,`${w(r).join(" ")}${s}`);return}e.push(i,`TYPEOF ${r.field}`),r.conditions.forEach(a=>{e.push(i+1,a.type),a.objectType&&(e.push(i+2,a.objectType),e.push(i+1,"THEN")),e.push(i+2,a.fieldList.join(", "))}),e.push(i,`END${s}`)}listClause(e,r,i,s){this.keywordThen(e,r,i,this.listRows(s).map(a=>({indent:r+1,text:a})))}listRows(e){let r=this.wrapper(this.options.newLineAfterKeywords),i=[],s=[];return e.forEach((a,o)=>{r.startsNewRow(a,o===e.length-1)&&s.length>0&&(i.push(`${s.join(", ")},`),s=[]),s.push(a)}),i.push(s.join(", ")),i}conditions(e,r){let i=new M,s=[],a=()=>r+s.length+1,o=e;for(;o;){let l=o.left,p=b(o)?o.right:void 0;if(k(l)){let c=this.isSelfContainedNegation(p);for(let u=0;u<l.openParen;u++){let E=c&&u===l.openParen-1;i.append(a(),"("),s.push(E),E||i.push(a())}}else if(l){for(let c=0;c<(l.openParen||0);c++)i.append(a(),"("),s.push(!1),i.push(a());this.condition(i,l,a());for(let c=0;c<(l.closeParen||0);c++){let u=s.pop()??!1,E=a();u?i.append(E,")"):i.push(E,")")}}b(o)&&(o.operator==="NOT"?i.append(a(),"NOT "):i.push(a(),`${o.operator} `)),o=p}return i.lines}isSelfContainedNegation(e){let r=e?.left;return!!r&&!k(r)&&!r.openParen&&(r.closeParen||0)>0}condition(e,r,i){if(W(r))if(e.append(i,`${G(r)} (`),this.options.fieldSubqueryParensOnOwnLine)e.concat(this.query(r.valueQuery,i+1)),e.push(i,")");else{let s=this.query(r.valueQuery,i);s.length>0&&(e.append(i,s[0].text),e.concat(s.slice(1))),e.append(i,")")}else e.append(i,`${G(r)} ${j(r)}`)}};function P(t){let e=[];for(let r of q(t))switch(r.kind){case"select":{let i=r.fields.map(s=>s.type==="FieldSubquery"?`(${P(s.subquery)})`:O(s));e.push(`SELECT ${i.join(", ")}`);break}case"value":e.push(`${r.keyword} ${r.value}`);break;case"bare":e.push(r.keyword);break;case"list":e.push(`${r.keyword} ${r.items.join(", ")}`);break;case"conditions":e.push(`${r.keyword} ${he(r.clause)}`);break}return e.join(" ").trim()}function he(t){let e="",r=t;for(;r;){let i=r.left;k(i)?e+=$(i.openParen,"("):i&&(e+=$(i.openParen??0,"("),e+=`${G(i)} `,e+=W(i)?`(${P(i.valueQuery)})`:j(i),e+=$(i.closeParen??0,")")),b(r)?(e+=r.operator==="NOT"?"NOT ":` ${r.operator} `,r=r.right):r=void 0}return e}function ke(t,e,r){return Ae(D(t,r),{format:!0,formatOptions:e})}function Ae(t,e={}){if(!t)return"";e=e||{},e.format=!!e.format,e.logging&&(console.time("composer"),console.log("Composing Query:",t),console.log("Format output:",e.format));let r=new fe(t,e).query;return e.logging&&console.timeEnd("composer"),r}var fe=class{constructor(e,r={}){this.soql=e;r={autoCompose:!0,...r};let{logging:i,format:s}=r;this.logging=!!i,this.format=!!s,this.query="",this.formatter=new K(r.formatOptions),r.autoCompose&&this.start()}soql;logging=!1;format=!1;query;formatter;start(){this.query=this.parseQuery(this.soql)}log(e){this.logging&&console.log("Current SOQL:",e)}parseQuery(e){let r=this.format?this.formatter.formatQuery(e):P(e);return this.log(r),r}parseFields(e){return e.map(r=>r.type==="FieldSubquery"?{text:this.format?this.formatter.formatSubqueryField(r.subquery):`(${P(r.subquery)})`}:{text:O(r),typeOfClause:r.type==="FieldTypeof"?this.parseTypeOfField(r):void 0})}parseTypeOfField(e){return w(e)}parseWhereOrHavingClause(e,r=0){return this.format?this.formatter.formatWhereOrHavingClause(e,r):he(e)}parseGroupByClause(e){let r=v(e).map(pe);return this.format?this.formatter.formatList(r):r.join(", ")}parseOrderBy(e){let r=v(e).map(ce);return this.format?this.formatter.formatList(r):r.join(", ")}parseWithDataCategory(e){return Ee(e)}};function Je(t){let e=t.slice(2),r=e[0]??"",i=e[1]??"",s={};for(let a=2;a<e.length;a++){let o=e[a];if(o.startsWith("--")){let l=o.slice(2),p=e[a+1];p&&!p.startsWith("-")?(s[l]=p,a++):s[l]=!0}else if(o.startsWith("-")&&o.length===2){let l=o.slice(1),p=e[a+1];p&&!p.startsWith("-")?(s[l]=p,a++):s[l]=!0}}return{command:r,query:i,flags:s}}function _(t,e,r){return t[e]===!0||t[r]===!0}function de(t,e,r){let i=t[e]??t[r];return typeof i=="string"?i:void 0}function Ue(t){let e={},r=de(t,"indent","i"),i=de(t,"indent-string","t"),s=de(t,"line-length","m");return r&&(e.numIndent=Number(r)),i!==void 0&&(e.indentString=i),s&&(e.fieldMaxLineLength=Number(s)),_(t,"subquery-parens-new-line","s")&&(e.fieldSubqueryParensOnOwnLine=!0),_(t,"keywords-new-line","k")&&(e.newLineAfterKeywords=!0),e}function ve(){console.log(`Usage: soql-parser-js <command> <query> [options]
29
9
 
30
10
  Commands:
31
11
  parse <soql> Parse a SOQL query and output JSON AST
@@ -40,7 +20,8 @@ Parse options:
40
20
 
41
21
  Compose options:
42
22
  -f, --format Format output
43
- -i, --indent <chars> Number of tab characters to indent (default: 1)
23
+ -i, --indent <count> Number of times the indent string is repeated per level (default: 1)
24
+ -t, --indent-string <string> String used for one unit of indentation (default: tab), e.g. --indent-string " "
44
25
  -m, --line-length <chars> Max number of characters per line (default: 60)
45
26
  -s, --subquery-parens-new-line Subquery parens on own line
46
27
  -k, --keywords-new-line New line after keywords
@@ -49,7 +30,8 @@ Compose options:
49
30
  Format options:
50
31
  -a, --allow-apex Allow apex bind variables
51
32
  -p, --allow-partial Allow partial queries
52
- -i, --indent <chars> Number of tab characters to indent (default: 1)
33
+ -i, --indent <count> Number of times the indent string is repeated per level (default: 1)
34
+ -t, --indent-string <string> String used for one unit of indentation (default: tab), e.g. --indent-string " "
53
35
  -m, --line-length <chars> Max number of characters per line (default: 60)
54
36
  -s, --subquery-parens-new-line Subquery parens on own line
55
37
  -k, --keywords-new-line New line after keywords
@@ -58,4 +40,4 @@ Format options:
58
40
  Valid options:
59
41
  -a, --allow-apex Allow apex bind variables
60
42
  -p, --allow-partial Allow partial queries
61
- -j, --json Output as JSON`)}var{command:Y,query:U,flags:A}=Ie(process.argv);(!Y||!U)&&(pe(),process.exit(Y?1:0));switch(Y){case"parse":{console.log(JSON.stringify(x(U,{allowApexBindVariables:N(A,"allow-apex","a"),allowPartialQuery:N(A,"allow-partial","p"),ignoreParseErrors:N(A,"ignore-errors","i")})));break}case"compose":{let s={},e=v(A,"indent","i"),i=v(A,"line-length","m");e&&(s.numIndent=Number(e)),i&&(s.fieldMaxLineLength=Number(i)),N(A,"subquery-parens-new-line","s")&&(s.fieldSubqueryParensOnOwnLine=!0),N(A,"keywords-new-line","k")&&(s.newLineAfterKeywords=!0);let t=N(A,"format","f"),n=re(JSON.parse(U),{format:t,formatOptions:s});N(A,"json","j")?console.log(JSON.stringify({query:n})):console.log(n);break}case"format":{let s={},e={};N(A,"allow-apex","a")&&(s.allowApexBindVariables=!0),N(A,"allow-partial","p")&&(s.allowPartialQuery=!0);let i=v(A,"indent","i"),t=v(A,"line-length","m");i&&(e.numIndent=Number(i)),t&&(e.fieldMaxLineLength=Number(t)),N(A,"subquery-parens-new-line","s")&&(e.fieldSubqueryParensOnOwnLine=!0),N(A,"keywords-new-line","k")&&(e.newLineAfterKeywords=!0);let n=he(U,e,s);N(A,"json","j")?console.log(JSON.stringify({query:n})):console.log(n);break}case"valid":{let s={};N(A,"allow-apex","a")&&(s.allowApexBindVariables=!0),N(A,"allow-partial","p")&&(s.allowPartialQuery=!0);let e=X(U,s);N(A,"json","j")?console.log(JSON.stringify({isValid:e})):e?console.log("true"):(console.error("false"),process.exit(1));break}default:console.error(`Unknown command: ${Y}`),pe(),process.exit(1)}
43
+ -j, --json Output as JSON`)}var{command:z,query:Y,flags:C}=Je(process.argv);(!z||!Y)&&(ve(),process.exit(z?1:0));switch(z){case"parse":{console.log(JSON.stringify(D(Y,{allowApexBindVariables:_(C,"allow-apex","a"),allowPartialQuery:_(C,"allow-partial","p"),ignoreParseErrors:_(C,"ignore-errors","i")})));break}case"compose":{let t=Ue(C),e=_(C,"format","f"),r=Ae(JSON.parse(Y),{format:e,formatOptions:t});_(C,"json","j")?console.log(JSON.stringify({query:r})):console.log(r);break}case"format":{let t={};_(C,"allow-apex","a")&&(t.allowApexBindVariables=!0),_(C,"allow-partial","p")&&(t.allowPartialQuery=!0);let e=ke(Y,Ue(C),t);_(C,"json","j")?console.log(JSON.stringify({query:e})):console.log(e);break}case"valid":{let t={};_(C,"allow-apex","a")&&(t.allowApexBindVariables=!0),_(C,"allow-partial","p")&&(t.allowPartialQuery=!0);let e=le(Y,t);_(C,"json","j")?console.log(JSON.stringify({isValid:e})):e?console.log("true"):(console.error("false"),process.exit(1));break}default:console.error(`Unknown command: ${z}`),ve(),process.exit(1)}