@jetstreamapp/soql-parser-js 8.0.0 → 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.
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * @jetstreamapp/soql-parser-js v8.0.0
2
+ * @jetstreamapp/soql-parser-js v8.1.0
3
3
  * https://github.com/jetstreamapp/soql-parser-js
4
4
  * @license MIT
5
5
  */
6
- 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.ALL=76]="ALL",n[n.CUSTOM=77]="CUSTOM",n[n.STANDARD=78]="STANDARD",n[n.YESTERDAY=79]="YESTERDAY",n[n.TODAY=80]="TODAY",n[n.TOMORROW=81]="TOMORROW",n[n.LAST_WEEK=82]="LAST_WEEK",n[n.THIS_WEEK=83]="THIS_WEEK",n[n.NEXT_WEEK=84]="NEXT_WEEK",n[n.LAST_MONTH=85]="LAST_MONTH",n[n.THIS_MONTH=86]="THIS_MONTH",n[n.NEXT_MONTH=87]="NEXT_MONTH",n[n.LAST_90_DAYS=88]="LAST_90_DAYS",n[n.NEXT_90_DAYS=89]="NEXT_90_DAYS",n[n.THIS_QUARTER=90]="THIS_QUARTER",n[n.LAST_QUARTER=91]="LAST_QUARTER",n[n.NEXT_QUARTER=92]="NEXT_QUARTER",n[n.THIS_YEAR=93]="THIS_YEAR",n[n.LAST_YEAR=94]="LAST_YEAR",n[n.NEXT_YEAR=95]="NEXT_YEAR",n[n.THIS_FISCAL_QUARTER=96]="THIS_FISCAL_QUARTER",n[n.LAST_FISCAL_QUARTER=97]="LAST_FISCAL_QUARTER",n[n.NEXT_FISCAL_QUARTER=98]="NEXT_FISCAL_QUARTER",n[n.THIS_FISCAL_YEAR=99]="THIS_FISCAL_YEAR",n[n.LAST_FISCAL_YEAR=100]="LAST_FISCAL_YEAR",n[n.NEXT_FISCAL_YEAR=101]="NEXT_FISCAL_YEAR",n[n.NEXT_N_DAYS=102]="NEXT_N_DAYS",n[n.LAST_N_DAYS=103]="LAST_N_DAYS",n[n.N_DAYS_AGO=104]="N_DAYS_AGO",n[n.NEXT_N_WEEKS=105]="NEXT_N_WEEKS",n[n.LAST_N_WEEKS=106]="LAST_N_WEEKS",n[n.N_WEEKS_AGO=107]="N_WEEKS_AGO",n[n.NEXT_N_MONTHS=108]="NEXT_N_MONTHS",n[n.LAST_N_MONTHS=109]="LAST_N_MONTHS",n[n.N_MONTHS_AGO=110]="N_MONTHS_AGO",n[n.NEXT_N_QUARTERS=111]="NEXT_N_QUARTERS",n[n.LAST_N_QUARTERS=112]="LAST_N_QUARTERS",n[n.N_QUARTERS_AGO=113]="N_QUARTERS_AGO",n[n.NEXT_N_YEARS=114]="NEXT_N_YEARS",n[n.LAST_N_YEARS=115]="LAST_N_YEARS",n[n.N_YEARS_AGO=116]="N_YEARS_AGO",n[n.NEXT_N_FISCAL_QUARTERS=117]="NEXT_N_FISCAL_QUARTERS",n[n.LAST_N_FISCAL_QUARTERS=118]="LAST_N_FISCAL_QUARTERS",n[n.N_FISCAL_QUARTERS_AGO=119]="N_FISCAL_QUARTERS_AGO",n[n.NEXT_N_FISCAL_YEARS=120]="NEXT_N_FISCAL_YEARS",n[n.LAST_N_FISCAL_YEARS=121]="LAST_N_FISCAL_YEARS",n[n.N_FISCAL_YEARS_AGO=122]="N_FISCAL_YEARS_AGO",n[n.DELEGATED=123]="DELEGATED",n[n.EVERYTHING=124]="EVERYTHING",n[n.MINE_AND_MY_GROUPS=125]="MINE_AND_MY_GROUPS",n[n.MINE=126]="MINE",n[n.MY_TERRITORY=127]="MY_TERRITORY",n[n.MY_TEAM_TERRITORY=128]="MY_TEAM_TERRITORY",n[n.TEAM=129]="TEAM",n[n.ALL_PRIVATE=130]="ALL_PRIVATE",n[n.MRU=131]="MRU",n[n.EQUAL=132]="EQUAL",n[n.NOT_EQUAL=133]="NOT_EQUAL",n[n.LESS_THAN=134]="LESS_THAN",n[n.LESS_THAN_OR_EQUAL=135]="LESS_THAN_OR_EQUAL",n[n.GREATER_THAN=136]="GREATER_THAN",n[n.GREATER_THAN_OR_EQUAL=137]="GREATER_THAN_OR_EQUAL",n[n.L_PAREN=138]="L_PAREN",n[n.R_PAREN=139]="R_PAREN",n[n.L_SQUARE_BRACKET=140]="L_SQUARE_BRACKET",n[n.R_SQUARE_BRACKET=141]="R_SQUARE_BRACKET",n[n.DOT=142]="DOT",n[n.COMMA=143]="COMMA",n[n.COLON=144]="COLON",n[n.SEMICOLON=145]="SEMICOLON",n[n.ASTERISK=146]="ASTERISK",n[n.PLUS=147]="PLUS",n[n.MINUS=148]="MINUS",n[n.DATETIME=149]="DATETIME",n[n.DATE_TOKEN=150]="DATE_TOKEN",n[n.CURRENCY_PREFIXED_DECIMAL=151]="CURRENCY_PREFIXED_DECIMAL",n[n.CURRENCY_PREFIXED_INTEGER=152]="CURRENCY_PREFIXED_INTEGER",n[n.SIGNED_DECIMAL=153]="SIGNED_DECIMAL",n[n.UNSIGNED_DECIMAL=154]="UNSIGNED_DECIMAL",n[n.SIGNED_INTEGER=155]="SIGNED_INTEGER",n[n.UNSIGNED_INTEGER=156]="UNSIGNED_INTEGER",n[n.STRING_LITERAL=157]="STRING_LITERAL",n[n.GEOLOCATION_UNIT=158]="GEOLOCATION_UNIT",n[n.IDENTIFIER=159]="IDENTIFIER",n[n.EOF=160]="EOF",n))(R||{});function g(e){return e>=49&&e<=61}function O(e){return e>=62&&e<=67}function J(e){return e>=68&&e<=69}function ee(e){return e===70}function D(e){return e>=71&&e<=75}function Ae(e){return e>=76&&e<=78}function w(e){return e>=79&&e<=101}function Y(e){return e>=102&&e<=122}function Ne(e){return e>=123&&e<=131}function y(e){return e===159||e>=30&&e<=48||e>=49&&e<=61||e>=62&&e<=67||e>=68&&e<=69||e===70||e>=71&&e<=75||e>=76&&e<=78||e>=79&&e<=101||e>=102&&e<=122||e>=123&&e<=131||e===158||e===152}function te(e){return e===153||e===154||e===155||e===156}function Ce(e){return e>=132&&e<=137}var xe=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]]),f=[];(function(){for(let t of Object.keys(R)){let r=R[t];typeof r=="number"&&(f[r]=t)}f[72]="toLabel",f[73]="convertTimezone",f[74]="convertCurrency",f[157]="StringIdentifier",f[150]="DATE",f[32]="new",f[125]="MineAndMyGroups",f[127]="MyTerritory",f[128]="MyTeamTerritory",f[130]="AllPrivate",f[123]="Delegated",f[124]="Everything",f[126]="Mine",f[129]="Team",f[131]="Mru",f[159]="Identifier",f[132]="EQUAL",f[156]="UNSIGNED_INTEGER",f[155]="SIGNED_INTEGER",f[154]="UNSIGNED_DECIMAL",f[153]="SIGNED_DECIMAL",f[151]="CURRENCY_PREFIXED_DECIMAL",f[152]="CURRENCY_PREFIXED_INTEGER"})();function N(e){return f[e]||R[e]}function ie(e){return e>=65&&e<=90||e>=97&&e<=122}function d(e){return e>=48&&e<=57}function Z(e){return ie(e)||d(e)||e===95}function P(e){return e===32||e===9||e===10||e===13||e===12}function Re(e){let t=[],r=e.length,i=0;for(;i<r;){let s=e.charCodeAt(i);if(P(s)){for(i++;i<r&&P(e.charCodeAt(i));)i++;continue}if(s===47){let a=i+1<r?e.charCodeAt(i+1):0;if(a===47){for(i+=2;i<r;){let o=e.charCodeAt(i);if(o===10||o===13)break;i++}continue}if(a===42){let o=i;i+=2;let E=!1;for(;i<r;){if(e.charCodeAt(i)===42&&i+1<r&&e.charCodeAt(i+1)===47){i+=2,E=!0;break}i++}if(!E)throw new Error(`Unterminated comment at position ${o}`);continue}}if(s===39){let a=i;for(i++;i<r;){let c=e.charCodeAt(i);if(c===92){i+=2;continue}if(c===39){i++;break}i++}let o=e.substring(a,i),u=o.substring(1,o.length-1).toUpperCase();u==="MI"||u==="KM"?t.push({kind:158,text:o,start:a}):t.push({kind:157,text:o,start:a});continue}if(d(s)){if(i+9<r&&e.charCodeAt(i+4)===45&&e.charCodeAt(i+7)===45){let o=!0;for(let E of[0,1,2,3,5,6,8,9])if(!d(e.charCodeAt(i+E))){o=!1;break}if(o)if(i+10<r&&(e.charCodeAt(i+10)===84||e.charCodeAt(i+10)===116)){let E=i;for(i+=11;i<r;){let u=e.charCodeAt(i);if(d(u)||u===58)i++;else break}if(i<r&&e.charCodeAt(i)===46)for(i++;i<r&&d(e.charCodeAt(i));)i++;if(i<r){let u=e.charCodeAt(i);if(u===90||u===122)i++;else if(u===46){for(i++;i<r&&d(e.charCodeAt(i));)i++;i<r&&(e.charCodeAt(i)===90||e.charCodeAt(i)===122)&&i++}else if(u===43||u===45)for(i++;i<r;){let c=e.charCodeAt(i);if(d(c)||c===58)i++;else break}}t.push({kind:149,text:e.substring(E,i),start:E});continue}else{let E=i;i+=10,t.push({kind:150,text:e.substring(E,i),start:E});continue}}let a=i;for(;i<r&&d(e.charCodeAt(i));)i++;if(i<r&&e.charCodeAt(i)===46&&i+1<r&&d(e.charCodeAt(i+1))){for(i++;i<r&&d(e.charCodeAt(i));)i++;t.push({kind:154,text:e.substring(a,i),start:a});continue}t.push({kind:156,text:e.substring(a,i),start:a});continue}if(s===33){if(i+1<r&&e.charCodeAt(i+1)===61){t.push({kind:133,text:"!=",start:i}),i+=2;continue}throw new Error(`Unexpected character '!' at position ${i}`)}if(s===60){if(i+1<r){let a=e.charCodeAt(i+1);if(a===61){t.push({kind:135,text:"<=",start:i}),i+=2;continue}if(a===62){t.push({kind:133,text:"<>",start:i}),i+=2;continue}}t.push({kind:134,text:"<",start:i}),i++;continue}if(s===62){if(i+1<r&&e.charCodeAt(i+1)===61){t.push({kind:137,text:">=",start:i}),i+=2;continue}t.push({kind:136,text:">",start:i}),i++;continue}if(s===61){t.push({kind:132,text:"=",start:i}),i++;continue}if(s===40){t.push({kind:138,text:"(",start:i}),i++;continue}if(s===41){t.push({kind:139,text:")",start:i}),i++;continue}if(s===91){t.push({kind:140,text:"[",start:i}),i++;continue}if(s===93){t.push({kind:141,text:"]",start:i}),i++;continue}if(s===44){t.push({kind:143,text:",",start:i}),i++;continue}if(s===58){t.push({kind:144,text:":",start:i}),i++;continue}if(s===59){t.push({kind:145,text:";",start:i}),i++;continue}if(s===42){t.push({kind:146,text:"*",start:i}),i++;continue}if(s===43||s===45){if(i+1<r){let a=e.charCodeAt(i+1);if(d(a)){let o=i;for(i++;i<r&&d(e.charCodeAt(i));)i++;if(i<r&&e.charCodeAt(i)===46&&i+1<r&&d(e.charCodeAt(i+1))){for(i++;i<r&&d(e.charCodeAt(i));)i++;t.push({kind:153,text:e.substring(o,i),start:o});continue}t.push({kind:155,text:e.substring(o,i),start:o});continue}if(a===46&&i+2<r&&d(e.charCodeAt(i+2))){let o=i;for(i+=2;i<r&&d(e.charCodeAt(i));)i++;t.push({kind:153,text:e.substring(o,i),start:o});continue}}t.push({kind:s===43?147:148,text:e[i],start:i}),i++;continue}if(s===46){if(i+1<r&&d(e.charCodeAt(i+1))){let a=i;for(i++;i<r&&d(e.charCodeAt(i));)i++;t.push({kind:154,text:e.substring(a,i),start:a});continue}t.push({kind:142,text:".",start:i}),i++;continue}if(ie(s)){let a=i;for(i++;i<r;){let c=e.charCodeAt(i);if(Z(c)||c===46)i++;else break}let o=e.substring(a,i);if(o.includes(".."))throw new Error(`Invalid identifier with consecutive dots at position ${a}: "${o}"`);let E=o.toUpperCase();if(E==="ORDER"&&!o.includes(".")){let c=z(e,i,"BY");if(c!==-1){let l=e.substring(a,c);t.push({kind:21,text:l,start:a}),i=c;continue}}if(E==="GROUP"&&!o.includes(".")){let c=z(e,i,"BY");if(c!==-1){let l=e.substring(a,c);t.push({kind:10,text:l,start:a}),i=c;continue}}if(E==="DATA"&&!o.includes(".")){let c=z(e,i,"CATEGORY");if(c!==-1){let l=e.substring(a,c);t.push({kind:35,text:l,start:a}),i=c;continue}}if(o.length>=4){let c=o.substring(0,3);if(fe(c)){let l=o.substring(3);if(De(l)){l.includes(".")?t.push({kind:151,text:o,start:a}):t.push({kind:152,text:o,start:a});continue}}}if(o.length===3&&fe(o)){let c=i,l=i,p=!1;if(l<r&&e.charCodeAt(l)===45&&(p=!0,l++),p&&l<r&&d(e.charCodeAt(l))){for(;l<r&&d(e.charCodeAt(l));)l++;if(l<r&&e.charCodeAt(l)===46&&l+1<r&&d(e.charCodeAt(l+1))){for(l++;l<r&&d(e.charCodeAt(l));)l++;let h=e.substring(a,l);t.push({kind:151,text:h,start:a}),i=l;continue}if(l>=r||!Z(e.charCodeAt(l))&&e.charCodeAt(l)!==46){let h=e.substring(a,l);t.push({kind:152,text:h,start:a}),i=l;continue}i=c}}if(o.includes(".")){t.push({kind:159,text:o,start:a});continue}let u=xe.get(E);if(u!==void 0){t.push({kind:u,text:o,start:a});continue}t.push({kind:159,text:o,start:a});continue}throw new Error(`Unexpected character '${e[i]}' (code ${s}) at position ${i}`)}return t.push({kind:160,text:"",start:i}),t}function z(e,t,r){let i=e.length,s=t;if(s>=i||!P(e.charCodeAt(s)))return-1;for(;s<i&&P(e.charCodeAt(s));)s++;let a=r.length;if(s+a>i)return-1;for(let E=0;E<a;E++){let u=e.charCodeAt(s+E),c=r.charCodeAt(E);if((u>=97&&u<=122?u-32:u)!==c)return-1}let o=s+a;if(o<i){let E=e.charCodeAt(o);if(Z(E)||E===46)return-1}return o}function fe(e){for(let t=0;t<e.length;t++)if(!ie(e.charCodeAt(t)))return!1;return!0}function De(e){if(e.length===0)return!1;let t=0;if(e.charCodeAt(t)===45&&t++,t>=e.length||!d(e.charCodeAt(t)))return!1;for(;t<e.length&&d(e.charCodeAt(t));)t++;if(t<e.length&&e.charCodeAt(t)===46){if(t++,t>=e.length||!d(e.charCodeAt(t)))return!1;for(;t<e.length&&d(e.charCodeAt(t));)t++}return t===e.length}var be=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]),W=class W{constructor(t,r){this.pos=0;this.tokens=t,this.config=r}getPos(){return this.pos}peek(){return this.tokens[this.pos]}peekAt(t){let r=this.pos+t;return r>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[r]}advance(){let t=this.tokens[this.pos];return t.kind!==160&&this.pos++,t}expect(t){let r=this.peek();if(r.kind!==t)throw this.error(`Expected ${R[t]} but found ${R[r.kind]} ("${r.text}") at position ${r.start}`);return this.advance()}match(t){return this.peek().kind===t?(this.advance(),!0):!1}check(t){return this.peek().kind===t}isAtEnd(){return this.peek().kind===160}error(t){return this.config.logErrors&&console.log(t),new Error(t)}isAtClauseBoundary(){let t=this.peek().kind;return W.CLAUSE_BOUNDARY_KINDS.has(t)||t===139}synchronize(){for(;!this.isAtEnd();){if(this.isAtClauseBoundary())return;this.advance()}}consumeIdentifier(){let t=this.peek();if(y(t.kind))return this.advance();throw this.error(`Expected identifier but found ${R[t.kind]} ("${t.text}") at position ${t.start}`)}checkIdentifier(){return y(this.peek().kind)}isFunctionCall(){let t=this.peek(),r=this.peekAt(1);return(g(t.kind)||O(t.kind)||J(t.kind)||ee(t.kind)||D(t.kind))&&r.kind===138}canBeAlias(){let t=this.peek();return!(!y(t.kind)||be.has(t.kind)||t.kind===37&&this.peekAt(1).kind===156)}getLiteralType(t){let r=N(t);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":w(t)?"DATE_LITERAL":Y(t)?"DATE_N_LITERAL":"STRING"}parseSelectStatement(t=!1){let r=this.parseSelectClause(),i=this.parseFromClause(),s;t?(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 t,r;this.check(23)&&(t=this.parseSelectClause()),this.check(9)&&(r=this.parseFromClause());let i={};t&&(i.fields=t),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(t){if(!t.sObjectAlias||!Array.isArray(t.fields))return;let r=t.sObjectAlias;t.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 t=[];for(t.push(this.parseSelectField());this.match(143);)t.push(this.parseSelectField());return t}parseSelectField(){let t=this.peek(),r=this.peekAt(1);return t.kind===138&&r.kind===23?this.parseSelectClauseSubqueryIdentifier():t.kind===42?this.parseSelectClauseTypeOf():this.isFunctionCall()?this.parseSelectClauseFunctionIdentifier():this.parseSelectClauseIdentifier()}parseSelectClauseFunctionIdentifier(){let t=this.parseAnyFunction(!0);return this.canBeAlias()&&(t.alias=this.consumeIdentifier().text),t}parseSelectClauseSubqueryIdentifier(){this.expect(138);let t=this.parseSelectStatement(!0);return this.expect(139),{type:"FieldSubquery",subquery:t}}parseSelectClauseTypeOf(){this.expect(42);let t=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(143);)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(143);)i.push(this.consumeIdentifier().text);r.push({type:"ELSE",fieldList:i})}return this.expect(36),{type:"FieldTypeof",field:t,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 t={},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(()=>{t.usingScope=this.parseUsingScope()}),this.check(26)&&r(()=>{t.where=this.parseWhereClause()},()=>{delete t.where});this.check(27);)r(()=>{let i=this.parseWithClause();i.withSecurityEnforced&&(t.withSecurityEnforced=!0),i.withAccessLevel&&(t.withAccessLevel=i.withAccessLevel),i.withDataCategory&&(t.withDataCategory=i.withDataCategory)});return this.check(10)&&(r(()=>{t.groupBy=this.parseGroupByClause()}),this.check(11)&&r(()=>{t.having=this.parseHavingClause()})),this.check(21)&&r(()=>{t.orderBy=this.parseOrderByClause()}),this.check(16)&&r(()=>{this.advance(),t.limit=Number(this.expect(156).text)}),this.check(37)&&r(()=>{this.advance(),t.offset=Number(this.expect(156).text)}),this.check(28)&&r(()=>{this.advance();let i=this.peek();if(i.kind===43||i.kind===38||i.kind===29)t.for=N(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)t.update=N(this.advance().kind);else throw this.error(`Expected TRACKING or VIEWSTAT after UPDATE at position ${i.start}`)}),t}parseUsingScope(){this.expect(25),this.expect(39);let t=this.peek();if(Ne(t.kind))return this.advance().text;if(y(t.kind))return this.advance().text;throw this.error(`Expected scope enumeration value at position ${t.start}`)}parseWhereClause(){return this.expect(26),this.parseConditionExpressions(!0,!0)}parseConditionExpressions(t,r){let i,s,a={left:0,right:0};for(;;){let o;if(i)if(this.check(0))o="AND",this.advance();else if(this.check(20))o="OR",this.advance();else break;let E={},u=E,c=null;for(;this.hasNegationPrefix();){let h=0;for(;this.check(138)&&this.isNegationAhead();)this.advance(),h++,a.left++;if(this.check(17)){this.advance();let _={left:h>0?{openParen:h}:null,operator:"NOT",right:{left:{}}};c?c.right=_:E=_,c=_,u=_.right}else break}u.left=this.parseExpression(t,r,a),i?o&&(s.operator=o,s.right=E):(i=E,s=E);let l=E;for(;l.right&&l.right.left!==void 0;){let h=l.right;if(h.right&&h.right.left!==void 0)l=h;else{l=h;break}}if(s=l,this.isAtEnd())break;let p=this.peek().kind;if(p!==0&&p!==20)break}if(a.left!==a.right)throw this.error(`Mismatched parentheses in WHERE/HAVING clause: ${a.left} open vs ${a.right} close`);return i}hasNegationPrefix(){let t=0;for(;this.peekAt(t).kind===138;)t++;return this.peekAt(t).kind===17}isNegationAhead(){let t=1;for(;this.peekAt(t).kind===138;)t++;return this.peekAt(t).kind===17}parseExpression(t,r,i){let s=0;for(;this.check(138)&&!this.isSubqueryStart()&&!this.isArrayExpressionStart();)this.advance(),s++,i&&i.left++;let a,o=!1;t&&O(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseAggregateFunction(!1),o=!0):r&&J(this.peek().kind)&&this.peek().kind===68&&this.peekAt(1).kind===138?(a=this.parseLocationFunction(!1),o=!0):g(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseDateFunction(!1),o=!0):D(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseOtherFunction(!1),o=!0):a=this.consumeIdentifier().text;let E=this.parseOperator(),u=E.operator,c=E.isSet,l,p,h;if(c)if(this.check(138)&&this.peekAt(1).kind===23)this.expect(138),l=this.parseSelectStatement(!1),this.expect(139),p="SUBQUERY";else if(this.config.allowApexBindVariables&&this.check(144))l=this.parseApexBindVariable().value,p="APEX_BIND_VARIABLE";else{let S=this.parseArrayExpression();l=S.values,p=S.literalType,h=S.dateLiteralVariable}else{let S=this.parseAtomicValue();l=S.value,p=S.literalType,h=S.dateLiteralVariable}let _=0;for(;this.check(139)&&(!i||i.left>i.right);)this.advance(),_++,i&&i.right++;let T={};return o?T.fn=a:T.field=a,T.operator=u,p==="SUBQUERY"?T.valueQuery=l:T.value=l,T.literalType=p,h!==void 0&&(T.dateLiteralVariable=h),s>0&&(T.openParen=s),_>0&&(T.closeParen=_),T}isSubqueryStart(){return this.check(138)&&this.peekAt(1).kind===23}isArrayExpressionStart(){return!1}parseOperator(){let t=this.peek();if(Ce(t.kind))return{operator:this.advance().text,isSet:!1};if(t.kind===15)return this.advance(),{operator:"LIKE",isSet:!1};if(t.kind===12)return this.advance(),{operator:"IN",isSet:!0};if(t.kind===17&&this.peekAt(1).kind===12)return this.advance(),this.advance(),{operator:"NOT IN",isSet:!0};if(t.kind===13)return this.advance(),{operator:"INCLUDES",isSet:!0};if(t.kind===6)return this.advance(),{operator:"EXCLUDES",isSet:!0};throw this.error(`Expected operator but found ${R[t.kind]} ("${t.text}") at position ${t.start}`)}parseAtomicValue(){let t=this.peek();if(this.config.allowApexBindVariables&&t.kind===144)return{value:this.parseApexBindVariable().value,literalType:"APEX_BIND_VARIABLE"};if(t.kind===157)return{value:this.advance().text,literalType:"STRING"};if(t.kind===158)return{value:this.advance().text,literalType:"STRING"};if(t.kind===156)return{value:this.advance().text,literalType:"INTEGER"};if(t.kind===155)return{value:this.advance().text,literalType:"INTEGER"};if(t.kind===154)return{value:this.advance().text,literalType:"DECIMAL"};if(t.kind===153)return{value:this.advance().text,literalType:"DECIMAL"};if(t.kind===151)return{value:this.advance().text,literalType:"DECIMAL_WITH_CURRENCY_PREFIX"};if(t.kind===152)return{value:this.advance().text,literalType:"INTEGER_WITH_CURRENCY_PREFIX"};if(t.kind===149)return{value:this.advance().text,literalType:"DATETIME"};if(t.kind===150)return{value:this.advance().text,literalType:"DATE"};if(t.kind===18)return this.advance(),{value:"NULL",literalType:"NULL"};if(t.kind===24||t.kind===7)return{value:N(this.advance().kind),literalType:"BOOLEAN"};if(w(t.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(Y(t.kind)){let r=this.advance();this.expect(144);let i=this.peek(),s;if(i.kind===156||i.kind===155)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[t.kind]} ("${t.text}") at position ${t.start}`)}parseArrayExpression(){this.expect(138);let t=[];for(t.push(this.parseArrayItem());this.match(143);)t.push(this.parseArrayItem());this.expect(139);let r=t.map(u=>u.value),i=t.map(u=>u.type),s=t.map(u=>u.variable!==void 0?u.variable:null),a=s.some(u=>u!==null),o;new Set(i).size===1?o=this.getLiteralType(this.tokenKindFromTypeName(i[0])):o=i.map(u=>this.getLiteralType(this.tokenKindFromTypeName(u)));let E={values:r,literalType:o};return a&&(E.dateLiteralVariable=s),E}tokenKindFromTypeName(t){for(let r=0;r<=160;r++)if(N(r)===t)return r;return 159}parseArrayItem(){let t=this.peek();if(t.kind===157)return{value:this.advance().text,type:N(157)};if(t.kind===158)return{value:this.advance().text,type:N(158)};if(t.kind===151)return{value:this.advance().text,type:N(151)};if(t.kind===152)return{value:this.advance().text,type:N(152)};if(te(t.kind)){let r=this.advance();return{value:r.text,type:N(r.kind)}}if(t.kind===149)return{value:this.advance().text,type:N(149)};if(t.kind===150)return{value:this.advance().text,type:N(150)};if(t.kind===18)return this.advance(),{value:"NULL",type:"NULL"};if(t.kind===24)return{value:this.advance().text,type:"TRUE"};if(t.kind===7)return{value:this.advance().text,type:"FALSE"};if(w(t.kind))return{value:this.advance().text,type:N(t.kind)};if(Y(t.kind)){let r=this.advance();this.expect(144);let i=this.peek(),s;if(i.kind===156||i.kind===155)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:N(r.kind),variable:s}}throw this.error(`Expected array value but found ${R[t.kind]} ("${t.text}") at position ${t.start}`)}parseApexBindVariable(){this.expect(144);let t=[];for(this.check(32)?t.push(this.parseApexBindNewInstantiation()):this.checkIdentifier()&&(this.peekAt(1).kind===138?t.push(this.parseApexBindFunctionCall()):t.push(this.parseApexBindIdentifier()));this.check(142);)this.advance(),this.checkIdentifier()&&this.peekAt(1).kind===138?t.push(this.parseApexBindFunctionCall()):this.checkIdentifier()&&t.push(this.parseApexBindIdentifier());return{value:t.join(".")}}parseApexBindIdentifier(){let t=this.consumeIdentifier().text;return this.check(140)&&(t+=this.parseApexBindArrayAccessor()),t}parseApexBindNewInstantiation(){this.expect(32);let r=`new ${this.consumeIdentifier().text}`;if(this.check(134)){this.advance();let i=[];for(i.push(this.consumeIdentifier().text);this.match(143);)i.push(this.consumeIdentifier().text);this.expect(136),r+=`<${i.join(", ")}>`}return r+=this.parseApexBindFunctionParams(),this.check(140)&&(r+=this.parseApexBindArrayAccessor()),r}parseApexBindFunctionCall(){let r=this.consumeIdentifier().text+this.parseApexBindFunctionParams();return this.check(140)&&(r+=this.parseApexBindArrayAccessor()),r}parseApexBindFunctionParams(){this.expect(138);let t=[];if(!this.check(139))for(t.push(this.consumeIdentifier().text);this.match(143);)t.push(this.consumeIdentifier().text);return this.expect(139),`(${t.join(", ")})`}parseApexBindArrayAccessor(){this.expect(140);let t=this.peek(),r;if(t.kind===156)r=this.advance().text;else if(y(t.kind))r=this.advance().text;else throw this.error(`Expected integer or identifier in array accessor at position ${t.start}`);return this.expect(141),`[${r}]`}parseAnyFunction(t){let r=this.peek();if(g(r.kind))return this.parseDateFunction(t);if(O(r.kind))return this.parseAggregateFunction(t);if(r.kind===68)return this.parseLocationFunction(t);if(ee(r.kind))return this.parseFieldsFunction(t);if(D(r.kind))return this.parseOtherFunction(t);throw this.error(`Expected function name but found ${R[r.kind]} at position ${r.start}`)}parseDateFunction(t){let r=this.advance(),i=N(r.kind),s=this.parseFunctionExpression(!1,t),a={};return t&&(a.type="FieldFunctionExpression"),a.functionName=i,a.parameters=s,t&&(a.isAggregateFn=!0),a.rawValue=`${r.text}(${s.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseAggregateFunction(t){let r=this.advance(),i=N(r.kind),s=this.parseFunctionExpression(!0,t),a={};return t&&(a.type="FieldFunctionExpression"),a.functionName=i,a.parameters=s,t&&(a.isAggregateFn=!0),a.rawValue=`${r.text}(${s.map(o=>typeof o=="string"?o:o.rawValue).join(", ")})`,a}parseFieldsFunction(t){this.advance(),this.expect(138);let r=this.peek(),i;if(Ae(r.kind))i=this.advance().text;else if(y(r.kind))i=this.advance().text;else throw this.error(`Expected FIELDS function parameter at position ${r.start}`);this.expect(139);let s={};return t&&(s.type="FieldFunctionExpression"),s.functionName="FIELDS",s.parameters=[i],s.rawValue=`FIELDS(${i})`,s}parseOtherFunction(t){let r=this.advance(),i=N(r.kind),s=this.parseFunctionExpression(!1,t),a={};return t&&(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(t){this.advance(),this.expect(138);let r=this.consumeIdentifier().text;this.expect(143);let i;this.check(69)&&this.peekAt(1).kind===138?i=this.parseGeolocationFunction(t):i=this.consumeIdentifier().text,this.expect(143);let s=this.expect(158).text;this.expect(139);let a={};t&&(a.type="FieldFunctionExpression"),a.functionName="DISTANCE",a.parameters=[r,i,s],t&&(a.isAggregateFn=!0);let o=typeof i=="string"?i:i.rawValue;return a.rawValue=`DISTANCE(${r}, ${o}, ${s})`,a}parseGeolocationFunction(t){this.advance(),this.expect(138);let r=this.parseNumberValue();this.expect(143);let i=this.parseNumberValue();this.expect(139);let s={};return t&&(s.type="FieldFunctionExpression"),s.functionName="GEOLOCATION",s.parameters=[r,i],s.rawValue=`GEOLOCATION(${r}, ${i})`,s}parseNumberValue(){let t=this.peek();if(t.kind===156||t.kind===155||t.kind===154||t.kind===153)return this.advance().text;throw this.error(`Expected number but found ${R[t.kind]} ("${t.text}") at position ${t.start}`)}parseFunctionExpression(t,r=!0){this.expect(138);let i=[];if(!this.check(139))for(i.push(this.parseFunctionParam(t,r));this.match(143);)i.push(this.parseFunctionParam(t,r));return this.expect(139),i}parseFunctionParam(t,r){let i=this.peek(),s=this.peekAt(1);if(!t&&O(i.kind)&&s.kind===138)return this.parseAggregateFunction(r);if(D(i.kind)&&s.kind===138)return this.parseOtherFunction(r);if(i.kind===157)return this.advance().text;if(te(i.kind))return this.advance().text;if(y(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 t=[];for(t.push(this.parseGroupByItem());this.match(143);)t.push(this.parseGroupByItem());return t}parseGroupByItem(){let t=this.peek();return t.kind===4&&this.peekAt(1).kind===138?{fn:this.parseCubeOrRollupFunction("CUBE")}:t.kind===22&&this.peekAt(1).kind===138?{fn:this.parseCubeOrRollupFunction("ROLLUP")}:g(t.kind)&&this.peekAt(1).kind===138?{fn:this.parseDateFunction(!1)}:{field:this.consumeIdentifier().text}}parseCubeOrRollupFunction(t){let r=this.advance(),i=this.parseFunctionExpression(!1);return{functionName:t,parameters:i,rawValue:`${t}(${i.join(", ")})`}}parseHavingClause(){return this.expect(11),this.parseConditionExpressions(!0,!1)}parseOrderByClause(){this.expect(21);let t=[];for(t.push(this.parseOrderByItem());this.match(143);)t.push(this.parseOrderByItem());return t}parseOrderByItem(){let t=this.peek(),r=this.peekAt(1),i;if(t.kind===75&&r.kind===138){let s=this.advance(),a=this.parseFunctionExpression(!1);i={fn:{functionName:N(s.kind),parameters:a,rawValue:`${s.text}(${a.join(", ")})`}}}else O(t.kind)&&r.kind===138?i={fn:this.parseAggregateFunction(!1)}:g(t.kind)&&r.kind===138?i={fn:this.parseDateFunction(!1)}:t.kind===68&&r.kind===138?i={fn:this.parseLocationFunction(!1)}:i={field:this.consumeIdentifier().text};if(this.check(2)?i.order=N(this.advance().kind):this.check(3)&&(i.order=N(this.advance().kind)),this.check(19))if(this.advance(),this.check(8))i.nulls=N(this.advance().kind);else if(this.check(14))i.nulls=N(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 t=this.peek();if(t.kind===46)return this.advance(),{withSecurityEnforced:!0};if(t.kind===48)return this.advance(),{withAccessLevel:"USER_MODE"};if(t.kind===47)return this.advance(),{withAccessLevel:"SYSTEM_MODE"};if(t.kind===35)return{withDataCategory:this.parseWithDataCategory()};throw this.error(`Expected SECURITY_ENFORCED, USER_MODE, SYSTEM_MODE, or DATA CATEGORY after WITH at position ${t.start}`)}parseWithDataCategory(){this.expect(35);let t=[];for(t.push(this.parseDataCategoryCondition());this.check(0);)this.advance(),t.push(this.parseDataCategoryCondition());return{conditions:t}}parseDataCategoryCondition(){let t=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(138),a=[];for(a.push(this.consumeIdentifier().text);this.match(143);)a.push(this.consumeIdentifier().text);return s&&this.expect(139),{groupName:t,selector:i,parameters:a}}};W.CLAUSE_BOUNDARY_KINDS=new Set([26,21,10,11,16,37,27,28,29,25,160]);var re=W;function B(e,t){let r=t||{},i=Re(e),s=new re(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 ke(e,t){try{return B(e,t),!0}catch{return!1}}function Te(e){return e===32||e===9||e===10||e===13||e===12}function ne(e,t){let r=[],i=e.length,s=0;for(;s<i;){let a=e.charCodeAt(s);if(a===39){for(s++;s<i;){let o=e.charCodeAt(s);if(o===92){s+=2;continue}if(o===39){s++;break}s++}continue}if(a===47){let o=s+1<i?e.charCodeAt(s+1):0;if(o===47){let E=s;for(s+=2;s<i;){let u=e.charCodeAt(s);if(u===10||u===13)break;s++}if(r.push({type:"line",text:e.substring(E,s),start:E,end:s}),t)return r;continue}if(o===42){let E=s;for(s+=2;s<i;){if(e.charCodeAt(s)===42&&s+1<i&&e.charCodeAt(s+1)===47){s+=2;break}s++}if(r.push({type:"block",text:e.substring(E,s),start:E,end:s}),t)return r;continue}}s++}return r}function ve(e){return ne(e,!1)}function Ue(e){return ne(e,!0).length>0}function Ge(e){let t=ne(e,!1);if(t.length===0)return e;let r="",i=0;for(let s of t){r+=e.substring(i,s.start);let a=r.length>0?r.charCodeAt(r.length-1):0,o=s.end<e.length?e.charCodeAt(s.end):0;a!==0&&!Te(a)&&o!==0&&!Te(o)&&(r+=" "),i=s.end}return r+=e.substring(i),r}function A(e){return typeof e=="string"}function Me(e){return e?e.every(t=>A(t)):!1}function I(e){return Number.isFinite(e)}function C(e){return e==null}function F(e,t,r){return C(e)?"":`${r||""}${e}${t||""}`}function _e(e,t=!1){return Array.isArray(e)?e.length>0?`(${e.join(", ")})`:t?"()":"":t?`(${e||""})`:e||""}function $(e,t,r=""){return I(e)&&e>0?new Array(e).fill(t).join(r):""}function ae(e){return!e.parameters||e.parameters.length===0?[]:Me(e.parameters)?e.parameters:A(e.parameters[0])?[e.parameters[0]]:ae(e.parameters[0])}function Se(e){if(!e.parameters||e.parameters.length===0)return!1;let t=e.parameters[0];return A(t)?!1:!!t.isAggregateFn}function H(e){return e&&!C(e.alias)}function ye(e){return A(e.field)&&!Array.isArray(e.relationships)&&!Array.isArray(e.conditions)}function Ie(e){return!C(e.functionName||e.fn)}function Le(e){return A(e.field)&&Array.isArray(e.relationships)}function ge(e){return!C(e.subquery)}function Oe(e){return A(e.field)&&Array.isArray(e.conditions)}function Q(e){return A(e.relationshipName)}function Fe(e){return!!e&&!!e.type&&e.type==="FieldSubquery"}function Pe(e){return!!e&&!!e.operator&&!!e.right}function we(e){return!!e&&!!e.operator&&!!e.right}function m(e){return!!e&&!!e.operator&&!!e.right}function Ye(e){return e&&A(e.field)&&A(e.operator)&&!C(e.value)}function We(e){return e&&A(e.field)&&A(e.operator)&&!C(e.value)&&(e.literalType==="DATE_LITERAL"||Array.isArray(e.literalType)&&e.literalType[0]==="DATE_LITERAL")}function Be(e){return e&&A(e.field)&&A(e.operator)&&!C(e.value)&&!C(e.dateLiteralVariable)}function oe(e){return e&&!C(e.fn)&&A(e.operator)&&!C(e.value)}function x(e){return e&&I(e.openParen)&&C(e.operator)&&C(e.field)&&C(e.fn)&&C(e.closeParen)}function b(e){return e&&A(e.field)&&A(e.operator)&&!C(e.valueQuery)&&C(e.value)}function ue(e){return e&&!C(e.field)}function $e(e){return e&&!C(e.fn)}function V(e){return e&&!C(e.field)}function He(e){return e&&!C(e.fn)}function Qe(e){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(e)}function me(e,t,r){if(C(t))return e;if(r&&t!=="APEX_BIND_VARIABLE"&&Qe(r)&&!Array.isArray(e)&&(e=[e],t=Array.isArray(t)?t:[t]),Array.isArray(t)&&Array.isArray(e))return e.map((i,s)=>Ve(i,t?.[s]));switch(Array.isArray(t)&&(t=t[0]),t){case"STRING":return Array.isArray(e)?e.filter(Boolean).map(i=>se(i)):se(e);case"APEX_BIND_VARIABLE":return`:${e}`;default:return e}}function Ve(e,t){switch(t){case"STRING":return se(e);case"NULL":return"null";default:return e}}function se(e){if(A(e)&&e.startsWith("'")&&e.endsWith("'")&&e.length>=2)return e;let t=String(e??"");return`'${qe(t)}'`}var je=/[nNrRtTbBfF"'\\_%]/,Xe=/^[0-9a-fA-F]{4}$/;function qe(e){let t="";for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){let s=e[r+1];s!==void 0&&je.test(s)?(t+=i+s,r++):s==="u"&&Xe.test(e.substr(r+2,4))?(t+=e.substr(r,6),r+=5):t+="\\\\"}else i==="'"?t+="\\'":t+=i}return t}function ct(e){return Ke(e)}function Ke(e){if(typeof e=="string")return{type:"Field",field:e};if(Ie(e)){let t=[];return e.parameters&&(t=Array.isArray(e.parameters)?e.parameters:[e.parameters]),{type:"FieldFunctionExpression",functionName:e.functionName||e.fn,parameters:t,alias:e.alias}}else{if(Le(e))return{type:"FieldRelationship",field:e.field,relationships:e.relationships,objectPrefix:e.objectPrefix};if(ge(e))return{type:"FieldSubquery",subquery:e.subquery};if(Oe(e))return{type:"FieldTypeof",field:e.field,conditions:e.conditions};if(ye(e))return{type:"Field",field:e.field,objectPrefix:e.objectPrefix};throw new TypeError("The input object provided did not match any valid field types")}}function Et(e,t){if(!e)return[];e=Fe(e)?e.subquery:e;let r=e.fields;if(!r)return[];let i={};e.groupBy&&(i=(Array.isArray(e.groupBy)?e.groupBy:[e.groupBy]).reduce((u,c)=>(V(c)&&(u[c.field.toLocaleLowerCase()]=c.field),u),{}));let s=-1,a=(Q(e)?e.relationshipName:e.sObject||"").toLowerCase(),o=(e.sObjectAlias||"").toLowerCase();return r.flatMap(u=>{switch(u.type){case"Field":return u.alias||u.field;case"FieldFunctionExpression":{let c=ae(u);if(c=c.map(l=>{if(l.includes(".")){let p=l.split("."),h=p[0].toLowerCase();return(h===o||h===a)&&(p=p.slice(1)),p.join(".")}return l}),u.alias&&(u.isAggregateFn||t))return u.alias;if(u.alias){let l=c[0];return l.includes(".")?(c=l.split(".").slice(0,-1),c.push(u.alias),c.join(".")):u.alias}return u.isAggregateFn||Se(u)||t?(s++,`expr${s}`):c.length>0?c.join("."):u.functionName}case"FieldRelationship":{let c=u.relationships[0].toLowerCase();return H(u)?u.alias:u.rawValue&&i[u.rawValue.toLocaleLowerCase()]?u.field:c===o||c===a?u.relationships.concat([u.field]).slice(1).join("."):u.relationships.concat([u.field]).join(".")}case"FieldSubquery":return u.subquery.relationshipName;case"FieldTypeof":{let c=new Set,l=[];return u.conditions.forEach(p=>{p.fieldList.forEach(h=>{c.has(h)||(c.add(h),l.push(`${u.field}.${h}`))})}),l}default:break}}).filter(u=>A(u))}function j(e){let t;return e.rawValue?t=e.rawValue:t=`${e.functionName}(${(e.parameters||[]).map(r=>A(r)?r:j(r)).join(", ")})`,e.alias&&(t+=` ${e.alias}`),t}function L(e){let t=e.objectPrefix?`${e.objectPrefix}.`:"";switch(e.type){case"Field":return`${t}${e.field}${e.alias?` ${e.alias}`:""}`;case"FieldFunctionExpression":return`${e.functionName}(${ze(e)})${e.alias?` ${e.alias}`:""}`;case"FieldRelationship":return`${t}${e.relationships.join(".")}.${e.field}${H(e)?` ${e.alias}`:""}`;case"FieldTypeof":return v(e).join(" ");default:return""}}function ze(e){return e.parameters?e.parameters.map(t=>A(t)?t:L(t)).join(", "):""}function v(e){return[`TYPEOF ${e.field}`,...e.conditions.map(Ze),"END"]}function Ze(e){let t=e.fieldList.join(", ");return e.objectType?`${e.type} ${e.objectType} THEN ${t}`:`${e.type} ${t}`}function Je(e){return Q(e)?e.relationshipName?`${[...e.sObjectPrefix||[],e.relationshipName].join(".")}${F(e.sObjectAlias,""," ")}`:"":e.sObject?`${e.sObject}${F(e.sObjectAlias,""," ")}`:""}function U(e){return`${oe(e)?j(e.fn):e.field} ${e.operator}`}function X(e){return _e(me(e.value,e.literalType,e.operator))}function ce(e){return V(e)?e.field:j(e.fn)}function Ee(e){let t=ue(e)?`${F(e.field," ")}`:`${j(e.fn)} `;return t+=`${F(e.order," ")}${F(e.nulls,"","NULLS ")}`,t.trim()}function pe(e){return e.conditions.map(t=>{let r=t.parameters.length>1?`(${t.parameters.join(", ")})`:`${t.parameters.join(", ")}`;return`${t.groupName} ${t.selector} ${r}`}).join(" AND ")}function et(e){return!!e.groupBy&&(!Array.isArray(e.groupBy)||e.groupBy.length>0)}function tt(e){return!!e.orderBy&&(!Array.isArray(e.orderBy)||e.orderBy.length>0)}function k(e){return Array.isArray(e)?e:[e]}function*q(e){e.fields&&(yield{kind:"select",fields:e.fields});let t=Je(e);t&&(yield{kind:"value",keyword:"FROM",value:t}),e.usingScope&&(yield{kind:"value",keyword:"USING SCOPE",value:e.usingScope}),e.where&&(yield{kind:"conditions",keyword:"WHERE",clause:e.where}),e.withDataCategory&&(yield{kind:"value",keyword:"WITH DATA CATEGORY",value:pe(e.withDataCategory)}),e.withSecurityEnforced&&(yield{kind:"bare",keyword:"WITH SECURITY_ENFORCED"}),e.withAccessLevel&&(yield{kind:"bare",keyword:`WITH ${e.withAccessLevel}`}),et(e)&&(yield{kind:"list",keyword:"GROUP BY",items:k(e.groupBy).map(ce)},e.having&&(yield{kind:"conditions",keyword:"HAVING",clause:e.having})),tt(e)&&(yield{kind:"list",keyword:"ORDER BY",items:k(e.orderBy).map(Ee)}),I(e.limit)&&(yield{kind:"value",keyword:"LIMIT",value:`${e.limit}`}),I(e.offset)&&(yield{kind:"value",keyword:"OFFSET",value:`${e.offset}`}),e.for&&(yield{kind:"value",keyword:"FOR",value:e.for}),e.update&&(yield{kind:"value",keyword:"UPDATE",value:e.update})}function it(e={}){let t=e.newLineAfterKeywords??!1;return{numIndent:I(e.numIndent)&&e.numIndent>=1?Math.floor(e.numIndent):1,indentString:A(e.indentString)&&/^[ \t]*$/.test(e.indentString)?e.indentString:" ",fieldMaxLineLength:I(e.fieldMaxLineLength)?e.fieldMaxLineLength:60,fieldSubqueryParensOnOwnLine:t||(e.fieldSubqueryParensOnOwnLine??!0),newLineAfterKeywords:t}}var G=class{constructor(){this.lines=[]}push(t,r=""){this.lines.push({indent:t,text:r})}append(t,r){if(this.lines.length===0){this.push(t,r);return}this.lines[this.lines.length-1].text+=r}concat(t){this.lines.push(...t)}},K=class{constructor(t={}){this.options=it(t)}formatQuery(t){return this.render(this.query(t,0))}formatWhereOrHavingClause(t,r=0){return this.renderFragment(this.conditions(t,r))}formatSubqueryField(t){let r=new G;return this.selectSubquery(r,t,0,""),this.render(r.lines)}formatList(t){return this.renderFragment(this.listRows(t).map(r=>({indent:1,text:r})))}render(t){return t.map(r=>`${this.indent(r.indent)}${r.text}`).join(`
6
+ var Pe=Object.defineProperty;var we=(e,t,r)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var T=(e,t,r)=>we(e,typeof t!="symbol"?t+"":t,r);function f(e){return typeof e=="string"}function Ye(e){return e?e.every(t=>f(t)):!1}function y(e){return Number.isFinite(e)}function N(e){return e==null}function g(e,t,r){return N(e)?"":`${r||""}${e}${t||""}`}function Te(e,t=!1){return Array.isArray(e)?e.length>0?`(${e.join(", ")})`:t?"()":"":t?`(${e||""})`:e||""}function w(e,t,r=""){return y(e)&&e>0?Array.from({length:e},()=>t).join(r):""}function ee(e){return!e.parameters||e.parameters.length===0?[]:Ye(e.parameters)?e.parameters:f(e.parameters[0])?[e.parameters[0]]:ee(e.parameters[0])}function _e(e){if(!e.parameters||e.parameters.length===0)return!1;let t=e.parameters[0];return f(t)?!1:!!t.isAggregateFn}function Y(e){return e&&!N(e.alias)}function Se(e){return f(e.field)&&!Array.isArray(e.relationships)&&!Array.isArray(e.conditions)}function ye(e){return!N(e.functionName||e.fn)}function Ie(e){return f(e.field)&&Array.isArray(e.relationships)}function Le(e){return!N(e.subquery)}function Fe(e){return f(e.field)&&Array.isArray(e.conditions)}function W(e){return f(e.relationshipName)}function ge(e){return!!e&&!!e.type&&e.type==="FieldSubquery"}function We(e){return!!e&&!!e.operator&&!!e.right}function $e(e){return!!e&&!!e.operator&&!!e.right}function O(e){return!!e&&!!e.operator&&!!e.right}function Be(e){return e&&f(e.field)&&f(e.operator)&&!N(e.value)}function He(e){return e&&f(e.field)&&f(e.operator)&&!N(e.value)&&(e.literalType==="DATE_LITERAL"||Array.isArray(e.literalType)&&e.literalType[0]==="DATE_LITERAL")}function Qe(e){return e&&f(e.field)&&f(e.operator)&&!N(e.value)&&!N(e.dateLiteralVariable)}function te(e){return e&&!N(e.fn)&&f(e.operator)&&!N(e.value)}function m(e){return e&&y(e.openParen)&&N(e.operator)&&N(e.field)&&N(e.fn)&&N(e.closeParen)}function b(e){return e&&f(e.field)&&f(e.operator)&&!N(e.valueQuery)&&N(e.value)}function ie(e){return e&&!N(e.field)}function Ve(e){return e&&!N(e.fn)}function $(e){return e&&!N(e.field)}function Xe(e){return e&&!N(e.fn)}function je(e){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(e)}function Oe(e,t,r){if(N(t))return e;if(r&&t!=="APEX_BIND_VARIABLE"&&je(r)&&!Array.isArray(e)&&(e=[e],t=Array.isArray(t)?t:[t]),Array.isArray(t)&&Array.isArray(e))return e.map((i,s)=>qe(i,t?.[s]));switch(Array.isArray(t)&&(t=t[0]),t){case"STRING":return Array.isArray(e)?e.filter(Boolean).map(i=>J(i)):J(e);case"APEX_BIND_VARIABLE":return`:${e}`;default:return e}}function qe(e,t){switch(t){case"STRING":return J(e);case"NULL":return"null";default:return e}}function J(e){if(f(e)&&e.startsWith("'")&&e.endsWith("'")&&e.length>=2)return e;let t=String(e??"");return`'${Ze(t)}'`}var Ke=/[nNrRtTbBfF"'\\_%]/,ze=/^[0-9a-fA-F]{4}$/;function Ze(e){let t="";for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){let s=e[r+1];s!==void 0&&Ke.test(s)?(t+=i+s,r++):s==="u"&&ze.test(e.substr(r+2,4))?(t+=e.substr(r,6),r+=5):t+="\\\\"}else i==="'"?t+="\\'":t+=i}return t}var ne="[A-Za-z][A-Za-z0-9_]*",me=`${ne}(?:\\.${ne})*`,Je=new RegExp(`^\\s*(${me})\\s*([+-])\\s*(${me})\\s*$`),et=new RegExp(`^${ne}$`);function se(e){return e?.functionName==="FORMULA"&&!N(e.formula)}function xe(e){return{type:"FieldReference",parts:e.split(".")}}function be(e){let t=Je.exec(e);if(t)return{type:"BinaryExpression",operator:t[2],left:xe(t[1]),right:xe(t[3])}}function De(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"&&et.test(t))}function B(e){let t=e?.left?.parts,r=e?.right?.parts,i=e?.operator;if(i!=="+"&&i!=="-"||!De(t)||!De(r))throw new Error("Invalid FORMULA expression. Expected two field references separated by + or -.");return`${t.join(".")} ${i} ${r.join(".")}`}var C=(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))(C||{});function x(e){return e>=49&&e<=61}function D(e){return e>=62&&e<=67}function ue(e){return e>=68&&e<=69}function le(e){return e===70}function k(e){return e>=71&&e<=75}function Ue(e){return e>=77&&e<=79}function Q(e){return e>=80&&e<=102}function V(e){return e>=103&&e<=123}function ve(e){return e>=124&&e<=132}function I(e){return e===160||e>=30&&e<=48||e>=49&&e<=61||e>=62&&e<=67||e>=68&&e<=69||e===70||e>=71&&e<=75||e===76||e>=77&&e<=79||e>=80&&e<=102||e>=103&&e<=123||e>=124&&e<=132||e===159||e===153}function ce(e){return e===154||e===155||e===156||e===157}function pe(e){return e>=133&&e<=138}var tt=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]]),d=[];(function(){for(let t of Object.keys(C)){let r=C[t];typeof r=="number"&&(d[r]=t)}d[72]="toLabel",d[73]="convertTimezone",d[74]="convertCurrency",d[158]="StringIdentifier",d[151]="DATE",d[32]="new",d[126]="MineAndMyGroups",d[128]="MyTerritory",d[129]="MyTeamTerritory",d[131]="AllPrivate",d[124]="Delegated",d[125]="Everything",d[127]="Mine",d[130]="Team",d[132]="Mru",d[160]="Identifier",d[133]="EQUAL",d[157]="UNSIGNED_INTEGER",d[156]="SIGNED_INTEGER",d[155]="UNSIGNED_DECIMAL",d[154]="SIGNED_DECIMAL",d[152]="CURRENCY_PREFIXED_DECIMAL",d[153]="CURRENCY_PREFIXED_INTEGER"})();function R(e){return d[e]||C[e]}function Ee(e){return e>=65&&e<=90||e>=97&&e<=122}function h(e){return e>=48&&e<=57}function ae(e){return Ee(e)||h(e)||e===95}function H(e){return e===32||e===9||e===10||e===13||e===12}function Me(e){let t=[],r=e.length,i=0;for(;i<r;){let s=e.charCodeAt(i);if(H(s)){for(i++;i<r&&H(e.charCodeAt(i));)i++;continue}if(s===47){let o=i+1<r?e.charCodeAt(i+1):0;if(o===47){for(i+=2;i<r;){let a=e.charCodeAt(i);if(a===10||a===13)break;i++}continue}if(o===42){let a=i;i+=2;let p=!1;for(;i<r;){if(e.charCodeAt(i)===42&&i+1<r&&e.charCodeAt(i+1)===47){i+=2,p=!0;break}i++}if(!p)throw new Error(`Unterminated comment at position ${a}`);continue}}if(s===39){let o=i;for(i++;i<r;){let l=e.charCodeAt(i);if(l===92){i+=2;continue}if(l===39){i++;break}i++}let a=e.substring(o,i),u=a.substring(1,a.length-1).toUpperCase();u==="MI"||u==="KM"?t.push({kind:159,text:a,start:o}):t.push({kind:158,text:a,start:o});continue}if(h(s)){if(i+9<r&&e.charCodeAt(i+4)===45&&e.charCodeAt(i+7)===45){let a=!0;for(let p of[0,1,2,3,5,6,8,9])if(!h(e.charCodeAt(i+p))){a=!1;break}if(a)if(i+10<r&&(e.charCodeAt(i+10)===84||e.charCodeAt(i+10)===116)){let p=i;for(i+=11;i<r;){let u=e.charCodeAt(i);if(h(u)||u===58)i++;else break}if(i<r&&e.charCodeAt(i)===46)for(i++;i<r&&h(e.charCodeAt(i));)i++;if(i<r){let u=e.charCodeAt(i);if(u===90||u===122)i++;else if(u===46){for(i++;i<r&&h(e.charCodeAt(i));)i++;i<r&&(e.charCodeAt(i)===90||e.charCodeAt(i)===122)&&i++}else if(u===43||u===45)for(i++;i<r;){let l=e.charCodeAt(i);if(h(l)||l===58)i++;else break}}t.push({kind:150,text:e.substring(p,i),start:p});continue}else{let p=i;i+=10,t.push({kind:151,text:e.substring(p,i),start:p});continue}}let o=i;for(;i<r&&h(e.charCodeAt(i));)i++;if(i<r&&e.charCodeAt(i)===46&&i+1<r&&h(e.charCodeAt(i+1))){for(i++;i<r&&h(e.charCodeAt(i));)i++;t.push({kind:155,text:e.substring(o,i),start:o});continue}t.push({kind:157,text:e.substring(o,i),start:o});continue}if(s===33){if(i+1<r&&e.charCodeAt(i+1)===61){t.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 o=e.charCodeAt(i+1);if(o===61){t.push({kind:136,text:"<=",start:i}),i+=2;continue}if(o===62){t.push({kind:134,text:"<>",start:i}),i+=2;continue}}t.push({kind:135,text:"<",start:i}),i++;continue}if(s===62){if(i+1<r&&e.charCodeAt(i+1)===61){t.push({kind:138,text:">=",start:i}),i+=2;continue}t.push({kind:137,text:">",start:i}),i++;continue}if(s===61){t.push({kind:133,text:"=",start:i}),i++;continue}if(s===40){t.push({kind:139,text:"(",start:i}),i++;continue}if(s===41){t.push({kind:140,text:")",start:i}),i++;continue}if(s===91){t.push({kind:141,text:"[",start:i}),i++;continue}if(s===93){t.push({kind:142,text:"]",start:i}),i++;continue}if(s===44){t.push({kind:144,text:",",start:i}),i++;continue}if(s===58){t.push({kind:145,text:":",start:i}),i++;continue}if(s===59){t.push({kind:146,text:";",start:i}),i++;continue}if(s===42){t.push({kind:147,text:"*",start:i}),i++;continue}if(s===43||s===45){if(i+1<r){let o=e.charCodeAt(i+1);if(h(o)){let a=i;for(i++;i<r&&h(e.charCodeAt(i));)i++;if(i<r&&e.charCodeAt(i)===46&&i+1<r&&h(e.charCodeAt(i+1))){for(i++;i<r&&h(e.charCodeAt(i));)i++;t.push({kind:154,text:e.substring(a,i),start:a});continue}t.push({kind:156,text:e.substring(a,i),start:a});continue}if(o===46&&i+2<r&&h(e.charCodeAt(i+2))){let a=i;for(i+=2;i<r&&h(e.charCodeAt(i));)i++;t.push({kind:154,text:e.substring(a,i),start:a});continue}}t.push({kind:s===43?148:149,text:e[i],start:i}),i++;continue}if(s===46){if(i+1<r&&h(e.charCodeAt(i+1))){let o=i;for(i++;i<r&&h(e.charCodeAt(i));)i++;t.push({kind:155,text:e.substring(o,i),start:o});continue}t.push({kind:143,text:".",start:i}),i++;continue}if(Ee(s)){let o=i;for(i++;i<r;){let l=e.charCodeAt(i);if(ae(l)||l===46)i++;else break}let a=e.substring(o,i);if(a.includes(".."))throw new Error(`Invalid identifier with consecutive dots at position ${o}: "${a}"`);let p=a.toUpperCase();if(p==="ORDER"&&!a.includes(".")){let l=oe(e,i,"BY");if(l!==-1){let c=e.substring(o,l);t.push({kind:21,text:c,start:o}),i=l;continue}}if(p==="GROUP"&&!a.includes(".")){let l=oe(e,i,"BY");if(l!==-1){let c=e.substring(o,l);t.push({kind:10,text:c,start:o}),i=l;continue}}if(p==="DATA"&&!a.includes(".")){let l=oe(e,i,"CATEGORY");if(l!==-1){let c=e.substring(o,l);t.push({kind:35,text:c,start:o}),i=l;continue}}if(a.length>=4){let l=a.substring(0,3);if(ke(l)){let c=a.substring(3);if(it(c)){c.includes(".")?t.push({kind:152,text:a,start:o}):t.push({kind:153,text:a,start:o});continue}}}if(a.length===3&&ke(a)){let l=i,c=i,E=!1;if(c<r&&e.charCodeAt(c)===45&&(E=!0,c++),E&&c<r&&h(e.charCodeAt(c))){for(;c<r&&h(e.charCodeAt(c));)c++;if(c<r&&e.charCodeAt(c)===46&&c+1<r&&h(e.charCodeAt(c+1))){for(c++;c<r&&h(e.charCodeAt(c));)c++;let A=e.substring(o,c);t.push({kind:152,text:A,start:o}),i=c;continue}if(c>=r||!ae(e.charCodeAt(c))&&e.charCodeAt(c)!==46){let A=e.substring(o,c);t.push({kind:153,text:A,start:o}),i=c;continue}i=l}}if(a.includes(".")){t.push({kind:160,text:a,start:o});continue}let u=tt.get(p);if(u!==void 0){t.push({kind:u,text:a,start:o});continue}t.push({kind:160,text:a,start:o});continue}throw new Error(`Unexpected character '${e[i]}' (code ${s}) at position ${i}`)}return t.push({kind:161,text:"",start:i}),t}function oe(e,t,r){let i=e.length,s=t;if(s>=i||!H(e.charCodeAt(s)))return-1;for(;s<i&&H(e.charCodeAt(s));)s++;let o=r.length;if(s+o>i)return-1;for(let p=0;p<o;p++){let u=e.charCodeAt(s+p),l=r.charCodeAt(p);if((u>=97&&u<=122?u-32:u)!==l)return-1}let a=s+o;if(a<i){let p=e.charCodeAt(a);if(ae(p)||p===46)return-1}return a}function ke(e){for(let t=0;t<e.length;t++)if(!Ee(e.charCodeAt(t)))return!1;return!0}function it(e){if(e.length===0)return!1;let t=0;if(e.charCodeAt(t)===45&&t++,t>=e.length||!h(e.charCodeAt(t)))return!1;for(;t<e.length&&h(e.charCodeAt(t));)t++;if(t<e.length&&e.charCodeAt(t)===46){if(t++,t>=e.length||!h(e.charCodeAt(t)))return!1;for(;t<e.length&&h(e.charCodeAt(t));)t++}return t===e.length}var rt=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]),X=class X{constructor(t,r){T(this,"tokens");T(this,"pos",0);T(this,"config");this.tokens=t,this.config=r}getPos(){return this.pos}peek(){return this.tokens[this.pos]}peekAt(t){let r=this.pos+t;return r>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[r]}advance(){let t=this.tokens[this.pos];return t.kind!==161&&this.pos++,t}expect(t){let r=this.peek();if(r.kind!==t)throw this.error(`Expected ${C[t]} but found ${C[r.kind]} ("${r.text}") at position ${r.start}`);return this.advance()}match(t){return this.peek().kind===t?(this.advance(),!0):!1}check(t){return this.peek().kind===t}isAtEnd(){return this.peek().kind===161}error(t){return this.config.logErrors&&console.log(t),new Error(t)}isAtClauseBoundary(){let t=this.peek().kind;return X.CLAUSE_BOUNDARY_KINDS.has(t)||t===140}synchronize(){for(;!this.isAtEnd();){if(this.isAtClauseBoundary())return;this.advance()}}consumeIdentifier(){let t=this.peek();if(I(t.kind))return this.advance();throw this.error(`Expected identifier but found ${C[t.kind]} ("${t.text}") at position ${t.start}`)}checkIdentifier(){return I(this.peek().kind)}isFunctionCall(){let t=this.peek(),r=this.peekAt(1);return(x(t.kind)||D(t.kind)||ue(t.kind)||le(t.kind)||k(t.kind))&&r.kind===139}canBeAlias(){let t=this.peek();return!(!I(t.kind)||rt.has(t.kind)||t.kind===37&&this.peekAt(1).kind===157)}getLiteralType(t){let r=R(t);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(t)?"DATE_LITERAL":V(t)?"DATE_N_LITERAL":"STRING"}parseSelectStatement(t=!1){let r=this.parseSelectClause(),i=this.parseFromClause(),s;t?(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 o=this.parseClauseStatements();return Object.assign(s,o),s}parseSelectStatementPartial(){let t,r;this.check(23)&&(t=this.parseSelectClause()),this.check(9)&&(r=this.parseFromClause());let i={};t&&(i.fields=t),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(t){if(!t.sObjectAlias||!Array.isArray(t.fields))return;let r=t.sObjectAlias;t.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 t=[];for(t.push(this.parseSelectField());this.match(144);)t.push(this.parseSelectField());return t}parseSelectField(){let t=this.peek(),r=this.peekAt(1);return t.kind===139&&r.kind===23?this.parseSelectClauseSubqueryIdentifier():t.kind===42?this.parseSelectClauseTypeOf():this.isFunctionCall()?this.parseSelectClauseFunctionIdentifier():this.parseSelectClauseIdentifier()}parseSelectClauseFunctionIdentifier(){let t=this.parseAnyFunction(!0);return this.canBeAlias()&&(t.alias=this.consumeIdentifier().text),t}parseSelectClauseSubqueryIdentifier(){this.expect(139);let t=this.parseSelectStatement(!0);return this.expect(140),{type:"FieldSubquery",subquery:t}}parseSelectClauseTypeOf(){this.expect(42);let t=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:t,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 t={},r=(i,s)=>{if(this.config.ignoreParseErrors)try{i(),this.isAtClauseBoundary()||(s&&s(),this.synchronize())}catch(o){this.config.logErrors&&console.log(o),s&&s(),this.synchronize()}else i()};for(this.check(25)&&r(()=>{t.usingScope=this.parseUsingScope()}),this.check(26)&&r(()=>{t.where=this.parseWhereClause()},()=>{delete t.where});this.check(27);)r(()=>{let i=this.parseWithClause();i.withSecurityEnforced&&(t.withSecurityEnforced=!0),i.withAccessLevel&&(t.withAccessLevel=i.withAccessLevel),i.withDataCategory&&(t.withDataCategory=i.withDataCategory)});return this.check(10)&&(r(()=>{t.groupBy=this.parseGroupByClause()}),this.check(11)&&r(()=>{t.having=this.parseHavingClause()})),this.check(21)&&r(()=>{t.orderBy=this.parseOrderByClause()}),this.check(16)&&r(()=>{this.advance(),t.limit=Number(this.expect(157).text)}),this.check(37)&&r(()=>{this.advance(),t.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)t.for=R(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)t.update=R(this.advance().kind);else throw this.error(`Expected TRACKING or VIEWSTAT after UPDATE at position ${i.start}`)}),t}parseUsingScope(){this.expect(25),this.expect(39);let t=this.peek();if(ve(t.kind))return this.advance().text;if(I(t.kind))return this.advance().text;throw this.error(`Expected scope enumeration value at position ${t.start}`)}parseWhereClause(){return this.expect(26),this.parseConditionExpressions("WHERE")}parseConditionExpressions(t){let r,i,s={left:0,right:0};for(;;){let o;if(r)if(this.check(0))o="AND",this.advance();else if(this.check(20))o="OR",this.advance();else break;let a={},p=a,u=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 A={left:E>0?{openParen:E}:null,operator:"NOT",right:{left:{}}};u?u.right=A:a=A,u=A,p=A.right}else break}p.left=this.parseExpression(t,s),r?o&&(i.operator=o,i.right=a):(r=a,i=a);let l=a;for(;l.right&&l.right.left!==void 0;){let E=l.right;if(E.right&&E.right.left!==void 0)l=E;else{l=E;break}}if(i=l,this.isAtEnd())break;let c=this.peek().kind;if(c!==0&&c!==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 t=0;for(;this.peekAt(t).kind===139;)t++;return this.peekAt(t).kind===17}isNegationAhead(){let t=1;for(;this.peekAt(t).kind===139;)t++;return this.peekAt(t).kind===17}parseExpression(t,r){let i=0;for(;this.check(139)&&!this.isSubqueryStart()&&!this.isArrayExpressionStart();)this.advance(),i++,r&&r.left++;let s=t==="WHERE",o,a=!1;s&&this.peek().kind===76&&this.peekAt(1).kind===139?(o=this.parseFormulaFunction(),a=!0):D(this.peek().kind)&&this.peekAt(1).kind===139?(o=this.parseAggregateFunction(!1),a=!0):s&&ue(this.peek().kind)&&this.peek().kind===68&&this.peekAt(1).kind===139?(o=this.parseLocationFunction(!1),a=!0):x(this.peek().kind)&&this.peekAt(1).kind===139?(o=this.parseDateFunction(!1),a=!0):k(this.peek().kind)&&this.peekAt(1).kind===139?(o=this.parseOtherFunction(!1),a=!0):o=this.consumeIdentifier().text;let p=this.parseOperator(),u=p.operator,l=p.isSet,c,E,A;if(l)if(this.check(139)&&this.peekAt(1).kind===23)this.expect(139),c=this.parseSelectStatement(!1),this.expect(140),E="SUBQUERY";else if(this.config.allowApexBindVariables&&this.check(145))c=this.parseApexBindVariable().value,E="APEX_BIND_VARIABLE";else{let S=this.parseArrayExpression();c=S.values,E=S.literalType,A=S.dateLiteralVariable}else{let S=this.parseAtomicValue();c=S.value,E=S.literalType,A=S.dateLiteralVariable}let F=0;for(;this.check(140)&&(!r||r.left>r.right);)this.advance(),F++,r&&r.right++;let _={};return a?_.fn=o:_.field=o,_.operator=u,E==="SUBQUERY"?_.valueQuery=c:_.value=c,_.literalType=E,A!==void 0&&(_.dateLiteralVariable=A),i>0&&(_.openParen=i),F>0&&(_.closeParen=F),_}isSubqueryStart(){return this.check(139)&&this.peekAt(1).kind===23}isArrayExpressionStart(){return!1}parseOperator(){let t=this.peek();if(pe(t.kind))return{operator:this.advance().text,isSet:!1};if(t.kind===15)return this.advance(),{operator:"LIKE",isSet:!1};if(t.kind===12)return this.advance(),{operator:"IN",isSet:!0};if(t.kind===17&&this.peekAt(1).kind===12)return this.advance(),this.advance(),{operator:"NOT IN",isSet:!0};if(t.kind===13)return this.advance(),{operator:"INCLUDES",isSet:!0};if(t.kind===6)return this.advance(),{operator:"EXCLUDES",isSet:!0};throw this.error(`Expected operator but found ${C[t.kind]} ("${t.text}") at position ${t.start}`)}parseAtomicValue(){let t=this.peek();if(this.config.allowApexBindVariables&&t.kind===145)return{value:this.parseApexBindVariable().value,literalType:"APEX_BIND_VARIABLE"};if(t.kind===158)return{value:this.advance().text,literalType:"STRING"};if(t.kind===159)return{value:this.advance().text,literalType:"STRING"};if(t.kind===157)return{value:this.advance().text,literalType:"INTEGER"};if(t.kind===156)return{value:this.advance().text,literalType:"INTEGER"};if(t.kind===155)return{value:this.advance().text,literalType:"DECIMAL"};if(t.kind===154)return{value:this.advance().text,literalType:"DECIMAL"};if(t.kind===152)return{value:this.advance().text,literalType:"DECIMAL_WITH_CURRENCY_PREFIX"};if(t.kind===153)return{value:this.advance().text,literalType:"INTEGER_WITH_CURRENCY_PREFIX"};if(t.kind===150)return{value:this.advance().text,literalType:"DATETIME"};if(t.kind===151)return{value:this.advance().text,literalType:"DATE"};if(t.kind===18)return this.advance(),{value:"NULL",literalType:"NULL"};if(t.kind===24||t.kind===7)return{value:R(this.advance().kind),literalType:"BOOLEAN"};if(Q(t.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(V(t.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 ${C[t.kind]} ("${t.text}") at position ${t.start}`)}parseArrayExpression(){this.expect(139);let t=[];for(t.push(this.parseArrayItem());this.match(144);)t.push(this.parseArrayItem());this.expect(140);let r=t.map(u=>u.value),i=t.map(u=>u.type),s=t.map(u=>u.variable!==void 0?u.variable:null),o=s.some(u=>u!==null),a;new Set(i).size===1?a=this.getLiteralType(this.tokenKindFromTypeName(i[0])):a=i.map(u=>this.getLiteralType(this.tokenKindFromTypeName(u)));let p={values:r,literalType:a};return o&&(p.dateLiteralVariable=s),p}tokenKindFromTypeName(t){for(let r=0;r<=161;r++)if(R(r)===t)return r;return 160}parseArrayItem(){let t=this.peek();if(t.kind===158)return{value:this.advance().text,type:R(158)};if(t.kind===159)return{value:this.advance().text,type:R(159)};if(t.kind===152)return{value:this.advance().text,type:R(152)};if(t.kind===153)return{value:this.advance().text,type:R(153)};if(ce(t.kind)){let r=this.advance();return{value:r.text,type:R(r.kind)}}if(t.kind===150)return{value:this.advance().text,type:R(150)};if(t.kind===151)return{value:this.advance().text,type:R(151)};if(t.kind===18)return this.advance(),{value:"NULL",type:"NULL"};if(t.kind===24)return{value:this.advance().text,type:"TRUE"};if(t.kind===7)return{value:this.advance().text,type:"FALSE"};if(Q(t.kind))return{value:this.advance().text,type:R(t.kind)};if(V(t.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:R(r.kind),variable:s}}throw this.error(`Expected array value but found ${C[t.kind]} ("${t.text}") at position ${t.start}`)}parseApexBindVariable(){this.expect(145);let t=[];for(this.check(32)?t.push(this.parseApexBindNewInstantiation()):this.checkIdentifier()&&(this.peekAt(1).kind===139?t.push(this.parseApexBindFunctionCall()):t.push(this.parseApexBindIdentifier()));this.check(143);)this.advance(),this.checkIdentifier()&&this.peekAt(1).kind===139?t.push(this.parseApexBindFunctionCall()):this.checkIdentifier()&&t.push(this.parseApexBindIdentifier());return{value:t.join(".")}}parseApexBindIdentifier(){let t=this.consumeIdentifier().text;return this.check(141)&&(t+=this.parseApexBindArrayAccessor()),t}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 t=[];if(!this.check(140))for(t.push(this.consumeIdentifier().text);this.match(144);)t.push(this.consumeIdentifier().text);return this.expect(140),`(${t.join(", ")})`}parseApexBindArrayAccessor(){this.expect(141);let t=this.peek(),r;if(t.kind===157)r=this.advance().text;else if(I(t.kind))r=this.advance().text;else throw this.error(`Expected integer or identifier in array accessor at position ${t.start}`);return this.expect(142),`[${r}]`}parseFormulaFunction(){let t=this.expect(76);this.expect(139);let r=this.expect(158);this.expect(140);let i=be(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(!pe(s.kind))throw this.error(`Expected comparison operator after FORMULA but found ${C[s.kind]} ("${s.text}") at position ${s.start}`);let o=this.peekAt(1);if(o.kind===145)throw this.error(`Expected value after FORMULA comparison but found COLON (":") at position ${o.start}`);return{functionName:"FORMULA",parameters:[`'${B(i)}'`],rawValue:`${t.text}(${r.text})`,formula:i}}parseAnyFunction(t){let r=this.peek();if(x(r.kind))return this.parseDateFunction(t);if(D(r.kind))return this.parseAggregateFunction(t);if(r.kind===68)return this.parseLocationFunction(t);if(le(r.kind))return this.parseFieldsFunction(t);if(k(r.kind))return this.parseOtherFunction(t);throw this.error(`Expected function name but found ${C[r.kind]} at position ${r.start}`)}parseDateFunction(t){let r=this.advance(),i=R(r.kind),s=this.parseFunctionExpression(!1,t),o={};return t&&(o.type="FieldFunctionExpression"),o.functionName=i,o.parameters=s,t&&(o.isAggregateFn=!0),o.rawValue=`${r.text}(${s.map(a=>typeof a=="string"?a:a.rawValue).join(", ")})`,o}parseAggregateFunction(t){let r=this.advance(),i=R(r.kind),s=this.parseFunctionExpression(!0,t),o={};return t&&(o.type="FieldFunctionExpression"),o.functionName=i,o.parameters=s,t&&(o.isAggregateFn=!0),o.rawValue=`${r.text}(${s.map(a=>typeof a=="string"?a:a.rawValue).join(", ")})`,o}parseFieldsFunction(t){this.advance(),this.expect(139);let r=this.peek(),i;if(Ue(r.kind))i=this.advance().text;else if(I(r.kind))i=this.advance().text;else throw this.error(`Expected FIELDS function parameter at position ${r.start}`);this.expect(140);let s={};return t&&(s.type="FieldFunctionExpression"),s.functionName="FIELDS",s.parameters=[i],s.rawValue=`FIELDS(${i})`,s}parseOtherFunction(t){let r=this.advance(),i=R(r.kind),s=this.parseFunctionExpression(!1,t),o={};return t&&(o.type="FieldFunctionExpression"),o.functionName=i,o.parameters=s,o.rawValue=`${r.text}(${s.map(a=>typeof a=="string"?a:a.rawValue).join(", ")})`,o}parseLocationFunction(t){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(t):i=this.consumeIdentifier().text,this.expect(144);let s=this.expect(159).text;this.expect(140);let o={};t&&(o.type="FieldFunctionExpression"),o.functionName="DISTANCE",o.parameters=[r,i,s],t&&(o.isAggregateFn=!0);let a=typeof i=="string"?i:i.rawValue;return o.rawValue=`DISTANCE(${r}, ${a}, ${s})`,o}parseGeolocationFunction(t){this.advance(),this.expect(139);let r=this.parseNumberValue();this.expect(144);let i=this.parseNumberValue();this.expect(140);let s={};return t&&(s.type="FieldFunctionExpression"),s.functionName="GEOLOCATION",s.parameters=[r,i],s.rawValue=`GEOLOCATION(${r}, ${i})`,s}parseNumberValue(){let t=this.peek();if(t.kind===157||t.kind===156||t.kind===155||t.kind===154)return this.advance().text;throw this.error(`Expected number but found ${C[t.kind]} ("${t.text}") at position ${t.start}`)}parseFunctionExpression(t,r=!0){this.expect(139);let i=[];if(!this.check(140))for(i.push(this.parseFunctionParam(t,r));this.match(144);)i.push(this.parseFunctionParam(t,r));return this.expect(140),i}parseFunctionParam(t,r){let i=this.peek(),s=this.peekAt(1);if(!t&&D(i.kind)&&s.kind===139)return this.parseAggregateFunction(r);if(k(i.kind)&&s.kind===139)return this.parseOtherFunction(r);if(i.kind===158)return this.advance().text;if(ce(i.kind))return this.advance().text;if(I(i.kind))return this.advance().text;throw this.error(`Expected function parameter but found ${C[i.kind]} ("${i.text}") at position ${i.start}`)}parseGroupByClause(){this.expect(10);let t=[];for(t.push(this.parseGroupByItem());this.match(144);)t.push(this.parseGroupByItem());return t}parseGroupByItem(){let t=this.peek();return t.kind===4&&this.peekAt(1).kind===139?{fn:this.parseCubeOrRollupFunction("CUBE")}:t.kind===22&&this.peekAt(1).kind===139?{fn:this.parseCubeOrRollupFunction("ROLLUP")}:x(t.kind)&&this.peekAt(1).kind===139?{fn:this.parseDateFunction(!1)}:{field:this.consumeIdentifier().text}}parseCubeOrRollupFunction(t){this.advance();let r=this.parseFunctionExpression(!1);return{functionName:t,parameters:r,rawValue:`${t}(${r.join(", ")})`}}parseHavingClause(){return this.expect(11),this.parseConditionExpressions("HAVING")}parseOrderByClause(){this.expect(21);let t=[];for(t.push(this.parseOrderByItem());this.match(144);)t.push(this.parseOrderByItem());return t}parseOrderByItem(){let t=this.peek(),r=this.peekAt(1),i;if(t.kind===75&&r.kind===139){let s=this.advance(),o=this.parseFunctionExpression(!1);i={fn:{functionName:R(s.kind),parameters:o,rawValue:`${s.text}(${o.join(", ")})`}}}else D(t.kind)&&r.kind===139?i={fn:this.parseAggregateFunction(!1)}:x(t.kind)&&r.kind===139?i={fn:this.parseDateFunction(!1)}:t.kind===68&&r.kind===139?i={fn:this.parseLocationFunction(!1)}:i={field:this.consumeIdentifier().text};if(this.check(2)?i.order=R(this.advance().kind):this.check(3)&&(i.order=R(this.advance().kind)),this.check(19))if(this.advance(),this.check(8))i.nulls=R(this.advance().kind);else if(this.check(14))i.nulls=R(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 t=this.peek();if(t.kind===46)return this.advance(),{withSecurityEnforced:!0};if(t.kind===48)return this.advance(),{withAccessLevel:"USER_MODE"};if(t.kind===47)return this.advance(),{withAccessLevel:"SYSTEM_MODE"};if(t.kind===35)return{withDataCategory:this.parseWithDataCategory()};throw this.error(`Expected SECURITY_ENFORCED, USER_MODE, SYSTEM_MODE, or DATA CATEGORY after WITH at position ${t.start}`)}parseWithDataCategory(){this.expect(35);let t=[];for(t.push(this.parseDataCategoryCondition());this.check(0);)this.advance(),t.push(this.parseDataCategoryCondition());return{conditions:t}}parseDataCategoryCondition(){let t=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),o=[];for(o.push(this.consumeIdentifier().text);this.match(144);)o.push(this.consumeIdentifier().text);return s&&this.expect(140),{groupName:t,selector:i,parameters:o}}};T(X,"CLAUSE_BOUNDARY_KINDS",new Set([26,21,10,11,16,37,27,28,29,25,161]));var he=X;function j(e,t){let r=t||{},i=Me(e),s=new he(i,r),o;if(r.allowPartialQuery?o=s.parseSelectStatementPartial():o=s.parseSelectStatement(!1),!s.isAtEnd()&&!r.ignoreParseErrors){let a=i[s.getPos()];throw new Error(`Unexpected token "${a.text}" at position ${a.start}. Expected end of query.`)}return o}function nt(e,t){try{return j(e,t),!0}catch{return!1}}function Ge(e){return e===32||e===9||e===10||e===13||e===12}function de(e,t){let r=[],i=e.length,s=0;for(;s<i;){let o=e.charCodeAt(s);if(o===39){for(s++;s<i;){let a=e.charCodeAt(s);if(a===92){s+=2;continue}if(a===39){s++;break}s++}continue}if(o===47){let a=s+1<i?e.charCodeAt(s+1):0;if(a===47){let p=s;for(s+=2;s<i;){let u=e.charCodeAt(s);if(u===10||u===13)break;s++}if(r.push({type:"line",text:e.substring(p,s),start:p,end:s}),t)return r;continue}if(a===42){let p=s;for(s+=2;s<i;){if(e.charCodeAt(s)===42&&s+1<i&&e.charCodeAt(s+1)===47){s+=2;break}s++}if(r.push({type:"block",text:e.substring(p,s),start:p,end:s}),t)return r;continue}}s++}return r}function st(e){return de(e,!1)}function ot(e){return de(e,!0).length>0}function at(e){let t=de(e,!1);if(t.length===0)return e;let r="",i=0;for(let s of t){r+=e.substring(i,s.start);let o=r.length>0?r.charCodeAt(r.length-1):0,a=s.end<e.length?e.charCodeAt(s.end):0;o!==0&&!Ge(o)&&a!==0&&!Ge(a)&&(r+=" "),i=s.end}return r+=e.substring(i),r}function Ot(e){return ut(e)}function ut(e){if(typeof e=="string")return{type:"Field",field:e};if(ye(e)){let t=[];return e.parameters&&(t=Array.isArray(e.parameters)?e.parameters:[e.parameters]),{type:"FieldFunctionExpression",functionName:e.functionName||e.fn,parameters:t,alias:e.alias}}else{if(Ie(e))return{type:"FieldRelationship",field:e.field,relationships:e.relationships,objectPrefix:e.objectPrefix};if(Le(e))return{type:"FieldSubquery",subquery:e.subquery};if(Fe(e))return{type:"FieldTypeof",field:e.field,conditions:e.conditions};if(Se(e))return{type:"Field",field:e.field,objectPrefix:e.objectPrefix};throw new TypeError("The input object provided did not match any valid field types")}}function mt(e,t){if(!e)return[];e=ge(e)?e.subquery:e;let r=e.fields;if(!r)return[];let i={};e.groupBy&&(i=(Array.isArray(e.groupBy)?e.groupBy:[e.groupBy]).reduce((u,l)=>($(l)&&(u[l.field.toLocaleLowerCase()]=l.field),u),{}));let s=-1,o=(W(e)?e.relationshipName:e.sObject||"").toLowerCase(),a=(e.sObjectAlias||"").toLowerCase();return r.flatMap(u=>{switch(u.type){case"Field":return u.alias||u.field;case"FieldFunctionExpression":{let l=ee(u);if(l=l.map(c=>{if(c.includes(".")){let E=c.split("."),A=E[0].toLowerCase();return(A===a||A===o)&&(E=E.slice(1)),E.join(".")}return c}),u.alias&&(u.isAggregateFn||t))return u.alias;if(u.alias){let c=l[0];return c.includes(".")?(l=c.split(".").slice(0,-1),l.push(u.alias),l.join(".")):u.alias}return u.isAggregateFn||_e(u)||t?(s++,`expr${s}`):l.length>0?l.join("."):u.functionName}case"FieldRelationship":{let l=u.relationships[0].toLowerCase();return Y(u)?u.alias:u.rawValue&&i[u.rawValue.toLocaleLowerCase()]?u.field:l===a||l===o?u.relationships.concat([u.field]).slice(1).join("."):u.relationships.concat([u.field]).join(".")}case"FieldSubquery":return u.subquery.relationshipName;case"FieldTypeof":{let l=new Set,c=[];return u.conditions.forEach(E=>{E.fieldList.forEach(A=>{l.has(A)||(l.add(A),c.push(`${u.field}.${A}`))})}),c}default:break}}).filter(u=>f(u))}function q(e){if(se(e))return`FORMULA('${B(e.formula)}')`;let t;return e.rawValue?t=e.rawValue:t=`${e.functionName}(${(e.parameters||[]).map(r=>f(r)?r:q(r)).join(", ")})`,e.alias&&(t+=` ${e.alias}`),t}function L(e){let t=e.objectPrefix?`${e.objectPrefix}.`:"";switch(e.type){case"Field":return`${t}${e.field}${e.alias?` ${e.alias}`:""}`;case"FieldFunctionExpression":return`${e.functionName}(${lt(e)})${e.alias?` ${e.alias}`:""}`;case"FieldRelationship":return`${t}${e.relationships.join(".")}.${e.field}${Y(e)?` ${e.alias}`:""}`;case"FieldTypeof":return v(e).join(" ");default:return""}}function lt(e){return e.parameters?e.parameters.map(t=>f(t)?t:L(t)).join(", "):""}function v(e){return[`TYPEOF ${e.field}`,...e.conditions.map(ct),"END"]}function ct(e){let t=e.fieldList.join(", ");return e.objectType?`${e.type} ${e.objectType} THEN ${t}`:`${e.type} ${t}`}function pt(e){return W(e)?e.relationshipName?`${[...e.sObjectPrefix||[],e.relationshipName].join(".")}${g(e.sObjectAlias,""," ")}`:"":e.sObject?`${e.sObject}${g(e.sObjectAlias,""," ")}`:""}function M(e){return`${te(e)?q(e.fn):e.field} ${e.operator}`}function K(e){return Te(Oe(e.value,e.literalType,e.operator))}function fe(e){return $(e)?e.field:q(e.fn)}function Ae(e){let t=ie(e)?`${g(e.field," ")}`:`${q(e.fn)} `;return t+=`${g(e.order," ")}${g(e.nulls,"","NULLS ")}`,t.trim()}function Ne(e){return e.conditions.map(t=>{let r=t.parameters.length>1?`(${t.parameters.join(", ")})`:`${t.parameters.join(", ")}`;return`${t.groupName} ${t.selector} ${r}`}).join(" AND ")}function Et(e){return!!e.groupBy&&(!Array.isArray(e.groupBy)||e.groupBy.length>0)}function ht(e){return!!e.orderBy&&(!Array.isArray(e.orderBy)||e.orderBy.length>0)}function U(e){return Array.isArray(e)?e:[e]}function*z(e){e.fields&&(yield{kind:"select",fields:e.fields});let t=pt(e);t&&(yield{kind:"value",keyword:"FROM",value:t}),e.usingScope&&(yield{kind:"value",keyword:"USING SCOPE",value:e.usingScope}),e.where&&(yield{kind:"conditions",keyword:"WHERE",clause:e.where}),e.withDataCategory&&(yield{kind:"value",keyword:"WITH DATA CATEGORY",value:Ne(e.withDataCategory)}),e.withSecurityEnforced&&(yield{kind:"bare",keyword:"WITH SECURITY_ENFORCED"}),e.withAccessLevel&&(yield{kind:"bare",keyword:`WITH ${e.withAccessLevel}`}),Et(e)&&(yield{kind:"list",keyword:"GROUP BY",items:U(e.groupBy).map(fe)},e.having&&(yield{kind:"conditions",keyword:"HAVING",clause:e.having})),ht(e)&&(yield{kind:"list",keyword:"ORDER BY",items:U(e.orderBy).map(Ae)}),y(e.limit)&&(yield{kind:"value",keyword:"LIMIT",value:`${e.limit}`}),y(e.offset)&&(yield{kind:"value",keyword:"OFFSET",value:`${e.offset}`}),e.for&&(yield{kind:"value",keyword:"FOR",value:e.for}),e.update&&(yield{kind:"value",keyword:"UPDATE",value:e.update})}function dt(e={}){let t=e.newLineAfterKeywords??!1;return{numIndent:y(e.numIndent)&&e.numIndent>=1?Math.floor(e.numIndent):1,indentString:f(e.indentString)&&/^[ \t]*$/.test(e.indentString)?e.indentString:" ",fieldMaxLineLength:y(e.fieldMaxLineLength)?e.fieldMaxLineLength:60,fieldSubqueryParensOnOwnLine:t||(e.fieldSubqueryParensOnOwnLine??!0),newLineAfterKeywords:t}}var G=class{constructor(){T(this,"lines",[])}push(t,r=""){this.lines.push({indent:t,text:r})}append(t,r){if(this.lines.length===0){this.push(t,r);return}this.lines[this.lines.length-1].text+=r}concat(t){this.lines.push(...t)}},Z=class{constructor(t={}){T(this,"options");this.options=dt(t)}formatQuery(t){return this.render(this.query(t,0))}formatWhereOrHavingClause(t,r=0){return this.renderFragment(this.conditions(t,r))}formatSubqueryField(t){let r=new G;return this.selectSubquery(r,t,0,""),this.render(r.lines)}formatList(t){return this.renderFragment(this.listRows(t).map(r=>({indent:1,text:r})))}render(t){return t.map(r=>`${this.indent(r.indent)}${r.text}`).join(`
7
7
  `)}renderFragment(t){return t.map((r,i)=>i===0?r.text:`${this.indent(r.indent)}${r.text}`).join(`
8
- `)}indent(t){return this.options.indentString.repeat(this.options.numIndent*Math.max(t,0))}query(t,r){let i=new G;for(let s of q(t))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(t,r,i,s){this.options.newLineAfterKeywords?(t.push(r,i),t.push(r+1,s)):t.push(r,`${i} ${s}`)}keywordThen(t,r,i,s){let[a,...o]=s;this.options.newLineAfterKeywords||!a?(t.push(r,i),t.concat(s)):(t.push(r,`${i} ${a.text}`),t.concat(o))}selectClause(t,r,i){let{newLineAfterKeywords:s}=this.options;t.push(i,"SELECT");let a=this.wrapper(!1),o=[],E=!1,u=!s,c=l=>{if(o.length>0){let p=`${o.join(", ")}${l?",":""}`;u?t.append(i,` ${p}`):t.push(i+1,p),o=[]}u=!1};r.forEach((l,p)=>{let h=p===r.length-1,_=h?"":",";if(l.type==="FieldSubquery")c(!0),a.reset(),this.selectSubquery(t,l.subquery,i+1,_),E=!0;else if(l.type==="FieldTypeof")c(!0),a.reset(),this.typeOfField(t,l,i+1,_),E=!0;else{let T=L(l);(a.startsNewRow(T,h)||E)&&(c(!0),E=!1),o.push(T)}}),c(!1)}wrapper(t){let{fieldMaxLineLength:r}=this.options,i=0;return{startsNewRow(s,a){let o=s.length+(a?0:2);return t||i+o>r?(i=o,!0):(i+=o,!1)},reset(){i=0}}}selectSubquery(t,r,i,s){if(this.options.fieldSubqueryParensOnOwnLine)t.push(i,"("),t.concat(this.query(r,i+1)),t.push(i,`)${s}`);else{let a=this.query(r,i);if(a.length===0){t.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}`},t.concat(a)}}typeOfField(t,r,i,s){if(!this.options.newLineAfterKeywords){t.push(i,`${v(r).join(" ")}${s}`);return}t.push(i,`TYPEOF ${r.field}`),r.conditions.forEach(a=>{t.push(i+1,a.type),a.objectType&&(t.push(i+2,a.objectType),t.push(i+1,"THEN")),t.push(i+2,a.fieldList.join(", "))}),t.push(i,`END${s}`)}listClause(t,r,i,s){this.keywordThen(t,r,i,this.listRows(s).map(a=>({indent:r+1,text:a})))}listRows(t){let r=this.wrapper(this.options.newLineAfterKeywords),i=[],s=[];return t.forEach((a,o)=>{r.startsNewRow(a,o===t.length-1)&&s.length>0&&(i.push(`${s.join(", ")},`),s=[]),s.push(a)}),i.push(s.join(", ")),i}conditions(t,r){let i=new G,s=[],a=()=>r+s.length+1,o=t;for(;o;){let E=o.left,u=m(o)?o.right:void 0;if(x(E)){let c=this.isSelfContainedNegation(u);for(let l=0;l<E.openParen;l++){let p=c&&l===E.openParen-1;i.append(a(),"("),s.push(p),p||i.push(a())}}else if(E){for(let c=0;c<(E.openParen||0);c++)i.append(a(),"("),s.push(!1),i.push(a());this.condition(i,E,a());for(let c=0;c<(E.closeParen||0);c++){let l=s.pop()??!1,p=a();l?i.append(p,")"):i.push(p,")")}}m(o)&&(o.operator==="NOT"?i.append(a(),"NOT "):i.push(a(),`${o.operator} `)),o=u}return i.lines}isSelfContainedNegation(t){let r=t?.left;return!!r&&!x(r)&&!r.openParen&&(r.closeParen||0)>0}condition(t,r,i){if(b(r))if(t.append(i,`${U(r)} (`),this.options.fieldSubqueryParensOnOwnLine)t.concat(this.query(r.valueQuery,i+1)),t.push(i,")");else{let s=this.query(r.valueQuery,i);s.length>0&&(t.append(i,s[0].text),t.concat(s.slice(1))),t.append(i,")")}else t.append(i,`${U(r)} ${X(r)}`)}};function M(e){let t=[];for(let r of q(e))switch(r.kind){case"select":{let i=r.fields.map(s=>s.type==="FieldSubquery"?`(${M(s.subquery)})`:L(s));t.push(`SELECT ${i.join(", ")}`);break}case"value":t.push(`${r.keyword} ${r.value}`);break;case"bare":t.push(r.keyword);break;case"list":t.push(`${r.keyword} ${r.items.join(", ")}`);break;case"conditions":t.push(`${r.keyword} ${he(r.clause)}`);break}return t.join(" ").trim()}function he(e){let t="",r=e;for(;r;){let i=r.left;x(i)?t+=$(i.openParen,"("):i&&(t+=$(i.openParen??0,"("),t+=`${U(i)} `,t+=b(i)?`(${M(i.valueQuery)})`:X(i),t+=$(i.closeParen??0,")")),m(r)?(t+=r.operator==="NOT"?"NOT ":` ${r.operator} `,r=r.right):r=void 0}return t}function Lt(e,t,r){return rt(B(e,r),{format:!0,formatOptions:t})}function rt(e,t={}){if(!e)return"";t=t||{},t.format=!!t.format,t.logging&&(console.time("composer"),console.log("Composing Query:",e),console.log("Format output:",t.format));let r=new de(e,t).query;return t.logging&&console.timeEnd("composer"),r}var de=class{constructor(t,r={}){this.soql=t;this.logging=!1;this.format=!1;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()}start(){this.query=this.parseQuery(this.soql)}log(t){this.logging&&console.log("Current SOQL:",t)}parseQuery(t){let r=this.format?this.formatter.formatQuery(t):M(t);return this.log(r),r}parseFields(t){return t.map(r=>r.type==="FieldSubquery"?{text:this.format?this.formatter.formatSubqueryField(r.subquery):`(${M(r.subquery)})`}:{text:L(r),typeOfClause:r.type==="FieldTypeof"?this.parseTypeOfField(r):void 0})}parseTypeOfField(t){return v(t)}parseWhereOrHavingClause(t,r=0){return this.format?this.formatter.formatWhereOrHavingClause(t,r):he(t)}parseGroupByClause(t){let r=k(t).map(ce);return this.format?this.formatter.formatList(r):r.join(", ")}parseOrderBy(t){let r=k(t).map(Ee);return this.format?this.formatter.formatList(r):r.join(", ")}parseWithDataCategory(t){return pe(t)}};export{de as Compose,rt as composeQuery,Lt as formatQuery,ve as getComments,ct as getComposedField,Ke as getField,Et as getFlattenedFields,H as hasAlias,Ue as hasComments,Fe as isFieldSubquery,V as isGroupByField,He as isGroupByFn,we as isHavingClauseWithRightCondition,x as isNegationCondition,ue as isOrderByField,$e as isOrderByFn,ke as isQueryValid,A as isString,Q as isSubquery,Ye as isValueCondition,oe as isValueFunctionCondition,b as isValueQueryCondition,We as isValueWithDateLiteralCondition,Be as isValueWithDateNLiteralCondition,Pe as isWhereClauseWithRightCondition,m as isWhereOrHavingClauseWithRightCondition,B as parseQuery,Ge as stripComments};
8
+ `)}indent(t){return this.options.indentString.repeat(this.options.numIndent*Math.max(t,0))}query(t,r){let i=new G;for(let s of z(t))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(t,r,i,s){this.options.newLineAfterKeywords?(t.push(r,i),t.push(r+1,s)):t.push(r,`${i} ${s}`)}keywordThen(t,r,i,s){let[o,...a]=s;this.options.newLineAfterKeywords||!o?(t.push(r,i),t.concat(s)):(t.push(r,`${i} ${o.text}`),t.concat(a))}selectClause(t,r,i){let{newLineAfterKeywords:s}=this.options;t.push(i,"SELECT");let o=this.wrapper(!1),a=[],p=!1,u=!s,l=c=>{if(a.length>0){let E=`${a.join(", ")}${c?",":""}`;u?t.append(i,` ${E}`):t.push(i+1,E),a=[]}u=!1};r.forEach((c,E)=>{let A=E===r.length-1,F=A?"":",";if(c.type==="FieldSubquery")l(!0),o.reset(),this.selectSubquery(t,c.subquery,i+1,F),p=!0;else if(c.type==="FieldTypeof")l(!0),o.reset(),this.typeOfField(t,c,i+1,F),p=!0;else{let _=L(c);(o.startsNewRow(_,A)||p)&&(l(!0),p=!1),a.push(_)}}),l(!1)}wrapper(t){let{fieldMaxLineLength:r}=this.options,i=0;return{startsNewRow(s,o){let a=s.length+(o?0:2);return t||i+a>r?(i=a,!0):(i+=a,!1)},reset(){i=0}}}selectSubquery(t,r,i,s){if(this.options.fieldSubqueryParensOnOwnLine)t.push(i,"("),t.concat(this.query(r,i+1)),t.push(i,`)${s}`);else{let o=this.query(r,i);if(o.length===0){t.push(i,`()${s}`);return}o[0]={...o[0],text:`(${o[0].text}`};let a=o.length-1;o[a]={...o[a],text:`${o[a].text})${s}`},t.concat(o)}}typeOfField(t,r,i,s){if(!this.options.newLineAfterKeywords){t.push(i,`${v(r).join(" ")}${s}`);return}t.push(i,`TYPEOF ${r.field}`),r.conditions.forEach(o=>{t.push(i+1,o.type),o.objectType&&(t.push(i+2,o.objectType),t.push(i+1,"THEN")),t.push(i+2,o.fieldList.join(", "))}),t.push(i,`END${s}`)}listClause(t,r,i,s){this.keywordThen(t,r,i,this.listRows(s).map(o=>({indent:r+1,text:o})))}listRows(t){let r=this.wrapper(this.options.newLineAfterKeywords),i=[],s=[];return t.forEach((o,a)=>{r.startsNewRow(o,a===t.length-1)&&s.length>0&&(i.push(`${s.join(", ")},`),s=[]),s.push(o)}),i.push(s.join(", ")),i}conditions(t,r){let i=new G,s=[],o=()=>r+s.length+1,a=t;for(;a;){let p=a.left,u=O(a)?a.right:void 0;if(m(p)){let l=this.isSelfContainedNegation(u);for(let c=0;c<p.openParen;c++){let E=l&&c===p.openParen-1;i.append(o(),"("),s.push(E),E||i.push(o())}}else if(p){for(let l=0;l<(p.openParen||0);l++)i.append(o(),"("),s.push(!1),i.push(o());this.condition(i,p,o());for(let l=0;l<(p.closeParen||0);l++){let c=s.pop()??!1,E=o();c?i.append(E,")"):i.push(E,")")}}O(a)&&(a.operator==="NOT"?i.append(o(),"NOT "):i.push(o(),`${a.operator} `)),a=u}return i.lines}isSelfContainedNegation(t){let r=t?.left;return!!r&&!m(r)&&!r.openParen&&(r.closeParen||0)>0}condition(t,r,i){if(b(r))if(t.append(i,`${M(r)} (`),this.options.fieldSubqueryParensOnOwnLine)t.concat(this.query(r.valueQuery,i+1)),t.push(i,")");else{let s=this.query(r.valueQuery,i);s.length>0&&(t.append(i,s[0].text),t.concat(s.slice(1))),t.append(i,")")}else t.append(i,`${M(r)} ${K(r)}`)}};function P(e){let t=[];for(let r of z(e))switch(r.kind){case"select":{let i=r.fields.map(s=>s.type==="FieldSubquery"?`(${P(s.subquery)})`:L(s));t.push(`SELECT ${i.join(", ")}`);break}case"value":t.push(`${r.keyword} ${r.value}`);break;case"bare":t.push(r.keyword);break;case"list":t.push(`${r.keyword} ${r.items.join(", ")}`);break;case"conditions":t.push(`${r.keyword} ${Re(r.clause)}`);break}return t.join(" ").trim()}function Re(e){let t="",r=e;for(;r;){let i=r.left;m(i)?t+=w(i.openParen,"("):i&&(t+=w(i.openParen??0,"("),t+=`${M(i)} `,t+=b(i)?`(${P(i.valueQuery)})`:K(i),t+=w(i.closeParen??0,")")),O(r)?(t+=r.operator==="NOT"?"NOT ":` ${r.operator} `,r=r.right):r=void 0}return t}function Qt(e,t,r){return ft(j(e,r),{format:!0,formatOptions:t})}function ft(e,t={}){if(!e)return"";t=t||{},t.format=!!t.format,t.logging&&(console.time("composer"),console.log("Composing Query:",e),console.log("Format output:",t.format));let r=new Ce(e,t).query;return t.logging&&console.timeEnd("composer"),r}var Ce=class{constructor(t,r={}){T(this,"soql",t);T(this,"logging",!1);T(this,"format",!1);T(this,"query");T(this,"formatter");r={autoCompose:!0,...r};let{logging:i,format:s}=r;this.logging=!!i,this.format=!!s,this.query="",this.formatter=new Z(r.formatOptions),r.autoCompose&&this.start()}start(){this.query=this.parseQuery(this.soql)}log(t){this.logging&&console.log("Current SOQL:",t)}parseQuery(t){let r=this.format?this.formatter.formatQuery(t):P(t);return this.log(r),r}parseFields(t){return t.map(r=>r.type==="FieldSubquery"?{text:this.format?this.formatter.formatSubqueryField(r.subquery):`(${P(r.subquery)})`}:{text:L(r),typeOfClause:r.type==="FieldTypeof"?this.parseTypeOfField(r):void 0})}parseTypeOfField(t){return v(t)}parseWhereOrHavingClause(t,r=0){return this.format?this.formatter.formatWhereOrHavingClause(t,r):Re(t)}parseGroupByClause(t){let r=U(t).map(fe);return this.format?this.formatter.formatList(r):r.join(", ")}parseOrderBy(t){let r=U(t).map(Ae);return this.format?this.formatter.formatList(r):r.join(", ")}parseWithDataCategory(t){return Ne(t)}};export{Ce as Compose,ft as composeQuery,Qt as formatQuery,st as getComments,Ot as getComposedField,ut as getField,mt as getFlattenedFields,Y as hasAlias,ot as hasComments,ge as isFieldSubquery,se as isFormulaFunction,$ as isGroupByField,Xe as isGroupByFn,$e as isHavingClauseWithRightCondition,m as isNegationCondition,ie as isOrderByField,Ve as isOrderByFn,nt as isQueryValid,f as isString,W as isSubquery,Be as isValueCondition,te as isValueFunctionCondition,b as isValueQueryCondition,He as isValueWithDateLiteralCondition,Qe as isValueWithDateNLiteralCondition,We as isWhereClauseWithRightCondition,O as isWhereOrHavingClauseWithRightCondition,j as parseQuery,at as stripComments};
@@ -87,6 +87,9 @@ export interface WhereClauseWithRightCondition extends WhereClauseWithoutOperato
87
87
  operator: LogicalOperator;
88
88
  right: WhereClause;
89
89
  }
90
+ /**
91
+ * This is a special case where the left side of the where clause can potentially be null if there is a negation without parentheses
92
+ */
90
93
  export interface WhereClauseWithoutNegationOperator {
91
94
  left: NegationCondition | null;
92
95
  operator: LogicalOperatorNot;
@@ -124,7 +127,7 @@ export interface ValueQueryCondition extends OptionalParentheses {
124
127
  literalType?: 'SUBQUERY';
125
128
  }
126
129
  export interface ValueFunctionCondition extends OptionalParentheses {
127
- fn: FunctionExp;
130
+ fn: FunctionExp | FormulaFunctionExp;
128
131
  operator: Operator;
129
132
  value: string | string[];
130
133
  literalType?: LiteralType | LiteralType[];
@@ -165,6 +168,21 @@ export interface FunctionExp {
165
168
  parameters?: (string | FunctionExp)[];
166
169
  isAggregateFn?: boolean;
167
170
  }
171
+ export type FormulaArithmeticOperator = '+' | '-';
172
+ export interface FormulaFieldReference {
173
+ type: 'FieldReference';
174
+ parts: string[];
175
+ }
176
+ export interface FormulaBinaryExpression {
177
+ type: 'BinaryExpression';
178
+ operator: FormulaArithmeticOperator;
179
+ left: FormulaFieldReference;
180
+ right: FormulaFieldReference;
181
+ }
182
+ export interface FormulaFunctionExp extends FunctionExp {
183
+ functionName: 'FORMULA';
184
+ formula: FormulaBinaryExpression;
185
+ }
168
186
  export interface WithDataCategoryClause {
169
187
  conditions: WithDataCategoryCondition[];
170
188
  }
@@ -1,6 +1,7 @@
1
1
  import { hasAlias, isFieldSubquery, isGroupByField, isGroupByFn, isHavingClauseWithRightCondition, isNegationCondition, isOrderByField, isOrderByFn, isString, isSubquery, isValueCondition, isValueFunctionCondition, isValueQueryCondition, isValueWithDateLiteralCondition, isValueWithDateNLiteralCondition, isWhereClauseWithRightCondition, isWhereOrHavingClauseWithRightCondition } from '../utils';
2
+ import { isFormulaFunction } from '../formula';
2
3
  import * as SoqlModels from './api-models';
3
- export { hasAlias, isFieldSubquery, isGroupByField, isGroupByFn, isHavingClauseWithRightCondition, isNegationCondition, isOrderByField, isOrderByFn, isString, isSubquery, isValueCondition, isValueFunctionCondition, isValueQueryCondition, isValueWithDateLiteralCondition, isValueWithDateNLiteralCondition, isWhereClauseWithRightCondition, isWhereOrHavingClauseWithRightCondition, };
4
+ export { hasAlias, isFieldSubquery, isFormulaFunction, isGroupByField, isGroupByFn, isHavingClauseWithRightCondition, isNegationCondition, isOrderByField, isOrderByFn, isString, isSubquery, isValueCondition, isValueFunctionCondition, isValueQueryCondition, isValueWithDateLiteralCondition, isValueWithDateNLiteralCondition, isWhereClauseWithRightCondition, isWhereOrHavingClauseWithRightCondition, };
4
5
  export type ComposeFieldInput = ComposeField | ComposeFieldFunction | ComposeFieldRelationship | ComposeFieldSubquery | ComposeFieldTypeof;
5
6
  export interface ComposeField {
6
7
  field: string;
@@ -24,6 +25,26 @@ export interface ComposeFieldTypeof {
24
25
  field: string;
25
26
  conditions: SoqlModels.FieldTypeOfCondition[];
26
27
  }
28
+ /**
29
+ * @deprecated - use `getField()` instead
30
+ * Pass any a basic string or populate required properties on the ComposeField object
31
+ * and a constructed field will be returned
32
+ * @param input string | ComposeFieldInput
33
+ * @returns FieldType
34
+ */
27
35
  export declare function getComposedField(input: string | ComposeFieldInput): SoqlModels.FieldType;
36
+ /**
37
+ * Pass any a basic string or populate required properties on the ComposeField object
38
+ * and a constructed field will be returned
39
+ * @param input string | ComposeFieldInput
40
+ * @returns FieldType
41
+ */
28
42
  export declare function getField(input: string | ComposeFieldInput): SoqlModels.FieldType;
43
+ /**
44
+ * Gets flattened fields - this will turn a Query into a list of fields that can be used to parse results from a returned dataset from SFDC
45
+ * Subqueries only include the child SObject relationship name
46
+ * @param query
47
+ * @param [isAggregateResult] pass in true to force expr0...1 for all non-aliased functions even if field is not explicitly an aggregate expression
48
+ * @returns flattened fields
49
+ */
29
50
  export declare function getFlattenedFields(query: SoqlModels.Query | SoqlModels.Subquery | SoqlModels.FieldSubquery, isAggregateResult?: boolean): string[];
@@ -7,8 +7,30 @@ export interface SoqlComposeConfig {
7
7
  formatOptions?: FormatOptions;
8
8
  autoCompose: boolean;
9
9
  }
10
+ /**
11
+ * Formats query - This will compose and then parse a query with the provided format options
12
+ * or the defaults if omitted
13
+ * @param soql
14
+ * @param [formatOptions]
15
+ * @returns
16
+ */
10
17
  export declare function formatQuery(soql: string, formatOptions?: FormatOptions, parseOptions?: ParseQueryConfig): string;
18
+ /**
19
+ * Composes a parsed query back to a SOQL query
20
+ * The parsing methods are public in case there is a need to parse just a part of a query,
21
+ * but the common case is to call the "start()" method
22
+ * @param soql
23
+ * @param [config]
24
+ * @returns query
25
+ */
11
26
  export declare function composeQuery(soql: Query, config?: Partial<SoqlComposeConfig>): string;
27
+ /**
28
+ * Compose
29
+ * This class handles all the logic for turning a Query into a SOQL query.
30
+ * The individual methods are public so that parts of a query can be composed in isolation
31
+ * (create an instance with `autoCompose: false` and call the method for the part you need).
32
+ * With `format: false` (the default) the output is a single line, otherwise the `Formatter` produces multi-line output.
33
+ */
12
34
  export declare class Compose {
13
35
  private soql;
14
36
  logging: boolean;
@@ -16,16 +38,67 @@ export declare class Compose {
16
38
  query: string;
17
39
  formatter: Formatter;
18
40
  constructor(soql: Query, config?: Partial<SoqlComposeConfig>);
41
+ /**
42
+ * Starts compose
43
+ */
19
44
  start(): void;
45
+ /**
46
+ * If logging is enabled, print the query to the console
47
+ * @param soql
48
+ */
20
49
  private log;
50
+ /**
51
+ * Parses query
52
+ * Base entry point for the query
53
+ * @param query
54
+ * @returns query
55
+ */
21
56
  parseQuery(query: Query | Subquery): string;
57
+ /**
58
+ * Parses fields
59
+ * e.x.: SELECT amount, FORMAT(amount) Amt, (SELECT Id, Name FROM Contacts)
60
+ * @param fields
61
+ * @returns fields
62
+ */
22
63
  parseFields(fields: FieldType[]): {
23
64
  text: string;
24
65
  typeOfClause?: string[];
25
66
  }[];
67
+ /**
68
+ * Parses type of Field
69
+ * e.x.: TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate ELSE Name
70
+ * @param typeOfField
71
+ * @returns type of field
72
+ */
26
73
  parseTypeOfField(typeOfField: FieldTypeOf): string[];
74
+ /**
75
+ * Parses where clause
76
+ * e.x.: WHERE LoginTime > 2010-09-20T22:16:30.000Z AND LoginTime < 2010-09-21T22:16:30.000Z
77
+ * WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName LIKE 'apple%') AND Id IN (SELECT AccountId FROM Opportunity WHERE isClosed = false)
78
+ * @param whereOrHaving
79
+ * @param [indent] - Only used when formatting: the indentation level of the clause. Defaults to 0.
80
+ * @returns where clause
81
+ */
27
82
  parseWhereOrHavingClause(whereOrHaving: WhereClause | HavingClause, indent?: number): string;
83
+ /**
84
+ * Parses group by clause
85
+ * e.x.: GROUP BY CampaignId
86
+ * @param groupBy
87
+ * @returns group by clause
88
+ */
28
89
  parseGroupByClause(groupBy: GroupByClause | GroupByClause[]): string;
90
+ /**
91
+ * Parses order by
92
+ * e.x.: ORDER BY BillingPostalCode ASC NULLS LAST
93
+ * @param orderBy
94
+ * @returns order by
95
+ */
29
96
  parseOrderBy(orderBy: OrderByClause | OrderByClause[]): string;
97
+ /**
98
+ * Parses with data category
99
+ * e.x.: WITH DATA CATEGORY Geography__c AT (usa__c, uk__c)
100
+ * @param withDataCategory
101
+ * @returns with data category
102
+ */
30
103
  parseWithDataCategory(withDataCategory: WithDataCategoryClause): string;
31
104
  }
@@ -1,21 +1,67 @@
1
- import { ConditionWithValueQuery, FieldType, FieldTypeOf, FieldTypeOfCondition, FunctionExp, GroupByClause, HavingClause, NegationCondition, OrderByClause, Query, Subquery, ValueQueryCondition, WhereClause, WithDataCategoryClause } from '../api/api-models';
2
- export declare function renderFn(fn: FunctionExp): string;
1
+ import { ConditionWithValueQuery, FieldType, FieldTypeOf, FieldTypeOfCondition, FormulaFunctionExp, FunctionExp, GroupByClause, HavingClause, NegationCondition, OrderByClause, Query, Subquery, ValueQueryCondition, WhereClause, WithDataCategoryClause } from '../api/api-models';
2
+ /**
3
+ * Leaf renderers and the shared clause sequence, used by both the plain composer and the formatter.
4
+ *
5
+ * Every renderer in this module turns one node of the parsed query into a string
6
+ * *without* making any whitespace/newline/indentation decisions and *without* rendering subqueries -
7
+ * that is the job of the callers (`composePlain()` and `Formatter`).
8
+ * `queryClauses()` owns the order and presence of the clauses themselves, so the two callers
9
+ * only decide layout. None of these functions mutate their input.
10
+ */
11
+ /**
12
+ * Renders a function expression, e.g. `COUNT(Id) total` or `FORMULA('Amount - Cost')`.
13
+ * A FORMULA that carries a nested `formula` AST is always rebuilt from that AST and its `rawValue` is ignored.
14
+ * Every other function, including a FORMULA without `formula`, prefers `rawValue` when populated,
15
+ * otherwise it is built from `functionName` and `parameters`.
16
+ */
17
+ export declare function renderFn(fn: FunctionExp | FormulaFunctionExp): string;
18
+ /**
19
+ * Renders the text of a SELECT field. Subquery fields are not handled here since they require
20
+ * rendering a nested query - callers must handle `FieldSubquery` themselves.
21
+ * TYPEOF fields are rendered on a single line (see `renderTypeOfParts` for the individual parts).
22
+ */
3
23
  export declare function renderFieldText(field: Exclude<FieldType, {
4
24
  type: 'FieldSubquery';
5
25
  }>): string;
26
+ /**
27
+ * Renders a TYPEOF field as its individual parts, e.g.
28
+ * `['TYPEOF What', 'WHEN Account THEN Phone, NumberOfEmployees', 'ELSE Name, Email', 'END']`
29
+ */
6
30
  export declare function renderTypeOfParts(field: FieldTypeOf): string[];
7
31
  export declare function renderTypeOfCondition(condition: FieldTypeOfCondition): string;
32
+ /**
33
+ * Renders the FROM target (object or relationship, with optional alias), or an empty string if there is none.
34
+ * e.g. `Account a`, `Account.Contacts c`
35
+ */
8
36
  export declare function renderFrom(query: Query | Subquery): string;
37
+ /** Any condition other than a bare `NOT` - i.e. one that carries an operator and either a `field` or an `fn`. */
9
38
  export type NonNegationCondition = Exclude<ConditionWithValueQuery, NegationCondition>;
39
+ /** A condition that is rendered as `<lhs> <operator> <value>` - excludes `NOT` and subquery (`IN (SELECT ...)`) conditions. */
10
40
  export type SimpleCondition = Exclude<ConditionWithValueQuery, NegationCondition | ValueQueryCondition>;
41
+ /**
42
+ * Renders the left-hand side of a condition, including the operator, e.g. `Name LIKE`, `COUNT(Id) >`
43
+ */
11
44
  export declare function renderConditionLhs(condition: NonNegationCondition): string;
45
+ /**
46
+ * Renders the value of a (non-subquery) condition, e.g. `'foo'`, `('a', 'b')`, `TRUE`, `LAST_N_DAYS:7`
47
+ */
12
48
  export declare function renderConditionValue(condition: SimpleCondition): string;
49
+ /** e.g. `Name`, `COUNT(Id)` */
13
50
  export declare function renderGroupByItem(groupBy: GroupByClause): string;
51
+ /** e.g. `Name ASC NULLS LAST`, `COUNT(Id) DESC` */
14
52
  export declare function renderOrderByItem(orderBy: OrderByClause): string;
53
+ /** e.g. `Geography__c AT (usa__c, uk__c) AND Product__c ABOVE mobile_phones__c` */
15
54
  export declare function renderWithDataCategory(withDataCategory: WithDataCategoryClause): string;
55
+ /** True if the query has a GROUP BY clause that should be rendered (a non-empty array or a single clause) */
16
56
  export declare function hasGroupBy(query: Query | Subquery): boolean;
57
+ /** True if the query has an ORDER BY clause that should be rendered (a non-empty array or a single clause) */
17
58
  export declare function hasOrderBy(query: Query | Subquery): boolean;
59
+ /** Wraps a single clause or array of clauses in an array */
18
60
  export declare function asArray<T>(value: T | T[]): T[];
61
+ /**
62
+ * One clause of a query, tagged by how it is laid out. The SELECT fields are passed through unrendered
63
+ * because subquery fields have to be rendered by the caller.
64
+ */
19
65
  export type ClausePart = {
20
66
  kind: 'select';
21
67
  fields: FieldType[];
@@ -35,4 +81,11 @@ export type ClausePart = {
35
81
  keyword: string;
36
82
  clause: WhereClause | HavingClause;
37
83
  };
84
+ /**
85
+ * Yields the clauses of a query in the order SOQL requires, skipping any that are absent or empty.
86
+ *
87
+ * This is the single source of truth for clause ordering and presence - both `composePlain()` and
88
+ * `Formatter.query()` walk this sequence and only decide how each part is laid out. Adding support for a
89
+ * new clause means adding it here once, not in each renderer.
90
+ */
38
91
  export declare function queryClauses(query: Query | Subquery): Generator<ClausePart>;
@@ -1,3 +1,15 @@
1
1
  import { HavingClause, Query, Subquery, WhereClause } from '../api/api-models';
2
+ /**
3
+ * Composes a query (or subquery) to a single-line SOQL string without any formatting.
4
+ * This is the `format: false` path of `composeQuery()`.
5
+ * @param query
6
+ * @returns query
7
+ */
2
8
  export declare function composePlain(query: Query | Subquery): string;
9
+ /**
10
+ * Composes a WHERE or HAVING clause (without the keyword) to a single-line string without any formatting.
11
+ * e.x.: `Name LIKE 'a%' AND (Id IN (SELECT AccountId FROM Contact) OR NOT Foo = 'bar')`
12
+ * @param whereOrHaving
13
+ * @returns where or having clause
14
+ */
3
15
  export declare function composePlainConditions(whereOrHaving: WhereClause | HavingClause): string;