@jetstreamapp/soql-parser-js 8.0.0 → 8.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AUTHORS.md CHANGED
@@ -1 +1 @@
1
- * Austin Turner @paustint
1
+ - Austin Turner @paustint
package/CHANGELOG.md CHANGED
@@ -4,6 +4,133 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [8.1.1] - 2026-09-26
8
+
9
+ ### Changed
10
+
11
+ - **Upgraded dependencies** — Vitest 5 (with `@vitest/coverage-v8` 5), oxfmt 0.70, oxlint 1.85,
12
+ `@types/node` 26 and the latest release-it, `@release-it/keep-a-changelog` and tsx, plus React
13
+ 19.3 and `docusaurus-plugin-llms` 0.6 in the docs site, which also moves onto the published 8.1.0
14
+ of the library. No changes to the published library. oxlint 1.85 reports default-importing a
15
+ module whose default export is also a named export (`import(no-named-as-default)`), so four test
16
+ files now import `testCases` by name. Both lockfiles moved to lockfile v3 and had their transitive
17
+ dependencies refreshed, clearing 9 of the docs site's `npm audit` findings; the remaining 24 come
18
+ from versions pinned by Docusaurus and `docusaurus-plugin-llms` themselves. The plugin upgrade also
19
+ nests each page's headings under that page's title in `llms-full.txt`
20
+ - **The docs site's `npm run typecheck` passes again.** It had stopped at TS5102 since the move to
21
+ TypeScript 7, which removed the `baseUrl` that `@docusaurus/tsconfig` still sets, and that hid the
22
+ errors behind it: React 19 dropped the global `JSX` namespace, so components now return
23
+ `React.JSX.Element`, and the playground narrows a caught parse error before reading its message
24
+
25
+ ## [8.1.0] - 2026-09-05
26
+
27
+ ### Added
28
+
29
+ - **Added SOQL `FORMULA()` support in `WHERE` clauses** — arithmetic expressions containing
30
+ two field references joined by `+` or `-` are parsed into a typed nested AST, validated against
31
+ the supported grammar, and reconstructed by both the composer and formatter. `FORMULA()` is
32
+ rejected in unsupported clauses and remains dependency-free. An `isFormulaFunction()` type guard
33
+ narrows a condition's `fn` to `FormulaFunctionExp`, and composing a malformed formula AST throws
34
+ rather than emitting invalid SOQL.
35
+
36
+ ### Changed
37
+
38
+ - **Replaced Prettier with [oxfmt](https://oxc.rs/docs/guide/usage/formatter.html) and added
39
+ [oxlint](https://oxc.rs/docs/guide/usage/linter.html) as the project linter** — the repository had
40
+ no linter at all. Config moved from `.prettierrc` to `.oxfmtrc.json` (every option carried over
41
+ except the no-op `insertPragma`), with `.oxlintrc.json` alongside it and `npm run format`,
42
+ `format:check`, `lint` and `lint:fix`. oxlint runs the `correctness`, `suspicious` and `perf`
43
+ categories as errors; `style` and `pedantic` stay off because on a hand-written recursive-descent
44
+ parser they ask for the code to be restructured — function length, inline comments, negated
45
+ conditions — rather than pointing at defects. Individually disabled rules each carry their reason
46
+ inline, including two genuine false positives: `no-unmodified-loop-condition` does not see that
47
+ the parser's paren-matching loops mutate `parenCount.right`, and `no-await-in-loop` flags polling
48
+ loops whose iterations are sequential by design. The repository was reformatted in the process,
49
+ and the result is byte identical to what Prettier produced for the files it flagged
50
+ - **The `pre-commit` hook blocks a commit when staged files are unformatted or fail lint**, running
51
+ both checks so one attempt reports everything to fix. `npm install` wires it up by pointing
52
+ `core.hooksPath` at `.githooks/`
53
+ - **CI now gates on `format:check`, `lint` and `typecheck`** alongside the tests and build, since the
54
+ hook can be bypassed with `--no-verify`. CI installs with `npm ci` rather than `npm install`, and
55
+ runs on pushes to `main` and on pull requests instead of on every push
56
+ - **A `Changelog` workflow requires an `[Unreleased]` entry on pull requests that touch published
57
+ code.** That section decides the version, so a change nobody wrote down was previously only
58
+ noticed at release time, after the bump had been derived. It fails when `CHANGELOG.md` is
59
+ untouched, then runs `scripts/derive-increment.mjs` so a file edited without a real entry fails
60
+ too. The `skip-changelog` label opts out
61
+ - **The release version is derived from the changelog headings alone.** `scripts/derive-increment.mjs`
62
+ maps `Breaking Changes` to a major, `Added`/`Deprecated` to a minor and
63
+ `Changed`/`Removed`/`Fixed`/`Security` to a patch. Only headings are read, never the entry text —
64
+ scanning the body for a word like "BREAKING" fires on ordinary prose, and an entry that merely
65
+ mentions a breaking change would silently turn a patch into a major. An unrecognized heading is an
66
+ error rather than a guess, so an unclassified change cannot ship as a patch. `npm run release`
67
+ starts a release from the terminal, verifying that `main` is clean and matches origin, printing the
68
+ plan for confirmation, then dispatching the workflow and tailing the run. The release still runs
69
+ entirely in CI, which holds the publish credentials; `release-it` moved behind `npm run release:ci`
70
+ - **The release workflow now matches the one in the Jetstream monorepo.** It authenticates with
71
+ `client-id` rather than `app-id`, which the action marks deprecated. Release commits are no longer
72
+ authored by `Release Workflow <support@getjetstream.app>`, which is not an account GitHub can
73
+ resolve: the identity is derived from the token, with `app-slug` naming the committer and the App's
74
+ numeric user id forming the `<id>+<slug>[bot]@users.noreply.github.com` address that links commits
75
+ back to the App, so they carry the bot's avatar. Every action is pinned to a commit SHA with the
76
+ version in a trailing comment, because a tag can be repointed at new code and a SHA cannot
77
+ - **Tooling is now shared with [sf-formula-parser](https://github.com/jetstreamapp/sf-formula-parser)** —
78
+ `scripts/derive-increment.mjs`, `scripts/release.mjs`, `.githooks/pre-commit` and the `ci`,
79
+ `release` and `changelog` workflows are identical in both repositories, as are `.oxfmtrc.json` and
80
+ `.claude/settings.json`. `tasks/` was renamed to `scripts/` to match, and `CLAUDE.md` became
81
+ `AGENTS.md`, which records the formatter and linter workflow, the release rules, and the two
82
+ constraints that are not obvious from the code: `"type": "module"` must not be added to the root
83
+ package.json, and `docs/` is a separate npm project. `npm test` is now `vitest run` rather than
84
+ bare `vitest`, which started a watch session; `test:watch` ran `jest --watch` long after jest
85
+ stopped being a dependency; `test:coverage` was added along with `@vitest/coverage-v8` so it runs
86
+ without prompting for a provider; and the `--testTimeout 10000` that lived in the test script moved
87
+ into `vitest.config.mts`
88
+ - **Upgraded dependencies** — TypeScript 7 in both the library and the docs site, plus the latest
89
+ esbuild, release-it and tsx. `npm-run-all` and `lodash.get` were dropped: the build chains its
90
+ steps with `&&`, and the single test that used `lodash.get` now resolves the dot separated path
91
+ locally. `vitest.config.ts` became `vitest.config.mts`, since it is ESM while the root package is
92
+ CommonJS, which Vite warned about under its upcoming native config loader
93
+ - **Enabled `isolatedDeclarations` and raised the TypeScript target to ES2022.** The target only
94
+ affects the emitted declarations, and esbuild was already producing es2020/es2022 bundles, so
95
+ nothing about the shipped JavaScript changes. Two exported functions in `src/utils.ts` needed
96
+ explicit return types. `npm run typecheck` covers tests, scripts and the cli via
97
+ `tsconfig.typecheck.json`, which the build's declaration-only `tsconfig.json` excludes
98
+ - **Removed `.npmignore`** — `package.json` `files` takes precedence over it, so it had no effect:
99
+ `npm pack --dry-run` produces a byte identical 21 file tarball without it. It had also drifted,
100
+ listing `CHANGELOG.md` and `AUTHORS.md` as excluded while `files` ships both. `files` is an
101
+ allowlist, which is the safer default — a new top-level directory is excluded unless it is named,
102
+ where a denylist would have published it
103
+ - **Documentation** — the playground's parse, compose and utility function output, and the install
104
+ command on the home page, now reveal a copy to clipboard button on hover, matching the one
105
+ Docusaurus already renders on markdown code blocks. The site publishes `llms.txt` and
106
+ `llms-full.txt` via `docusaurus-plugin-llms`, with links in the footer
107
+
108
+ ### Fixed
109
+
110
+ - **Doc comments are no longer stripped from the published type declarations** — `tsconfig.json` set
111
+ `removeComments`, so every JSDoc block was dropped from `dist/types` and editors showed no
112
+ documentation on hover for any exported symbol. Removing it restores them for 12 KB of declaration
113
+ output, and leaves the JavaScript bundles untouched since esbuild builds those
114
+ - **Corrected the dependency note in the README** — it still described `commander`, `chevrotain` and
115
+ `lodash.get` as dependencies of the library. Those were removed in 8.0.0; the package has no
116
+ runtime dependencies
117
+ - **Corrected the Node compatibility claim in the README** — it advertised Node 11 or higher with an
118
+ [Array.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)
119
+ polyfill, which stopped being true once the parser started using `??` and `?.`. Those are ES2020
120
+ syntax and esbuild's `es2022` target leaves them in the published bundles, so Node 11 cannot run
121
+ them whatever is polyfilled. The stated minimum is now Node 20, the oldest release still in
122
+ maintenance, rather than the bare syntax floor of Node 14 — the library is only ever tested on
123
+ supported releases
124
+ - **`CONTRIBUTING.md` sent contributors to a `master` branch that does not exist** — it asked them to
125
+ branch from and open pull requests against `master`, where the default branch is `main`. The
126
+ contribution guidelines link in the README pointed at the same dead branch
127
+ - **Everything oxlint flagged, with no behavior change to the published library.** A redundant double
128
+ negation, a `? true : false` ternary, an unused local and an unused catch binding were removed;
129
+ `new Array(n).fill(' ').join('')` in `pad()` became `' '.repeat(n)`; and three shadowed variables
130
+ were renamed. In the tests, the performance benchmark had no assertion and now checks that every
131
+ iteration actually parsed, two `toThrow()` calls gained the message matcher their neighbours
132
+ already used, and unused imports were dropped
133
+
7
134
  ## [8.0.0] - 2026-08-16
8
135
 
9
136
  This is a major release. The composed and formatted output changes in the cases listed under Bug Fixes, and the internals of the formatter were rewritten. `composeQuery`, `formatQuery`, `parseQuery` and the `FormatOptions` type are source compatible - see Breaking Changes for the two exceptions.
@@ -1034,6 +1161,8 @@ export interface FunctionExp {
1034
1161
  - `function isSubquery(query: Query | Subquery): query is Subquery`
1035
1162
  - Look at the README and refer to the unit tests for example usage.
1036
1163
 
1037
- [Unreleased]: https://github.com/jetstreamapp/soql-parser-js/compare/8.0.0...HEAD
1164
+ [Unreleased]: https://github.com/jetstreamapp/soql-parser-js/compare/8.1.1...HEAD
1165
+ [8.1.1]: https://github.com/jetstreamapp/soql-parser-js/compare/8.1.0...8.1.1
1166
+ [8.1.0]: https://github.com/jetstreamapp/soql-parser-js/compare/8.0.0...8.1.0
1038
1167
  [8.0.0]: https://github.com/jetstreamapp/soql-parser-js/compare/7.4.1...8.0.0
1039
1168
  [7.4.1]: https://github.com/jetstreamapp/soql-parser-js/compare/7.4.0...7.4.1
package/README.md CHANGED
@@ -32,10 +32,10 @@ Migrating from version 2 to version 3? [Check out the changelog](CHANGELOG.md#30
32
32
 
33
33
  ## Compatibility
34
34
 
35
- **Node**: version 11 or higher, or a polyfill for [Array.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)
35
+ **Node**: version 20 or higher
36
36
  **Browser**: Tested in all modern browsers, may not work with older browsers.
37
37
 
38
- The **commander** dependency is only required for the cli, the other two dependencies **chevrotain** and **lodash.get** are bundled with the non-cli code.
38
+ This library has no runtime dependencies - the parser, composer, formatter and cli are all self contained.
39
39
 
40
40
  ## Quick Start
41
41
 
@@ -52,6 +52,42 @@ isQueryValid('SELECT Id, Foo FROM Baz'); // true
52
52
  isQueryValid('SELECT Id Foo FROM Baz'); // false
53
53
  ```
54
54
 
55
+ ### `FORMULA()` in `WHERE`
56
+
57
+ The parser supports Salesforce's arithmetic [`FORMULA()` WHERE function](https://developer.salesforce.com/docs/atlas.en-us.264.0.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_formula.htm).
58
+ The quoted expression must contain two field references separated by `+` or `-`; `FORMULA()` is not
59
+ accepted in `SELECT`, `HAVING`, `GROUP BY`, or `ORDER BY`. Only comparison operators may follow it,
60
+ and Apex bind variables are rejected because Salesforce does not support them after `FORMULA()`.
61
+ Salesforce ships this function as a Beta feature as of Summer '26.
62
+
63
+ ```typescript
64
+ const query = parseQuery("SELECT Id FROM Opportunity WHERE FORMULA('Amount - ExpectedRevenue') > 100");
65
+
66
+ console.log(query.where?.left);
67
+ // {
68
+ // fn: {
69
+ // functionName: 'FORMULA',
70
+ // parameters: ["'Amount - ExpectedRevenue'"],
71
+ // rawValue: "FORMULA('Amount - ExpectedRevenue')",
72
+ // formula: {
73
+ // type: 'BinaryExpression',
74
+ // operator: '-',
75
+ // left: { type: 'FieldReference', parts: ['Amount'] },
76
+ // right: { type: 'FieldReference', parts: ['ExpectedRevenue'] },
77
+ // },
78
+ // },
79
+ // operator: '>',
80
+ // value: '100',
81
+ // literalType: 'INTEGER',
82
+ // }
83
+ ```
84
+
85
+ The nested formula AST is also accepted by `composeQuery()`. When `formula` is present, `FORMULA()`
86
+ is rebuilt from that AST and `rawValue` is ignored; a `FORMULA` function without `formula` composes
87
+ from `rawValue` like any other function. `parameters` holds the normalized expression and `rawValue`
88
+ keeps the original text. The parser validates the expression's shape, but it cannot validate
89
+ metadata-dependent Salesforce rules such as field data types or type compatibility.
90
+
55
91
  ## Available Features
56
92
 
57
93
  | Function | Description | Arguments |
@@ -79,6 +115,7 @@ Many of hte utility functions are provided to easily determine the shape of spec
79
115
  | stripComments | Removes comments from a query string without otherwise modifying it. Returns the original string as-is if there are no comments. See [Comments in queries](#comments-in-queries). | soql: `string` |
80
116
  | isSubquery | Returns `true` if the data passed in is a subquery. | query: `Query \| Subquery` |
81
117
  | isFieldSubquery | Returns `true` if the data passed in is a FieldSubquery. | value: `any` |
118
+ | isFormulaFunction | Returns `true` if the value is a `FORMULA()` function that carries a nested `formula` AST. | value: `FunctionExp \| FormulaFunctionExp` |
82
119
  | isWhereClauseWithRightCondition | Returns `true` if the value passed in is a `WhereClause` with an `operator` and `right` property | value: `WhereClause` |
83
120
  | isHavingClauseWithRightCondition | Returns `true` if the value passed in is a `HavingClause` with an `operator` and `right` property | value: `HavingClause` |
84
121
  | isWhereOrHavingClauseWithRightCondition | Returns `true` if the value passed in is a `WhereClause` or `HavingClause` with an `operator` and `right` property | value: `WhereClause \| HavingClause` |
@@ -677,7 +714,7 @@ export default class MyComponent extends LightningElement {
677
714
  }
678
715
  ```
679
716
 
680
- <!-- LWC event bindings must be unquoted (onclick={handleClick}); prettier would add quotes -->
717
+ <!-- LWC event bindings must be unquoted (onclick={handleClick}); the formatter would add quotes. oxfmt honors prettier-ignore in markdown -->
681
718
  <!-- prettier-ignore -->
682
719
  ```html
683
720
  <template>
@@ -870,13 +907,7 @@ export type LiteralType =
870
907
  | 'DATE_N_LITERAL'
871
908
  | 'APEX_BIND_VARIABLE';
872
909
  export type FieldType =
873
- | Field
874
- | FieldWithAlias
875
- | FieldFunctionExpression
876
- | FieldRelationship
877
- | FieldRelationshipWithAlias
878
- | FieldSubquery
879
- | FieldTypeOf;
910
+ Field | FieldWithAlias | FieldFunctionExpression | FieldRelationship | FieldRelationshipWithAlias | FieldSubquery | FieldTypeOf;
880
911
  export type OrderByCriterion = 'ASC' | 'DESC';
881
912
  export type NullsOrder = 'FIRST' | 'LAST';
882
913
  export type GroupByType = 'CUBE' | 'ROLLUP';
@@ -1015,11 +1046,7 @@ export interface WhereClauseWithRightCondition extends WhereClauseWithoutOperato
1015
1046
  }
1016
1047
 
1017
1048
  export type Condition =
1018
- | ValueCondition
1019
- | ValueWithDateLiteralCondition
1020
- | ValueWithDateNLiteralCondition
1021
- | ValueFunctionCondition
1022
- | NegationCondition;
1049
+ ValueCondition | ValueWithDateLiteralCondition | ValueWithDateNLiteralCondition | ValueFunctionCondition | NegationCondition;
1023
1050
 
1024
1051
  export type ConditionWithValueQuery = Condition | ValueQueryCondition;
1025
1052
 
@@ -1057,7 +1084,7 @@ export interface ValueQueryCondition extends OptionalParentheses {
1057
1084
  }
1058
1085
 
1059
1086
  export interface ValueFunctionCondition extends OptionalParentheses {
1060
- fn: FunctionExp;
1087
+ fn: FunctionExp | FormulaFunctionExp; // narrow with isFormulaFunction(); checking functionName alone does not narrow the type
1061
1088
  operator: Operator;
1062
1089
  value: string | string[];
1063
1090
  literalType?: LiteralType | LiteralType[];
@@ -1115,6 +1142,25 @@ export interface FunctionExp {
1115
1142
  isAggregateFn?: boolean; // not used for compose, will be populated if SOQL is parsed
1116
1143
  }
1117
1144
 
1145
+ export type FormulaArithmeticOperator = '+' | '-';
1146
+
1147
+ export interface FormulaFieldReference {
1148
+ type: 'FieldReference';
1149
+ parts: string[];
1150
+ }
1151
+
1152
+ export interface FormulaBinaryExpression {
1153
+ type: 'BinaryExpression';
1154
+ operator: FormulaArithmeticOperator;
1155
+ left: FormulaFieldReference;
1156
+ right: FormulaFieldReference;
1157
+ }
1158
+
1159
+ export interface FormulaFunctionExp extends FunctionExp {
1160
+ functionName: 'FORMULA';
1161
+ formula: FormulaBinaryExpression;
1162
+ }
1163
+
1118
1164
  export interface WithDataCategoryClause {
1119
1165
  conditions: WithDataCategoryCondition[];
1120
1166
  }
@@ -1128,4 +1174,4 @@ export interface WithDataCategoryCondition {
1128
1174
 
1129
1175
  ## Contributing
1130
1176
 
1131
- All contributions are welcome on the project. Please read the [contribution guidelines](https://github.com/jetstreamapp/soql-parser-js/blob/master/CONTRIBUTING.md).
1177
+ All contributions are welcome on the project. Please read the [contribution guidelines](https://github.com/jetstreamapp/soql-parser-js/blob/main/CONTRIBUTING.md).
package/dist/cjs/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * @jetstreamapp/soql-parser-js v8.0.0
2
+ * @jetstreamapp/soql-parser-js v8.1.1
3
3
  * https://github.com/jetstreamapp/soql-parser-js
4
4
  * @license MIT
5
5
  */
6
- "use strict";var J=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var Ve=(e,t)=>{for(var r in t)J(e,r,{get:t[r],enumerable:!0})},je=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of He(t))!Qe.call(e,s)&&s!==r&&J(e,s,{get:()=>t[s],enumerable:!(i=$e(t,s))||i.enumerable});return e};var Xe=e=>je(J({},"__esModule",{value:!0}),e);var ht={};Ve(ht,{Compose:()=>Z,composeQuery:()=>Be,formatQuery:()=>pt,getComments:()=>ye,getComposedField:()=>nt,getField:()=>We,getFlattenedFields:()=>st,hasAlias:()=>v,hasComments:()=>Ie,isFieldSubquery:()=>ce,isGroupByField:()=>G,isGroupByFn:()=>we,isHavingClauseWithRightCondition:()=>ve,isNegationCondition:()=>g,isOrderByField:()=>j,isOrderByFn:()=>Pe,isQueryValid:()=>_e,isString:()=>A,isSubquery:()=>U,isValueCondition:()=>Ue,isValueFunctionCondition:()=>V,isValueQueryCondition:()=>D,isValueWithDateLiteralCondition:()=>Ge,isValueWithDateNLiteralCondition:()=>Me,isWhereClauseWithRightCondition:()=>ke,isWhereOrHavingClauseWithRightCondition:()=>L,parseQuery:()=>k,stripComments:()=>Le});module.exports=Xe(ht);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 F(e){return e>=49&&e<=61}function m(e){return e>=62&&e<=67}function ie(e){return e>=68&&e<=69}function re(e){return e===70}function b(e){return e>=71&&e<=75}function Ne(e){return e>=76&&e<=78}function $(e){return e>=79&&e<=101}function H(e){return e>=102&&e<=122}function Ce(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 ne(e){return e===153||e===154||e===155||e===156}function Re(e){return e>=132&&e<=137}var qe=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 se(e){return e>=65&&e<=90||e>=97&&e<=122}function d(e){return e>=48&&e<=57}function te(e){return se(e)||d(e)||e===95}function B(e){return e===32||e===9||e===10||e===13||e===12}function Te(e){let t=[],r=e.length,i=0;for(;i<r;){let s=e.charCodeAt(i);if(B(s)){for(i++;i<r&&B(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(se(s)){let a=i;for(i++;i<r;){let c=e.charCodeAt(i);if(te(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=ee(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=ee(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=ee(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(Ae(c)){let l=o.substring(3);if(Ke(l)){l.includes(".")?t.push({kind:151,text:o,start:a}):t.push({kind:152,text:o,start:a});continue}}}if(o.length===3&&Ae(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||!te(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=qe.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 ee(e,t,r){let i=e.length,s=t;if(s>=i||!B(e.charCodeAt(s)))return-1;for(;s<i&&B(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(te(E)||E===46)return-1}return o}function Ae(e){for(let t=0;t<e.length;t++)if(!se(e.charCodeAt(t)))return!1;return!0}function Ke(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 ze=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]),ae=class e{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)}static{this.CLAUSE_BOUNDARY_KINDS=new Set([26,21,10,11,16,37,27,28,29,25,160])}isAtClauseBoundary(){let t=this.peek().kind;return e.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(F(t.kind)||m(t.kind)||ie(t.kind)||re(t.kind)||b(t.kind))&&r.kind===138}canBeAlias(){let t=this.peek();return!(!y(t.kind)||ze.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":$(t)?"DATE_LITERAL":H(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(Ce(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&&m(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseAggregateFunction(!1),o=!0):r&&ie(this.peek().kind)&&this.peek().kind===68&&this.peekAt(1).kind===138?(a=this.parseLocationFunction(!1),o=!0):F(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseDateFunction(!1),o=!0):b(this.peek().kind)&&this.peekAt(1).kind===138?(a=this.parseOtherFunction(!1),o=!0):a=this.consumeIdentifier().text;let 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(Re(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($(t.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(H(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(ne(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($(t.kind))return{value:this.advance().text,type:N(t.kind)};if(H(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(F(r.kind))return this.parseDateFunction(t);if(m(r.kind))return this.parseAggregateFunction(t);if(r.kind===68)return this.parseLocationFunction(t);if(re(r.kind))return this.parseFieldsFunction(t);if(b(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(Ne(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&&m(i.kind)&&s.kind===138)return this.parseAggregateFunction(r);if(b(i.kind)&&s.kind===138)return this.parseOtherFunction(r);if(i.kind===157)return this.advance().text;if(ne(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")}:F(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 m(t.kind)&&r.kind===138?i={fn:this.parseAggregateFunction(!1)}:F(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}}};function k(e,t){let r=t||{},i=Te(e),s=new ae(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 _e(e,t){try{return k(e,t),!0}catch{return!1}}function Se(e){return e===32||e===9||e===10||e===13||e===12}function oe(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 ye(e){return oe(e,!1)}function Ie(e){return oe(e,!0).length>0}function Le(e){let t=oe(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&&!Se(a)&&o!==0&&!Se(o)&&(r+=" "),i=s.end}return r+=e.substring(i),r}function A(e){return typeof e=="string"}function Ze(e){return e?e.every(t=>A(t)):!1}function I(e){return Number.isFinite(e)}function C(e){return e==null}function x(e,t,r){return C(e)?"":`${r||""}${e}${t||""}`}function ge(e,t=!1){return Array.isArray(e)?e.length>0?`(${e.join(", ")})`:t?"()":"":t?`(${e||""})`:e||""}function Q(e,t,r=""){return I(e)&&e>0?new Array(e).fill(t).join(r):""}function le(e){return!e.parameters||e.parameters.length===0?[]:Ze(e.parameters)?e.parameters:A(e.parameters[0])?[e.parameters[0]]:le(e.parameters[0])}function Oe(e){if(!e.parameters||e.parameters.length===0)return!1;let t=e.parameters[0];return A(t)?!1:!!t.isAggregateFn}function v(e){return e&&!C(e.alias)}function Fe(e){return A(e.field)&&!Array.isArray(e.relationships)&&!Array.isArray(e.conditions)}function me(e){return!C(e.functionName||e.fn)}function xe(e){return A(e.field)&&Array.isArray(e.relationships)}function De(e){return!C(e.subquery)}function be(e){return A(e.field)&&Array.isArray(e.conditions)}function U(e){return A(e.relationshipName)}function ce(e){return!!e&&!!e.type&&e.type==="FieldSubquery"}function ke(e){return!!e&&!!e.operator&&!!e.right}function ve(e){return!!e&&!!e.operator&&!!e.right}function L(e){return!!e&&!!e.operator&&!!e.right}function Ue(e){return e&&A(e.field)&&A(e.operator)&&!C(e.value)}function Ge(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 Me(e){return e&&A(e.field)&&A(e.operator)&&!C(e.value)&&!C(e.dateLiteralVariable)}function V(e){return e&&!C(e.fn)&&A(e.operator)&&!C(e.value)}function g(e){return e&&I(e.openParen)&&C(e.operator)&&C(e.field)&&C(e.fn)&&C(e.closeParen)}function D(e){return e&&A(e.field)&&A(e.operator)&&!C(e.valueQuery)&&C(e.value)}function j(e){return e&&!C(e.field)}function Pe(e){return e&&!C(e.fn)}function G(e){return e&&!C(e.field)}function we(e){return e&&!C(e.fn)}function Je(e){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(e)}function Ye(e,t,r){if(C(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)=>et(i,t?.[s]));switch(Array.isArray(t)&&(t=t[0]),t){case"STRING":return Array.isArray(e)?e.filter(Boolean).map(i=>ue(i)):ue(e);case"APEX_BIND_VARIABLE":return`:${e}`;default:return e}}function et(e,t){switch(t){case"STRING":return ue(e);case"NULL":return"null";default:return e}}function ue(e){if(A(e)&&e.startsWith("'")&&e.endsWith("'")&&e.length>=2)return e;let t=String(e??"");return`'${rt(t)}'`}var tt=/[nNrRtTbBfF"'\\_%]/,it=/^[0-9a-fA-F]{4}$/;function rt(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&&tt.test(s)?(t+=i+s,r++):s==="u"&&it.test(e.substr(r+2,4))?(t+=e.substr(r,6),r+=5):t+="\\\\"}else i==="'"?t+="\\'":t+=i}return t}function nt(e){return We(e)}function We(e){if(typeof e=="string")return{type:"Field",field:e};if(me(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(xe(e))return{type:"FieldRelationship",field:e.field,relationships:e.relationships,objectPrefix:e.objectPrefix};if(De(e))return{type:"FieldSubquery",subquery:e.subquery};if(be(e))return{type:"FieldTypeof",field:e.field,conditions:e.conditions};if(Fe(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 st(e,t){if(!e)return[];e=ce(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)=>(G(c)&&(u[c.field.toLocaleLowerCase()]=c.field),u),{}));let s=-1,a=(U(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=le(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||Oe(u)||t?(s++,`expr${s}`):c.length>0?c.join("."):u.functionName}case"FieldRelationship":{let c=u.relationships[0].toLowerCase();return v(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 X(e){let t;return e.rawValue?t=e.rawValue:t=`${e.functionName}(${(e.parameters||[]).map(r=>A(r)?r:X(r)).join(", ")})`,e.alias&&(t+=` ${e.alias}`),t}function O(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}(${at(e)})${e.alias?` ${e.alias}`:""}`;case"FieldRelationship":return`${t}${e.relationships.join(".")}.${e.field}${v(e)?` ${e.alias}`:""}`;case"FieldTypeof":return P(e).join(" ");default:return""}}function at(e){return e.parameters?e.parameters.map(t=>A(t)?t:O(t)).join(", "):""}function P(e){return[`TYPEOF ${e.field}`,...e.conditions.map(ot),"END"]}function ot(e){let t=e.fieldList.join(", ");return e.objectType?`${e.type} ${e.objectType} THEN ${t}`:`${e.type} ${t}`}function ut(e){return U(e)?e.relationshipName?`${[...e.sObjectPrefix||[],e.relationshipName].join(".")}${x(e.sObjectAlias,""," ")}`:"":e.sObject?`${e.sObject}${x(e.sObjectAlias,""," ")}`:""}function w(e){return`${V(e)?X(e.fn):e.field} ${e.operator}`}function q(e){return ge(Ye(e.value,e.literalType,e.operator))}function pe(e){return G(e)?e.field:X(e.fn)}function he(e){let t=j(e)?`${x(e.field," ")}`:`${X(e.fn)} `;return t+=`${x(e.order," ")}${x(e.nulls,"","NULLS ")}`,t.trim()}function de(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 lt(e){return!!e.groupBy&&(!Array.isArray(e.groupBy)||e.groupBy.length>0)}function ct(e){return!!e.orderBy&&(!Array.isArray(e.orderBy)||e.orderBy.length>0)}function M(e){return Array.isArray(e)?e:[e]}function*K(e){e.fields&&(yield{kind:"select",fields:e.fields});let t=ut(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:de(e.withDataCategory)}),e.withSecurityEnforced&&(yield{kind:"bare",keyword:"WITH SECURITY_ENFORCED"}),e.withAccessLevel&&(yield{kind:"bare",keyword:`WITH ${e.withAccessLevel}`}),lt(e)&&(yield{kind:"list",keyword:"GROUP BY",items:M(e.groupBy).map(pe)},e.having&&(yield{kind:"conditions",keyword:"HAVING",clause:e.having})),ct(e)&&(yield{kind:"list",keyword:"ORDER BY",items:M(e.orderBy).map(he)}),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 Et(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 Y=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)}},z=class{constructor(t={}){this.options=Et(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 Y;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
+ "use strict";var te=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var Je=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},et=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ze(t))!Ze.call(e,s)&&s!==r&&te(e,s,{get:()=>t[s],enumerable:!(i=Ke(t,s))||i.enumerable});return e};var tt=e=>et(te({},"__esModule",{value:!0}),e);var St={};Je(St,{Compose:()=>ee,composeQuery:()=>qe,formatQuery:()=>_t,getComments:()=>Qe,getComposedField:()=>ht,getField:()=>je,getFlattenedFields:()=>dt,hasAlias:()=>b,hasComments:()=>Ve,isFieldSubquery:()=>ne,isFormulaFunction:()=>Q,isGroupByField:()=>U,isGroupByFn:()=>ke,isHavingClauseWithRightCondition:()=>Oe,isNegationCondition:()=>L,isOrderByField:()=>H,isOrderByFn:()=>be,isQueryValid:()=>Be,isString:()=>d,isSubquery:()=>k,isValueCondition:()=>me,isValueFunctionCondition:()=>B,isValueQueryCondition:()=>m,isValueWithDateLiteralCondition:()=>xe,isValueWithDateNLiteralCondition:()=>De,isWhereClauseWithRightCondition:()=>ge,isWhereOrHavingClauseWithRightCondition:()=>I,parseQuery:()=>M,stripComments:()=>Xe});module.exports=tt(St);function d(e){return typeof e=="string"}function it(e){return e?e.every(t=>d(t)):!1}function S(e){return Number.isFinite(e)}function N(e){return e==null}function O(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 $(e,t,r=""){return S(e)&&e>0?Array.from({length:e},()=>t).join(r):""}function re(e){return!e.parameters||e.parameters.length===0?[]:it(e.parameters)?e.parameters:d(e.parameters[0])?[e.parameters[0]]:re(e.parameters[0])}function _e(e){if(!e.parameters||e.parameters.length===0)return!1;let t=e.parameters[0];return d(t)?!1:!!t.isAggregateFn}function b(e){return e&&!N(e.alias)}function Se(e){return d(e.field)&&!Array.isArray(e.relationships)&&!Array.isArray(e.conditions)}function ye(e){return!N(e.functionName||e.fn)}function Ie(e){return d(e.field)&&Array.isArray(e.relationships)}function Le(e){return!N(e.subquery)}function Fe(e){return d(e.field)&&Array.isArray(e.conditions)}function k(e){return d(e.relationshipName)}function ne(e){return!!e&&!!e.type&&e.type==="FieldSubquery"}function ge(e){return!!e&&!!e.operator&&!!e.right}function Oe(e){return!!e&&!!e.operator&&!!e.right}function I(e){return!!e&&!!e.operator&&!!e.right}function me(e){return e&&d(e.field)&&d(e.operator)&&!N(e.value)}function xe(e){return e&&d(e.field)&&d(e.operator)&&!N(e.value)&&(e.literalType==="DATE_LITERAL"||Array.isArray(e.literalType)&&e.literalType[0]==="DATE_LITERAL")}function De(e){return e&&d(e.field)&&d(e.operator)&&!N(e.value)&&!N(e.dateLiteralVariable)}function B(e){return e&&!N(e.fn)&&d(e.operator)&&!N(e.value)}function L(e){return e&&S(e.openParen)&&N(e.operator)&&N(e.field)&&N(e.fn)&&N(e.closeParen)}function m(e){return e&&d(e.field)&&d(e.operator)&&!N(e.valueQuery)&&N(e.value)}function H(e){return e&&!N(e.field)}function be(e){return e&&!N(e.fn)}function U(e){return e&&!N(e.field)}function ke(e){return e&&!N(e.fn)}function rt(e){return["IN","NOT IN","INCLUDES","EXCLUDES"].includes(e)}function Ue(e,t,r){if(N(t))return e;if(r&&t!=="APEX_BIND_VARIABLE"&&rt(r)&&!Array.isArray(e)&&(e=[e],t=Array.isArray(t)?t:[t]),Array.isArray(t)&&Array.isArray(e))return e.map((i,s)=>nt(i,t?.[s]));switch(Array.isArray(t)&&(t=t[0]),t){case"STRING":return Array.isArray(e)?e.filter(Boolean).map(i=>ie(i)):ie(e);case"APEX_BIND_VARIABLE":return`:${e}`;default:return e}}function nt(e,t){switch(t){case"STRING":return ie(e);case"NULL":return"null";default:return e}}function ie(e){if(d(e)&&e.startsWith("'")&&e.endsWith("'")&&e.length>=2)return e;let t=String(e??"");return`'${at(t)}'`}var st=/[nNrRtTbBfF"'\\_%]/,ot=/^[0-9a-fA-F]{4}$/;function at(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&&st.test(s)?(t+=i+s,r++):s==="u"&&ot.test(e.substr(r+2,4))?(t+=e.substr(r,6),r+=5):t+="\\\\"}else i==="'"?t+="\\'":t+=i}return t}var oe="[A-Za-z][A-Za-z0-9_]*",ve=`${oe}(?:\\.${oe})*`,ut=new RegExp(`^\\s*(${ve})\\s*([+-])\\s*(${ve})\\s*$`),lt=new RegExp(`^${oe}$`);function Q(e){return e?.functionName==="FORMULA"&&!N(e.formula)}function Me(e){return{type:"FieldReference",parts:e.split(".")}}function Pe(e){let t=ut.exec(e);if(t)return{type:"BinaryExpression",operator:t[2],left:Me(t[1]),right:Me(t[3])}}function Ge(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"&&lt.test(t))}function V(e){let t=e?.left?.parts,r=e?.right?.parts,i=e?.operator;if(i!=="+"&&i!=="-"||!Ge(t)||!Ge(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 le(e){return e>=68&&e<=69}function ce(e){return e===70}function v(e){return e>=71&&e<=75}function Ye(e){return e>=77&&e<=79}function j(e){return e>=80&&e<=102}function q(e){return e>=103&&e<=123}function We(e){return e>=124&&e<=132}function y(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 pe(e){return e===154||e===155||e===156||e===157}function Ee(e){return e>=133&&e<=138}var ct=new Map([["AND",0],["AS",1],["ASC",2],["DESC",3],["CUBE",4],["ELSE",5],["EXCLUDES",6],["FALSE",7],["FIRST",8],["FROM",9],["HAVING",11],["IN",12],["INCLUDES",13],["LAST",14],["LIKE",15],["LIMIT",16],["NOT",17],["NULL",18],["NULLS",19],["OR",20],["ROLLUP",22],["SELECT",23],["TRUE",24],["USING",25],["WHERE",26],["WITH",27],["FOR",28],["UPDATE",29],["ABOVE_OR_BELOW",31],["ABOVE",30],["NEW",32],["AT",33],["BELOW",34],["END",36],["OFFSET",37],["REFERENCE",38],["SCOPE",39],["TRACKING",40],["THEN",41],["TYPEOF",42],["VIEW",43],["VIEWSTAT",44],["WHEN",45],["SECURITY_ENFORCED",46],["SYSTEM_MODE",47],["USER_MODE",48],["CALENDAR_MONTH",49],["CALENDAR_QUARTER",50],["CALENDAR_YEAR",51],["DAY_IN_MONTH",52],["DAY_IN_WEEK",53],["DAY_IN_YEAR",54],["DAY_ONLY",55],["FISCAL_MONTH",56],["FISCAL_QUARTER",57],["FISCAL_YEAR",58],["HOUR_IN_DAY",59],["WEEK_IN_MONTH",60],["WEEK_IN_YEAR",61],["AVG",62],["COUNT_DISTINCT",64],["COUNT",63],["MIN",65],["MAX",66],["SUM",67],["DISTANCE",68],["GEOLOCATION",69],["FIELDS",70],["FORMAT",71],["TOLABEL",72],["CONVERTTIMEZONE",73],["CONVERTCURRENCY",74],["GROUPING",75],["FORMULA",76],["ALL",77],["CUSTOM",78],["STANDARD",79],["YESTERDAY",80],["TODAY",81],["TOMORROW",82],["LAST_WEEK",83],["THIS_WEEK",84],["NEXT_WEEK",85],["LAST_MONTH",86],["THIS_MONTH",87],["NEXT_MONTH",88],["LAST_90_DAYS",89],["NEXT_90_DAYS",90],["THIS_QUARTER",91],["LAST_QUARTER",92],["NEXT_QUARTER",93],["THIS_YEAR",94],["LAST_YEAR",95],["NEXT_YEAR",96],["THIS_FISCAL_QUARTER",97],["LAST_FISCAL_QUARTER",98],["NEXT_FISCAL_QUARTER",99],["THIS_FISCAL_YEAR",100],["LAST_FISCAL_YEAR",101],["NEXT_FISCAL_YEAR",102],["NEXT_N_DAYS",103],["LAST_N_DAYS",104],["N_DAYS_AGO",105],["NEXT_N_WEEKS",106],["LAST_N_WEEKS",107],["N_WEEKS_AGO",108],["NEXT_N_MONTHS",109],["LAST_N_MONTHS",110],["N_MONTHS_AGO",111],["NEXT_N_QUARTERS",112],["LAST_N_QUARTERS",113],["N_QUARTERS_AGO",114],["NEXT_N_YEARS",115],["LAST_N_YEARS",116],["N_YEARS_AGO",117],["NEXT_N_FISCAL_QUARTERS",118],["LAST_N_FISCAL_QUARTERS",119],["N_FISCAL_QUARTERS_AGO",120],["NEXT_N_FISCAL_YEARS",121],["LAST_N_FISCAL_YEARS",122],["N_FISCAL_YEARS_AGO",123],["DELEGATED",124],["EVERYTHING",125],["MINEANDMYGROUPS",126],["MINE",127],["MY_TERRITORY",128],["MY_TEAM_TERRITORY",129],["TEAM",130],["ALLPRIVATE",131],["MRU",132]]),f=[];(function(){for(let t of Object.keys(C)){let r=C[t];typeof r=="number"&&(f[r]=t)}f[72]="toLabel",f[73]="convertTimezone",f[74]="convertCurrency",f[158]="StringIdentifier",f[151]="DATE",f[32]="new",f[126]="MineAndMyGroups",f[128]="MyTerritory",f[129]="MyTeamTerritory",f[131]="AllPrivate",f[124]="Delegated",f[125]="Everything",f[127]="Mine",f[130]="Team",f[132]="Mru",f[160]="Identifier",f[133]="EQUAL",f[157]="UNSIGNED_INTEGER",f[156]="SIGNED_INTEGER",f[155]="UNSIGNED_DECIMAL",f[154]="SIGNED_DECIMAL",f[152]="CURRENCY_PREFIXED_DECIMAL",f[153]="CURRENCY_PREFIXED_INTEGER"})();function R(e){return f[e]||C[e]}function he(e){return e>=65&&e<=90||e>=97&&e<=122}function h(e){return e>=48&&e<=57}function ue(e){return he(e)||h(e)||e===95}function X(e){return e===32||e===9||e===10||e===13||e===12}function $e(e){let t=[],r=e.length,i=0;for(;i<r;){let s=e.charCodeAt(i);if(X(s)){for(i++;i<r&&X(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(he(s)){let o=i;for(i++;i<r;){let l=e.charCodeAt(i);if(ue(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=ae(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=ae(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=ae(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(we(l)){let c=a.substring(3);if(pt(c)){c.includes(".")?t.push({kind:152,text:a,start:o}):t.push({kind:153,text:a,start:o});continue}}}if(a.length===3&&we(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||!ue(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=ct.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 ae(e,t,r){let i=e.length,s=t;if(s>=i||!X(e.charCodeAt(s)))return-1;for(;s<i&&X(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(ue(p)||p===46)return-1}return a}function we(e){for(let t=0;t<e.length;t++)if(!he(e.charCodeAt(t)))return!1;return!0}function pt(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 Et=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]),de=class e{tokens;pos=0;config;constructor(t,r){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)}static CLAUSE_BOUNDARY_KINDS=new Set([26,21,10,11,16,37,27,28,29,25,161]);isAtClauseBoundary(){let t=this.peek().kind;return e.CLAUSE_BOUNDARY_KINDS.has(t)||t===140}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 ${C[t.kind]} ("${t.text}") at position ${t.start}`)}checkIdentifier(){return y(this.peek().kind)}isFunctionCall(){let t=this.peek(),r=this.peekAt(1);return(x(t.kind)||D(t.kind)||le(t.kind)||ce(t.kind)||v(t.kind))&&r.kind===139}canBeAlias(){let t=this.peek();return!(!y(t.kind)||Et.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":j(t)?"DATE_LITERAL":q(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(We(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("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&&le(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):v(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 _=this.parseArrayExpression();c=_.values,E=_.literalType,A=_.dateLiteralVariable}else{let _=this.parseAtomicValue();c=_.value,E=_.literalType,A=_.dateLiteralVariable}let g=0;for(;this.check(140)&&(!r||r.left>r.right);)this.advance(),g++,r&&r.right++;let T={};return a?T.fn=o:T.field=o,T.operator=u,E==="SUBQUERY"?T.valueQuery=c:T.value=c,T.literalType=E,A!==void 0&&(T.dateLiteralVariable=A),i>0&&(T.openParen=i),g>0&&(T.closeParen=g),T}isSubqueryStart(){return this.check(139)&&this.peekAt(1).kind===23}isArrayExpressionStart(){return!1}parseOperator(){let t=this.peek();if(Ee(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(j(t.kind))return{value:this.advance().text,literalType:"DATE_LITERAL"};if(q(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(pe(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(j(t.kind))return{value:this.advance().text,type:R(t.kind)};if(q(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(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(142),`[${r}]`}parseFormulaFunction(){let t=this.expect(76);this.expect(139);let r=this.expect(158);this.expect(140);let i=Pe(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(!Ee(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:[`'${V(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(ce(r.kind))return this.parseFieldsFunction(t);if(v(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(Ye(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(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(v(i.kind)&&s.kind===139)return this.parseOtherFunction(r);if(i.kind===158)return this.advance().text;if(pe(i.kind))return this.advance().text;if(y(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}}};function M(e,t){let r=t||{},i=$e(e),s=new de(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 Be(e,t){try{return M(e,t),!0}catch{return!1}}function He(e){return e===32||e===9||e===10||e===13||e===12}function fe(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 Qe(e){return fe(e,!1)}function Ve(e){return fe(e,!0).length>0}function Xe(e){let t=fe(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&&!He(o)&&a!==0&&!He(a)&&(r+=" "),i=s.end}return r+=e.substring(i),r}function ht(e){return je(e)}function je(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 dt(e,t){if(!e)return[];e=ne(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)=>(U(l)&&(u[l.field.toLocaleLowerCase()]=l.field),u),{}));let s=-1,o=(k(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=re(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 b(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=>d(u))}function K(e){if(Q(e))return`FORMULA('${V(e.formula)}')`;let t;return e.rawValue?t=e.rawValue:t=`${e.functionName}(${(e.parameters||[]).map(r=>d(r)?r:K(r)).join(", ")})`,e.alias&&(t+=` ${e.alias}`),t}function F(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}(${ft(e)})${e.alias?` ${e.alias}`:""}`;case"FieldRelationship":return`${t}${e.relationships.join(".")}.${e.field}${b(e)?` ${e.alias}`:""}`;case"FieldTypeof":return P(e).join(" ");default:return""}}function ft(e){return e.parameters?e.parameters.map(t=>d(t)?t:F(t)).join(", "):""}function P(e){return[`TYPEOF ${e.field}`,...e.conditions.map(At),"END"]}function At(e){let t=e.fieldList.join(", ");return e.objectType?`${e.type} ${e.objectType} THEN ${t}`:`${e.type} ${t}`}function Nt(e){return k(e)?e.relationshipName?`${[...e.sObjectPrefix||[],e.relationshipName].join(".")}${O(e.sObjectAlias,""," ")}`:"":e.sObject?`${e.sObject}${O(e.sObjectAlias,""," ")}`:""}function w(e){return`${B(e)?K(e.fn):e.field} ${e.operator}`}function z(e){return Te(Ue(e.value,e.literalType,e.operator))}function Ae(e){return U(e)?e.field:K(e.fn)}function Ne(e){let t=H(e)?`${O(e.field," ")}`:`${K(e.fn)} `;return t+=`${O(e.order," ")}${O(e.nulls,"","NULLS ")}`,t.trim()}function Re(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 Rt(e){return!!e.groupBy&&(!Array.isArray(e.groupBy)||e.groupBy.length>0)}function Ct(e){return!!e.orderBy&&(!Array.isArray(e.orderBy)||e.orderBy.length>0)}function G(e){return Array.isArray(e)?e:[e]}function*Z(e){e.fields&&(yield{kind:"select",fields:e.fields});let t=Nt(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:Re(e.withDataCategory)}),e.withSecurityEnforced&&(yield{kind:"bare",keyword:"WITH SECURITY_ENFORCED"}),e.withAccessLevel&&(yield{kind:"bare",keyword:`WITH ${e.withAccessLevel}`}),Rt(e)&&(yield{kind:"list",keyword:"GROUP BY",items:G(e.groupBy).map(Ae)},e.having&&(yield{kind:"conditions",keyword:"HAVING",clause:e.having})),Ct(e)&&(yield{kind:"list",keyword:"ORDER BY",items:G(e.orderBy).map(Ne)}),S(e.limit)&&(yield{kind:"value",keyword:"LIMIT",value:`${e.limit}`}),S(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 Tt(e={}){let t=e.newLineAfterKeywords??!1;return{numIndent:S(e.numIndent)&&e.numIndent>=1?Math.floor(e.numIndent):1,indentString:d(e.indentString)&&/^[ \t]*$/.test(e.indentString)?e.indentString:" ",fieldMaxLineLength:S(e.fieldMaxLineLength)?e.fieldMaxLineLength:60,fieldSubqueryParensOnOwnLine:t||(e.fieldSubqueryParensOnOwnLine??!0),newLineAfterKeywords:t}}var Y=class{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)}},J=class{options;constructor(t={}){this.options=Tt(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 Y;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 Y;for(let s of K(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=O(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,`${P(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 Y,s=[],a=()=>r+s.length+1,o=t;for(;o;){let E=o.left,u=L(o)?o.right:void 0;if(g(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,")")}}L(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&&!g(r)&&!r.openParen&&(r.closeParen||0)>0}condition(t,r,i){if(D(r))if(t.append(i,`${w(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,`${w(r)} ${q(r)}`)}};function W(e){let t=[];for(let r of K(e))switch(r.kind){case"select":{let i=r.fields.map(s=>s.type==="FieldSubquery"?`(${W(s.subquery)})`:O(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} ${fe(r.clause)}`);break}return t.join(" ").trim()}function fe(e){let t="",r=e;for(;r;){let i=r.left;g(i)?t+=Q(i.openParen,"("):i&&(t+=Q(i.openParen??0,"("),t+=`${w(i)} `,t+=D(i)?`(${W(i.valueQuery)})`:q(i),t+=Q(i.closeParen??0,")")),L(r)?(t+=r.operator==="NOT"?"NOT ":` ${r.operator} `,r=r.right):r=void 0}return t}function pt(e,t,r){return Be(k(e,r),{format:!0,formatOptions:t})}function Be(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 Z(e,t).query;return t.logging&&console.timeEnd("composer"),r}var Z=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 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):W(t);return this.log(r),r}parseFields(t){return t.map(r=>r.type==="FieldSubquery"?{text:this.format?this.formatter.formatSubqueryField(r.subquery):`(${W(r.subquery)})`}:{text:O(r),typeOfClause:r.type==="FieldTypeof"?this.parseTypeOfField(r):void 0})}parseTypeOfField(t){return P(t)}parseWhereOrHavingClause(t,r=0){return this.format?this.formatter.formatWhereOrHavingClause(t,r):fe(t)}parseGroupByClause(t){let r=M(t).map(pe);return this.format?this.formatter.formatList(r):r.join(", ")}parseOrderBy(t){let r=M(t).map(he);return this.format?this.formatter.formatList(r):r.join(", ")}parseWithDataCategory(t){return de(t)}};
8
+ `)}indent(t){return this.options.indentString.repeat(this.options.numIndent*Math.max(t,0))}query(t,r){let i=new Y;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,g=A?"":",";if(c.type==="FieldSubquery")l(!0),o.reset(),this.selectSubquery(t,c.subquery,i+1,g),p=!0;else if(c.type==="FieldTypeof")l(!0),o.reset(),this.typeOfField(t,c,i+1,g),p=!0;else{let T=F(c);(o.startsNewRow(T,A)||p)&&(l(!0),p=!1),a.push(T)}}),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,`${P(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 Y,s=[],o=()=>r+s.length+1,a=t;for(;a;){let p=a.left,u=I(a)?a.right:void 0;if(L(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,")")}}I(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&&!L(r)&&!r.openParen&&(r.closeParen||0)>0}condition(t,r,i){if(m(r))if(t.append(i,`${w(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,`${w(r)} ${z(r)}`)}};function W(e){let t=[];for(let r of Z(e))switch(r.kind){case"select":{let i=r.fields.map(s=>s.type==="FieldSubquery"?`(${W(s.subquery)})`:F(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} ${Ce(r.clause)}`);break}return t.join(" ").trim()}function Ce(e){let t="",r=e;for(;r;){let i=r.left;L(i)?t+=$(i.openParen,"("):i&&(t+=$(i.openParen??0,"("),t+=`${w(i)} `,t+=m(i)?`(${W(i.valueQuery)})`:z(i),t+=$(i.closeParen??0,")")),I(r)?(t+=r.operator==="NOT"?"NOT ":` ${r.operator} `,r=r.right):r=void 0}return t}function _t(e,t,r){return qe(M(e,r),{format:!0,formatOptions:t})}function qe(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 ee(e,t).query;return t.logging&&console.timeEnd("composer"),r}var ee=class{constructor(t,r={}){this.soql=t;r={autoCompose:!0,...r};let{logging:i,format:s}=r;this.logging=!!i,this.format=!!s,this.query="",this.formatter=new J(r.formatOptions),r.autoCompose&&this.start()}soql;logging=!1;format=!1;query;formatter;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):W(t);return this.log(r),r}parseFields(t){return t.map(r=>r.type==="FieldSubquery"?{text:this.format?this.formatter.formatSubqueryField(r.subquery):`(${W(r.subquery)})`}:{text:F(r),typeOfClause:r.type==="FieldTypeof"?this.parseTypeOfField(r):void 0})}parseTypeOfField(t){return P(t)}parseWhereOrHavingClause(t,r=0){return this.format?this.formatter.formatWhereOrHavingClause(t,r):Ce(t)}parseGroupByClause(t){let r=G(t).map(Ae);return this.format?this.formatter.formatList(r):r.join(", ")}parseOrderBy(t){let r=G(t).map(Ne);return this.format?this.formatter.formatList(r):r.join(", ")}parseWithDataCategory(t){return Re(t)}};