@vuu-ui/vuu-filters 0.8.4 → 0.8.5-debug

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/cjs/index.js CHANGED
@@ -1,34 +1,4440 @@
1
- "use strict";var Br=Object.create;var De=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Vr=Object.getPrototypeOf,Lr=Object.prototype.hasOwnProperty;var _r=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Ur=(o,e)=>{for(var t in e)De(o,t,{get:e[t],enumerable:!0})},kt=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Qr(e))!Lr.call(o,n)&&n!==t&&De(o,n,{get:()=>e[n],enumerable:!(r=zr(e,n))||r.enumerable});return o};var Pt=(o,e,t)=>(t=o!=null?Br(Vr(o)):{},kt(e||!o||!o.__esModule?De(t,"default",{value:o,enumerable:!0}):t,o)),Wr=o=>kt(De({},"__esModule",{value:!0}),o);var Ot=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)};var j=(o,e,t)=>(Ot(o,e,"read from private field"),t?t.call(o):e.get(o)),Ft=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},qe=(o,e,t,r)=>(Ot(o,e,"write to private field"),r?r.call(o,t):e.set(o,t),t);var bt=_r((Qn,$e)=>{(function(){"use strict";var o={}.hasOwnProperty,e="[native code]";function t(){for(var r=[],n=0;n<arguments.length;n++){var i=arguments[n];if(i){var s=typeof i;if(s==="string"||s==="number")r.push(i);else if(Array.isArray(i)){if(i.length){var l=t.apply(null,i);l&&r.push(l)}}else if(s==="object"){if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]")){r.push(i.toString());continue}for(var a in i)o.call(i,a)&&i[a]&&r.push(a)}}}return r.join(" ")}typeof $e<"u"&&$e.exports?(t.default=t,$e.exports=t):typeof define=="function"&&typeof define.amd=="object"&&define.amd?define("classnames",[],function(){return t}):window.classNames=t})()});var zo={};Ur(zo,{AND:()=>D,ColumnFilter:()=>so,ENDS_WITH:()=>Yr,EQUALS:()=>Me,FilterInput:()=>vo,FilterToolbar:()=>Bo,GREATER_THAN:()=>Xr,IN:()=>Mt,LESS_THAN:()=>Zr,OR:()=>Dt,STARTS_WITH:()=>et,addFilter:()=>ve,filterClauses:()=>Bt,filterEquals:()=>Be,filterIncludesColumn:()=>Qt,overrideColName:()=>zt,removeFilter:()=>ro,splitFilterOnColumn:()=>oo,updateFilter:()=>Lt,useCodeMirrorEditor:()=>It,useFilterSuggestionProvider:()=>Eo});module.exports=Wr(zo);var U=require("@heswell/salt-lab"),qt=require("@salt-ds/core");var Ke=require("react/jsx-runtime"),Nt=require("react");function wt(o){var e,t,r="";if(typeof o=="string"||typeof o=="number")r+=o;else if(typeof o=="object")if(Array.isArray(o))for(e=0;e<o.length;e++)o[e]&&(t=wt(o[e]))&&(r&&(r+=" "),r+=t);else for(e in o)o[e]&&(r&&(r+=" "),r+=e);return r}function Tt(){for(var o,e,t=0,r="";t<arguments.length;)(o=arguments[t++])&&(e=wt(o))&&(r&&(r+=" "),r+=e);return r}function At(o,e){e===void 0&&(e={});var t=e.insertAt;if(!(!o||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=o:n.appendChild(document.createTextNode(o))}}var Hr=`/* Style applied to the root element */
2
- .saltIcon {
3
- --icon-color: var(--saltIcon-color, var(--salt-text-secondary-foreground));
4
- --icon-size-multiplier: var(--saltIcon-size-multiplier, 1);
5
- --icon-base-size: var(--salt-size-icon-base, 12px);
6
- /**
7
- * Icon size will be the multiplier (an integer from the size prop) * the base size (set by the theme per density)
8
- * Icons should never be smaller than 12px for readability so we've added a max() to enforce this
9
- */
10
- --icon-size: max(calc(var(--icon-base-size) * var(--icon-size-multiplier)), 12px);
11
- }
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __accessCheck = (obj, member, msg) => {
33
+ if (!member.has(obj))
34
+ throw TypeError("Cannot " + msg);
35
+ };
36
+ var __privateGet = (obj, member, getter) => {
37
+ __accessCheck(obj, member, "read from private field");
38
+ return getter ? getter.call(obj) : member.get(obj);
39
+ };
40
+ var __privateAdd = (obj, member, value) => {
41
+ if (member.has(obj))
42
+ throw TypeError("Cannot add the same private member more than once");
43
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
44
+ };
45
+ var __privateSet = (obj, member, value, setter) => {
46
+ __accessCheck(obj, member, "write to private field");
47
+ setter ? setter.call(obj, value) : member.set(obj, value);
48
+ return value;
49
+ };
12
50
 
13
- .saltIcon {
14
- fill: var(--saltIcon-color, var(--icon-color));
15
- display: inline-block;
16
- margin: var(--saltIcon-margin, 0);
17
- position: relative;
18
- width: var(--icon-size);
19
- height: var(--icon-size);
20
- min-width: var(--icon-size);
21
- min-height: var(--icon-size);
22
- }
51
+ // ../../node_modules/classnames/index.js
52
+ var require_classnames = __commonJS({
53
+ "../../node_modules/classnames/index.js"(exports, module2) {
54
+ (function() {
55
+ "use strict";
56
+ var hasOwn = {}.hasOwnProperty;
57
+ var nativeCodeString = "[native code]";
58
+ function classNames() {
59
+ var classes = [];
60
+ for (var i = 0; i < arguments.length; i++) {
61
+ var arg = arguments[i];
62
+ if (!arg)
63
+ continue;
64
+ var argType = typeof arg;
65
+ if (argType === "string" || argType === "number") {
66
+ classes.push(arg);
67
+ } else if (Array.isArray(arg)) {
68
+ if (arg.length) {
69
+ var inner = classNames.apply(null, arg);
70
+ if (inner) {
71
+ classes.push(inner);
72
+ }
73
+ }
74
+ } else if (argType === "object") {
75
+ if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) {
76
+ classes.push(arg.toString());
77
+ continue;
78
+ }
79
+ for (var key in arg) {
80
+ if (hasOwn.call(arg, key) && arg[key]) {
81
+ classes.push(key);
82
+ }
83
+ }
84
+ }
85
+ }
86
+ return classes.join(" ");
87
+ }
88
+ if (typeof module2 !== "undefined" && module2.exports) {
89
+ classNames.default = classNames;
90
+ module2.exports = classNames;
91
+ } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) {
92
+ define("classnames", [], function() {
93
+ return classNames;
94
+ });
95
+ } else {
96
+ window.classNames = classNames;
97
+ }
98
+ })();
99
+ }
100
+ });
101
+
102
+ // src/index.ts
103
+ var src_exports = {};
104
+ __export(src_exports, {
105
+ AND: () => AND,
106
+ ENDS_WITH: () => ENDS_WITH,
107
+ EQUALS: () => EQUALS,
108
+ FilterInput: () => FilterInput,
109
+ FilterToolbar: () => FilterToolbar,
110
+ GREATER_THAN: () => GREATER_THAN,
111
+ IN: () => IN,
112
+ LESS_THAN: () => LESS_THAN,
113
+ OR: () => OR,
114
+ STARTS_WITH: () => STARTS_WITH,
115
+ addFilter: () => addFilter,
116
+ filterClauses: () => filterClauses,
117
+ filterEquals: () => filterEquals,
118
+ filterIncludesColumn: () => filterIncludesColumn,
119
+ getNumericFilter: () => getNumericFilter,
120
+ getTypeaheadFilter: () => getTypeaheadFilter,
121
+ overrideColName: () => overrideColName,
122
+ removeFilter: () => removeFilter,
123
+ splitFilterOnColumn: () => splitFilterOnColumn,
124
+ updateFilter: () => updateFilter,
125
+ useCodeMirrorEditor: () => useCodeMirrorEditor,
126
+ useFilterSuggestionProvider: () => useFilterSuggestionProvider
127
+ });
128
+ module.exports = __toCommonJS(src_exports);
23
129
 
24
- .saltIcon:hover {
25
- --icon-color: var(--saltIcon-color-hover, var(--salt-text-secondary-foreground));
130
+ // src/filter-input/FilterInput.tsx
131
+ var import_core = require("@salt-ds/core");
132
+
133
+ // src/filter-input/useCodeMirrorEditor.ts
134
+ var import_vuu_codemirror5 = require("@vuu-ui/vuu-codemirror");
135
+
136
+ // ../../node_modules/@lezer/common/dist/index.js
137
+ var DefaultBufferLength = 1024;
138
+ var nextPropID = 0;
139
+ var Range = class {
140
+ constructor(from, to) {
141
+ this.from = from;
142
+ this.to = to;
143
+ }
144
+ };
145
+ var NodeProp = class {
146
+ /// Create a new node prop type.
147
+ constructor(config = {}) {
148
+ this.id = nextPropID++;
149
+ this.perNode = !!config.perNode;
150
+ this.deserialize = config.deserialize || (() => {
151
+ throw new Error("This node type doesn't define a deserialize function");
152
+ });
153
+ }
154
+ /// This is meant to be used with
155
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
156
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
157
+ /// prop values for each node type in the set. Takes a [match
158
+ /// object](#common.NodeType^match) or function that returns undefined
159
+ /// if the node type doesn't get this prop, and the prop's value if
160
+ /// it does.
161
+ add(match) {
162
+ if (this.perNode)
163
+ throw new RangeError("Can't add per-node props to node types");
164
+ if (typeof match != "function")
165
+ match = NodeType.match(match);
166
+ return (type) => {
167
+ let result = match(type);
168
+ return result === void 0 ? null : [this, result];
169
+ };
170
+ }
171
+ };
172
+ NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
173
+ NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
174
+ NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
175
+ NodeProp.contextHash = new NodeProp({ perNode: true });
176
+ NodeProp.lookAhead = new NodeProp({ perNode: true });
177
+ NodeProp.mounted = new NodeProp({ perNode: true });
178
+ var noProps = /* @__PURE__ */ Object.create(null);
179
+ var NodeType = class {
180
+ /// @internal
181
+ constructor(name, props, id, flags = 0) {
182
+ this.name = name;
183
+ this.props = props;
184
+ this.id = id;
185
+ this.flags = flags;
186
+ }
187
+ /// Define a node type.
188
+ static define(spec) {
189
+ let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
190
+ let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
191
+ let type = new NodeType(spec.name || "", props, spec.id, flags);
192
+ if (spec.props)
193
+ for (let src of spec.props) {
194
+ if (!Array.isArray(src))
195
+ src = src(type);
196
+ if (src) {
197
+ if (src[0].perNode)
198
+ throw new RangeError("Can't store a per-node prop on a node type");
199
+ props[src[0].id] = src[1];
200
+ }
201
+ }
202
+ return type;
203
+ }
204
+ /// Retrieves a node prop for this type. Will return `undefined` if
205
+ /// the prop isn't present on this node.
206
+ prop(prop) {
207
+ return this.props[prop.id];
208
+ }
209
+ /// True when this is the top node of a grammar.
210
+ get isTop() {
211
+ return (this.flags & 1) > 0;
212
+ }
213
+ /// True when this node is produced by a skip rule.
214
+ get isSkipped() {
215
+ return (this.flags & 2) > 0;
216
+ }
217
+ /// Indicates whether this is an error node.
218
+ get isError() {
219
+ return (this.flags & 4) > 0;
220
+ }
221
+ /// When true, this node type doesn't correspond to a user-declared
222
+ /// named node, for example because it is used to cache repetition.
223
+ get isAnonymous() {
224
+ return (this.flags & 8) > 0;
225
+ }
226
+ /// Returns true when this node's name or one of its
227
+ /// [groups](#common.NodeProp^group) matches the given string.
228
+ is(name) {
229
+ if (typeof name == "string") {
230
+ if (this.name == name)
231
+ return true;
232
+ let group = this.prop(NodeProp.group);
233
+ return group ? group.indexOf(name) > -1 : false;
234
+ }
235
+ return this.id == name;
236
+ }
237
+ /// Create a function from node types to arbitrary values by
238
+ /// specifying an object whose property names are node or
239
+ /// [group](#common.NodeProp^group) names. Often useful with
240
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
241
+ /// names, separated by spaces, in a single property name to map
242
+ /// multiple node names to a single value.
243
+ static match(map) {
244
+ let direct = /* @__PURE__ */ Object.create(null);
245
+ for (let prop in map)
246
+ for (let name of prop.split(" "))
247
+ direct[name] = map[prop];
248
+ return (node) => {
249
+ for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
250
+ let found = direct[i < 0 ? node.name : groups[i]];
251
+ if (found)
252
+ return found;
253
+ }
254
+ };
255
+ }
256
+ };
257
+ NodeType.none = new NodeType(
258
+ "",
259
+ /* @__PURE__ */ Object.create(null),
260
+ 0,
261
+ 8
262
+ /* NodeFlag.Anonymous */
263
+ );
264
+ var NodeSet = class {
265
+ /// Create a set with the given types. The `id` property of each
266
+ /// type should correspond to its position within the array.
267
+ constructor(types) {
268
+ this.types = types;
269
+ for (let i = 0; i < types.length; i++)
270
+ if (types[i].id != i)
271
+ throw new RangeError("Node type ids should correspond to array positions when creating a node set");
272
+ }
273
+ /// Create a copy of this set with some node properties added. The
274
+ /// arguments to this method can be created with
275
+ /// [`NodeProp.add`](#common.NodeProp.add).
276
+ extend(...props) {
277
+ let newTypes = [];
278
+ for (let type of this.types) {
279
+ let newProps = null;
280
+ for (let source of props) {
281
+ let add = source(type);
282
+ if (add) {
283
+ if (!newProps)
284
+ newProps = Object.assign({}, type.props);
285
+ newProps[add[0].id] = add[1];
286
+ }
287
+ }
288
+ newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
289
+ }
290
+ return new NodeSet(newTypes);
291
+ }
292
+ };
293
+ var CachedNode = /* @__PURE__ */ new WeakMap();
294
+ var CachedInnerNode = /* @__PURE__ */ new WeakMap();
295
+ var IterMode;
296
+ (function(IterMode2) {
297
+ IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
298
+ IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
299
+ IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
300
+ IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
301
+ })(IterMode || (IterMode = {}));
302
+ var Tree = class {
303
+ /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
304
+ constructor(type, children, positions, length, props) {
305
+ this.type = type;
306
+ this.children = children;
307
+ this.positions = positions;
308
+ this.length = length;
309
+ this.props = null;
310
+ if (props && props.length) {
311
+ this.props = /* @__PURE__ */ Object.create(null);
312
+ for (let [prop, value] of props)
313
+ this.props[typeof prop == "number" ? prop : prop.id] = value;
314
+ }
315
+ }
316
+ /// @internal
317
+ toString() {
318
+ let mounted = this.prop(NodeProp.mounted);
319
+ if (mounted && !mounted.overlay)
320
+ return mounted.tree.toString();
321
+ let children = "";
322
+ for (let ch of this.children) {
323
+ let str = ch.toString();
324
+ if (str) {
325
+ if (children)
326
+ children += ",";
327
+ children += str;
328
+ }
329
+ }
330
+ return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
331
+ }
332
+ /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
333
+ /// the tree. Mode can be used to [control](#common.IterMode) which
334
+ /// nodes the cursor visits.
335
+ cursor(mode = 0) {
336
+ return new TreeCursor(this.topNode, mode);
337
+ }
338
+ /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
339
+ /// at the given position and side (see
340
+ /// [`moveTo`](#common.TreeCursor.moveTo).
341
+ cursorAt(pos, side = 0, mode = 0) {
342
+ let scope = CachedNode.get(this) || this.topNode;
343
+ let cursor = new TreeCursor(scope);
344
+ cursor.moveTo(pos, side);
345
+ CachedNode.set(this, cursor._tree);
346
+ return cursor;
347
+ }
348
+ /// Get a [syntax node](#common.SyntaxNode) object for the top of the
349
+ /// tree.
350
+ get topNode() {
351
+ return new TreeNode(this, 0, 0, null);
352
+ }
353
+ /// Get the [syntax node](#common.SyntaxNode) at the given position.
354
+ /// If `side` is -1, this will move into nodes that end at the
355
+ /// position. If 1, it'll move into nodes that start at the
356
+ /// position. With 0, it'll only enter nodes that cover the position
357
+ /// from both sides.
358
+ ///
359
+ /// Note that this will not enter
360
+ /// [overlays](#common.MountedTree.overlay), and you often want
361
+ /// [`resolveInner`](#common.Tree.resolveInner) instead.
362
+ resolve(pos, side = 0) {
363
+ let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
364
+ CachedNode.set(this, node);
365
+ return node;
366
+ }
367
+ /// Like [`resolve`](#common.Tree.resolve), but will enter
368
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
369
+ /// pointing into the innermost overlaid tree at the given position
370
+ /// (with parent links going through all parent structure, including
371
+ /// the host trees).
372
+ resolveInner(pos, side = 0) {
373
+ let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
374
+ CachedInnerNode.set(this, node);
375
+ return node;
376
+ }
377
+ /// Iterate over the tree and its children, calling `enter` for any
378
+ /// node that touches the `from`/`to` region (if given) before
379
+ /// running over such a node's children, and `leave` (if given) when
380
+ /// leaving the node. When `enter` returns `false`, that node will
381
+ /// not have its children iterated over (or `leave` called).
382
+ iterate(spec) {
383
+ let { enter, leave, from = 0, to = this.length } = spec;
384
+ let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
385
+ for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
386
+ let entered = false;
387
+ if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
388
+ if (c.firstChild())
389
+ continue;
390
+ entered = true;
391
+ }
392
+ for (; ; ) {
393
+ if (entered && leave && (anon || !c.type.isAnonymous))
394
+ leave(c);
395
+ if (c.nextSibling())
396
+ break;
397
+ if (!c.parent())
398
+ return;
399
+ entered = true;
400
+ }
401
+ }
402
+ }
403
+ /// Get the value of the given [node prop](#common.NodeProp) for this
404
+ /// node. Works with both per-node and per-type props.
405
+ prop(prop) {
406
+ return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
407
+ }
408
+ /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
409
+ /// format that can be passed to the [`Tree`](#common.Tree)
410
+ /// constructor.
411
+ get propValues() {
412
+ let result = [];
413
+ if (this.props)
414
+ for (let id in this.props)
415
+ result.push([+id, this.props[id]]);
416
+ return result;
417
+ }
418
+ /// Balance the direct children of this tree, producing a copy of
419
+ /// which may have children grouped into subtrees with type
420
+ /// [`NodeType.none`](#common.NodeType^none).
421
+ balance(config = {}) {
422
+ return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
423
+ }
424
+ /// Build a tree from a postfix-ordered buffer of node information,
425
+ /// or a cursor over such a buffer.
426
+ static build(data) {
427
+ return buildTree(data);
428
+ }
429
+ };
430
+ Tree.empty = new Tree(NodeType.none, [], [], 0);
431
+ var FlatBufferCursor = class {
432
+ constructor(buffer, index) {
433
+ this.buffer = buffer;
434
+ this.index = index;
435
+ }
436
+ get id() {
437
+ return this.buffer[this.index - 4];
438
+ }
439
+ get start() {
440
+ return this.buffer[this.index - 3];
441
+ }
442
+ get end() {
443
+ return this.buffer[this.index - 2];
444
+ }
445
+ get size() {
446
+ return this.buffer[this.index - 1];
447
+ }
448
+ get pos() {
449
+ return this.index;
450
+ }
451
+ next() {
452
+ this.index -= 4;
453
+ }
454
+ fork() {
455
+ return new FlatBufferCursor(this.buffer, this.index);
456
+ }
457
+ };
458
+ var TreeBuffer = class {
459
+ /// Create a tree buffer.
460
+ constructor(buffer, length, set) {
461
+ this.buffer = buffer;
462
+ this.length = length;
463
+ this.set = set;
464
+ }
465
+ /// @internal
466
+ get type() {
467
+ return NodeType.none;
468
+ }
469
+ /// @internal
470
+ toString() {
471
+ let result = [];
472
+ for (let index = 0; index < this.buffer.length; ) {
473
+ result.push(this.childString(index));
474
+ index = this.buffer[index + 3];
475
+ }
476
+ return result.join(",");
477
+ }
478
+ /// @internal
479
+ childString(index) {
480
+ let id = this.buffer[index], endIndex = this.buffer[index + 3];
481
+ let type = this.set.types[id], result = type.name;
482
+ if (/\W/.test(result) && !type.isError)
483
+ result = JSON.stringify(result);
484
+ index += 4;
485
+ if (endIndex == index)
486
+ return result;
487
+ let children = [];
488
+ while (index < endIndex) {
489
+ children.push(this.childString(index));
490
+ index = this.buffer[index + 3];
491
+ }
492
+ return result + "(" + children.join(",") + ")";
493
+ }
494
+ /// @internal
495
+ findChild(startIndex, endIndex, dir, pos, side) {
496
+ let { buffer } = this, pick = -1;
497
+ for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
498
+ if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
499
+ pick = i;
500
+ if (dir > 0)
501
+ break;
502
+ }
503
+ }
504
+ return pick;
505
+ }
506
+ /// @internal
507
+ slice(startI, endI, from) {
508
+ let b = this.buffer;
509
+ let copy = new Uint16Array(endI - startI), len = 0;
510
+ for (let i = startI, j = 0; i < endI; ) {
511
+ copy[j++] = b[i++];
512
+ copy[j++] = b[i++] - from;
513
+ let to = copy[j++] = b[i++] - from;
514
+ copy[j++] = b[i++] - startI;
515
+ len = Math.max(len, to);
516
+ }
517
+ return new TreeBuffer(copy, len, this.set);
518
+ }
519
+ };
520
+ function checkSide(side, pos, from, to) {
521
+ switch (side) {
522
+ case -2:
523
+ return from < pos;
524
+ case -1:
525
+ return to >= pos && from < pos;
526
+ case 0:
527
+ return from < pos && to > pos;
528
+ case 1:
529
+ return from <= pos && to > pos;
530
+ case 2:
531
+ return to > pos;
532
+ case 4:
533
+ return true;
534
+ }
535
+ }
536
+ function enterUnfinishedNodesBefore(node, pos) {
537
+ let scan = node.childBefore(pos);
538
+ while (scan) {
539
+ let last = scan.lastChild;
540
+ if (!last || last.to != scan.to)
541
+ break;
542
+ if (last.type.isError && last.from == last.to) {
543
+ node = scan;
544
+ scan = last.prevSibling;
545
+ } else {
546
+ scan = last;
547
+ }
548
+ }
549
+ return node;
550
+ }
551
+ function resolveNode(node, pos, side, overlays) {
552
+ var _a;
553
+ while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
554
+ let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
555
+ if (!parent)
556
+ return node;
557
+ node = parent;
558
+ }
559
+ let mode = overlays ? 0 : IterMode.IgnoreOverlays;
560
+ if (overlays)
561
+ for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
562
+ if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
563
+ node = parent;
564
+ }
565
+ for (; ; ) {
566
+ let inner = node.enter(pos, side, mode);
567
+ if (!inner)
568
+ return node;
569
+ node = inner;
570
+ }
571
+ }
572
+ var TreeNode = class {
573
+ constructor(_tree, from, index, _parent) {
574
+ this._tree = _tree;
575
+ this.from = from;
576
+ this.index = index;
577
+ this._parent = _parent;
578
+ }
579
+ get type() {
580
+ return this._tree.type;
581
+ }
582
+ get name() {
583
+ return this._tree.type.name;
584
+ }
585
+ get to() {
586
+ return this.from + this._tree.length;
587
+ }
588
+ nextChild(i, dir, pos, side, mode = 0) {
589
+ for (let parent = this; ; ) {
590
+ for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
591
+ let next = children[i], start = positions[i] + parent.from;
592
+ if (!checkSide(side, pos, start, start + next.length))
593
+ continue;
594
+ if (next instanceof TreeBuffer) {
595
+ if (mode & IterMode.ExcludeBuffers)
596
+ continue;
597
+ let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
598
+ if (index > -1)
599
+ return new BufferNode(new BufferContext(parent, next, i, start), null, index);
600
+ } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
601
+ let mounted;
602
+ if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
603
+ return new TreeNode(mounted.tree, start, i, parent);
604
+ let inner = new TreeNode(next, start, i, parent);
605
+ return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
606
+ }
607
+ }
608
+ if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
609
+ return null;
610
+ if (parent.index >= 0)
611
+ i = parent.index + dir;
612
+ else
613
+ i = dir < 0 ? -1 : parent._parent._tree.children.length;
614
+ parent = parent._parent;
615
+ if (!parent)
616
+ return null;
617
+ }
618
+ }
619
+ get firstChild() {
620
+ return this.nextChild(
621
+ 0,
622
+ 1,
623
+ 0,
624
+ 4
625
+ /* Side.DontCare */
626
+ );
627
+ }
628
+ get lastChild() {
629
+ return this.nextChild(
630
+ this._tree.children.length - 1,
631
+ -1,
632
+ 0,
633
+ 4
634
+ /* Side.DontCare */
635
+ );
636
+ }
637
+ childAfter(pos) {
638
+ return this.nextChild(
639
+ 0,
640
+ 1,
641
+ pos,
642
+ 2
643
+ /* Side.After */
644
+ );
645
+ }
646
+ childBefore(pos) {
647
+ return this.nextChild(
648
+ this._tree.children.length - 1,
649
+ -1,
650
+ pos,
651
+ -2
652
+ /* Side.Before */
653
+ );
654
+ }
655
+ enter(pos, side, mode = 0) {
656
+ let mounted;
657
+ if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
658
+ let rPos = pos - this.from;
659
+ for (let { from, to } of mounted.overlay) {
660
+ if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
661
+ return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
662
+ }
663
+ }
664
+ return this.nextChild(0, 1, pos, side, mode);
665
+ }
666
+ nextSignificantParent() {
667
+ let val = this;
668
+ while (val.type.isAnonymous && val._parent)
669
+ val = val._parent;
670
+ return val;
671
+ }
672
+ get parent() {
673
+ return this._parent ? this._parent.nextSignificantParent() : null;
674
+ }
675
+ get nextSibling() {
676
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
677
+ this.index + 1,
678
+ 1,
679
+ 0,
680
+ 4
681
+ /* Side.DontCare */
682
+ ) : null;
683
+ }
684
+ get prevSibling() {
685
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
686
+ this.index - 1,
687
+ -1,
688
+ 0,
689
+ 4
690
+ /* Side.DontCare */
691
+ ) : null;
692
+ }
693
+ cursor(mode = 0) {
694
+ return new TreeCursor(this, mode);
695
+ }
696
+ get tree() {
697
+ return this._tree;
698
+ }
699
+ toTree() {
700
+ return this._tree;
701
+ }
702
+ resolve(pos, side = 0) {
703
+ return resolveNode(this, pos, side, false);
704
+ }
705
+ resolveInner(pos, side = 0) {
706
+ return resolveNode(this, pos, side, true);
707
+ }
708
+ enterUnfinishedNodesBefore(pos) {
709
+ return enterUnfinishedNodesBefore(this, pos);
710
+ }
711
+ getChild(type, before = null, after = null) {
712
+ let r = getChildren(this, type, before, after);
713
+ return r.length ? r[0] : null;
714
+ }
715
+ getChildren(type, before = null, after = null) {
716
+ return getChildren(this, type, before, after);
717
+ }
718
+ /// @internal
719
+ toString() {
720
+ return this._tree.toString();
721
+ }
722
+ get node() {
723
+ return this;
724
+ }
725
+ matchContext(context) {
726
+ return matchNodeContext(this, context);
727
+ }
728
+ };
729
+ function getChildren(node, type, before, after) {
730
+ let cur = node.cursor(), result = [];
731
+ if (!cur.firstChild())
732
+ return result;
733
+ if (before != null) {
734
+ while (!cur.type.is(before))
735
+ if (!cur.nextSibling())
736
+ return result;
737
+ }
738
+ for (; ; ) {
739
+ if (after != null && cur.type.is(after))
740
+ return result;
741
+ if (cur.type.is(type))
742
+ result.push(cur.node);
743
+ if (!cur.nextSibling())
744
+ return after == null ? result : [];
745
+ }
746
+ }
747
+ function matchNodeContext(node, context, i = context.length - 1) {
748
+ for (let p = node.parent; i >= 0; p = p.parent) {
749
+ if (!p)
750
+ return false;
751
+ if (!p.type.isAnonymous) {
752
+ if (context[i] && context[i] != p.name)
753
+ return false;
754
+ i--;
755
+ }
756
+ }
757
+ return true;
758
+ }
759
+ var BufferContext = class {
760
+ constructor(parent, buffer, index, start) {
761
+ this.parent = parent;
762
+ this.buffer = buffer;
763
+ this.index = index;
764
+ this.start = start;
765
+ }
766
+ };
767
+ var BufferNode = class {
768
+ get name() {
769
+ return this.type.name;
770
+ }
771
+ get from() {
772
+ return this.context.start + this.context.buffer.buffer[this.index + 1];
773
+ }
774
+ get to() {
775
+ return this.context.start + this.context.buffer.buffer[this.index + 2];
776
+ }
777
+ constructor(context, _parent, index) {
778
+ this.context = context;
779
+ this._parent = _parent;
780
+ this.index = index;
781
+ this.type = context.buffer.set.types[context.buffer.buffer[index]];
782
+ }
783
+ child(dir, pos, side) {
784
+ let { buffer } = this.context;
785
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
786
+ return index < 0 ? null : new BufferNode(this.context, this, index);
787
+ }
788
+ get firstChild() {
789
+ return this.child(
790
+ 1,
791
+ 0,
792
+ 4
793
+ /* Side.DontCare */
794
+ );
795
+ }
796
+ get lastChild() {
797
+ return this.child(
798
+ -1,
799
+ 0,
800
+ 4
801
+ /* Side.DontCare */
802
+ );
803
+ }
804
+ childAfter(pos) {
805
+ return this.child(
806
+ 1,
807
+ pos,
808
+ 2
809
+ /* Side.After */
810
+ );
811
+ }
812
+ childBefore(pos) {
813
+ return this.child(
814
+ -1,
815
+ pos,
816
+ -2
817
+ /* Side.Before */
818
+ );
819
+ }
820
+ enter(pos, side, mode = 0) {
821
+ if (mode & IterMode.ExcludeBuffers)
822
+ return null;
823
+ let { buffer } = this.context;
824
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
825
+ return index < 0 ? null : new BufferNode(this.context, this, index);
826
+ }
827
+ get parent() {
828
+ return this._parent || this.context.parent.nextSignificantParent();
829
+ }
830
+ externalSibling(dir) {
831
+ return this._parent ? null : this.context.parent.nextChild(
832
+ this.context.index + dir,
833
+ dir,
834
+ 0,
835
+ 4
836
+ /* Side.DontCare */
837
+ );
838
+ }
839
+ get nextSibling() {
840
+ let { buffer } = this.context;
841
+ let after = buffer.buffer[this.index + 3];
842
+ if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
843
+ return new BufferNode(this.context, this._parent, after);
844
+ return this.externalSibling(1);
845
+ }
846
+ get prevSibling() {
847
+ let { buffer } = this.context;
848
+ let parentStart = this._parent ? this._parent.index + 4 : 0;
849
+ if (this.index == parentStart)
850
+ return this.externalSibling(-1);
851
+ return new BufferNode(this.context, this._parent, buffer.findChild(
852
+ parentStart,
853
+ this.index,
854
+ -1,
855
+ 0,
856
+ 4
857
+ /* Side.DontCare */
858
+ ));
859
+ }
860
+ cursor(mode = 0) {
861
+ return new TreeCursor(this, mode);
862
+ }
863
+ get tree() {
864
+ return null;
865
+ }
866
+ toTree() {
867
+ let children = [], positions = [];
868
+ let { buffer } = this.context;
869
+ let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
870
+ if (endI > startI) {
871
+ let from = buffer.buffer[this.index + 1];
872
+ children.push(buffer.slice(startI, endI, from));
873
+ positions.push(0);
874
+ }
875
+ return new Tree(this.type, children, positions, this.to - this.from);
876
+ }
877
+ resolve(pos, side = 0) {
878
+ return resolveNode(this, pos, side, false);
879
+ }
880
+ resolveInner(pos, side = 0) {
881
+ return resolveNode(this, pos, side, true);
882
+ }
883
+ enterUnfinishedNodesBefore(pos) {
884
+ return enterUnfinishedNodesBefore(this, pos);
885
+ }
886
+ /// @internal
887
+ toString() {
888
+ return this.context.buffer.childString(this.index);
889
+ }
890
+ getChild(type, before = null, after = null) {
891
+ let r = getChildren(this, type, before, after);
892
+ return r.length ? r[0] : null;
893
+ }
894
+ getChildren(type, before = null, after = null) {
895
+ return getChildren(this, type, before, after);
896
+ }
897
+ get node() {
898
+ return this;
899
+ }
900
+ matchContext(context) {
901
+ return matchNodeContext(this, context);
902
+ }
903
+ };
904
+ var TreeCursor = class {
905
+ /// Shorthand for `.type.name`.
906
+ get name() {
907
+ return this.type.name;
908
+ }
909
+ /// @internal
910
+ constructor(node, mode = 0) {
911
+ this.mode = mode;
912
+ this.buffer = null;
913
+ this.stack = [];
914
+ this.index = 0;
915
+ this.bufferNode = null;
916
+ if (node instanceof TreeNode) {
917
+ this.yieldNode(node);
918
+ } else {
919
+ this._tree = node.context.parent;
920
+ this.buffer = node.context;
921
+ for (let n = node._parent; n; n = n._parent)
922
+ this.stack.unshift(n.index);
923
+ this.bufferNode = node;
924
+ this.yieldBuf(node.index);
925
+ }
926
+ }
927
+ yieldNode(node) {
928
+ if (!node)
929
+ return false;
930
+ this._tree = node;
931
+ this.type = node.type;
932
+ this.from = node.from;
933
+ this.to = node.to;
934
+ return true;
935
+ }
936
+ yieldBuf(index, type) {
937
+ this.index = index;
938
+ let { start, buffer } = this.buffer;
939
+ this.type = type || buffer.set.types[buffer.buffer[index]];
940
+ this.from = start + buffer.buffer[index + 1];
941
+ this.to = start + buffer.buffer[index + 2];
942
+ return true;
943
+ }
944
+ yield(node) {
945
+ if (!node)
946
+ return false;
947
+ if (node instanceof TreeNode) {
948
+ this.buffer = null;
949
+ return this.yieldNode(node);
950
+ }
951
+ this.buffer = node.context;
952
+ return this.yieldBuf(node.index, node.type);
953
+ }
954
+ /// @internal
955
+ toString() {
956
+ return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
957
+ }
958
+ /// @internal
959
+ enterChild(dir, pos, side) {
960
+ if (!this.buffer)
961
+ return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
962
+ let { buffer } = this.buffer;
963
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
964
+ if (index < 0)
965
+ return false;
966
+ this.stack.push(this.index);
967
+ return this.yieldBuf(index);
968
+ }
969
+ /// Move the cursor to this node's first child. When this returns
970
+ /// false, the node has no child, and the cursor has not been moved.
971
+ firstChild() {
972
+ return this.enterChild(
973
+ 1,
974
+ 0,
975
+ 4
976
+ /* Side.DontCare */
977
+ );
978
+ }
979
+ /// Move the cursor to this node's last child.
980
+ lastChild() {
981
+ return this.enterChild(
982
+ -1,
983
+ 0,
984
+ 4
985
+ /* Side.DontCare */
986
+ );
987
+ }
988
+ /// Move the cursor to the first child that ends after `pos`.
989
+ childAfter(pos) {
990
+ return this.enterChild(
991
+ 1,
992
+ pos,
993
+ 2
994
+ /* Side.After */
995
+ );
996
+ }
997
+ /// Move to the last child that starts before `pos`.
998
+ childBefore(pos) {
999
+ return this.enterChild(
1000
+ -1,
1001
+ pos,
1002
+ -2
1003
+ /* Side.Before */
1004
+ );
1005
+ }
1006
+ /// Move the cursor to the child around `pos`. If side is -1 the
1007
+ /// child may end at that position, when 1 it may start there. This
1008
+ /// will also enter [overlaid](#common.MountedTree.overlay)
1009
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
1010
+ /// set to false.
1011
+ enter(pos, side, mode = this.mode) {
1012
+ if (!this.buffer)
1013
+ return this.yield(this._tree.enter(pos, side, mode));
1014
+ return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
1015
+ }
1016
+ /// Move to the node's parent node, if this isn't the top node.
1017
+ parent() {
1018
+ if (!this.buffer)
1019
+ return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
1020
+ if (this.stack.length)
1021
+ return this.yieldBuf(this.stack.pop());
1022
+ let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
1023
+ this.buffer = null;
1024
+ return this.yieldNode(parent);
1025
+ }
1026
+ /// @internal
1027
+ sibling(dir) {
1028
+ if (!this.buffer)
1029
+ return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
1030
+ let { buffer } = this.buffer, d = this.stack.length - 1;
1031
+ if (dir < 0) {
1032
+ let parentStart = d < 0 ? 0 : this.stack[d] + 4;
1033
+ if (this.index != parentStart)
1034
+ return this.yieldBuf(buffer.findChild(
1035
+ parentStart,
1036
+ this.index,
1037
+ -1,
1038
+ 0,
1039
+ 4
1040
+ /* Side.DontCare */
1041
+ ));
1042
+ } else {
1043
+ let after = buffer.buffer[this.index + 3];
1044
+ if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
1045
+ return this.yieldBuf(after);
1046
+ }
1047
+ return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
1048
+ }
1049
+ /// Move to this node's next sibling, if any.
1050
+ nextSibling() {
1051
+ return this.sibling(1);
1052
+ }
1053
+ /// Move to this node's previous sibling, if any.
1054
+ prevSibling() {
1055
+ return this.sibling(-1);
1056
+ }
1057
+ atLastNode(dir) {
1058
+ let index, parent, { buffer } = this;
1059
+ if (buffer) {
1060
+ if (dir > 0) {
1061
+ if (this.index < buffer.buffer.buffer.length)
1062
+ return false;
1063
+ } else {
1064
+ for (let i = 0; i < this.index; i++)
1065
+ if (buffer.buffer.buffer[i + 3] < this.index)
1066
+ return false;
1067
+ }
1068
+ ({ index, parent } = buffer);
1069
+ } else {
1070
+ ({ index, _parent: parent } = this._tree);
1071
+ }
1072
+ for (; parent; { index, _parent: parent } = parent) {
1073
+ if (index > -1)
1074
+ for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
1075
+ let child = parent._tree.children[i];
1076
+ if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
1077
+ return false;
1078
+ }
1079
+ }
1080
+ return true;
1081
+ }
1082
+ move(dir, enter) {
1083
+ if (enter && this.enterChild(
1084
+ dir,
1085
+ 0,
1086
+ 4
1087
+ /* Side.DontCare */
1088
+ ))
1089
+ return true;
1090
+ for (; ; ) {
1091
+ if (this.sibling(dir))
1092
+ return true;
1093
+ if (this.atLastNode(dir) || !this.parent())
1094
+ return false;
1095
+ }
1096
+ }
1097
+ /// Move to the next node in a
1098
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1099
+ /// traversal, going from a node to its first child or, if the
1100
+ /// current node is empty or `enter` is false, its next sibling or
1101
+ /// the next sibling of the first parent node that has one.
1102
+ next(enter = true) {
1103
+ return this.move(1, enter);
1104
+ }
1105
+ /// Move to the next node in a last-to-first pre-order traveral. A
1106
+ /// node is followed by its last child or, if it has none, its
1107
+ /// previous sibling or the previous sibling of the first parent
1108
+ /// node that has one.
1109
+ prev(enter = true) {
1110
+ return this.move(-1, enter);
1111
+ }
1112
+ /// Move the cursor to the innermost node that covers `pos`. If
1113
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1114
+ /// it will enter nodes that start at `pos`.
1115
+ moveTo(pos, side = 0) {
1116
+ while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1117
+ if (!this.parent())
1118
+ break;
1119
+ while (this.enterChild(1, pos, side)) {
1120
+ }
1121
+ return this;
1122
+ }
1123
+ /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
1124
+ /// position.
1125
+ get node() {
1126
+ if (!this.buffer)
1127
+ return this._tree;
1128
+ let cache = this.bufferNode, result = null, depth = 0;
1129
+ if (cache && cache.context == this.buffer) {
1130
+ scan:
1131
+ for (let index = this.index, d = this.stack.length; d >= 0; ) {
1132
+ for (let c = cache; c; c = c._parent)
1133
+ if (c.index == index) {
1134
+ if (index == this.index)
1135
+ return c;
1136
+ result = c;
1137
+ depth = d + 1;
1138
+ break scan;
1139
+ }
1140
+ index = this.stack[--d];
1141
+ }
1142
+ }
1143
+ for (let i = depth; i < this.stack.length; i++)
1144
+ result = new BufferNode(this.buffer, result, this.stack[i]);
1145
+ return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1146
+ }
1147
+ /// Get the [tree](#common.Tree) that represents the current node, if
1148
+ /// any. Will return null when the node is in a [tree
1149
+ /// buffer](#common.TreeBuffer).
1150
+ get tree() {
1151
+ return this.buffer ? null : this._tree._tree;
1152
+ }
1153
+ /// Iterate over the current node and all its descendants, calling
1154
+ /// `enter` when entering a node and `leave`, if given, when leaving
1155
+ /// one. When `enter` returns `false`, any children of that node are
1156
+ /// skipped, and `leave` isn't called for it.
1157
+ iterate(enter, leave) {
1158
+ for (let depth = 0; ; ) {
1159
+ let mustLeave = false;
1160
+ if (this.type.isAnonymous || enter(this) !== false) {
1161
+ if (this.firstChild()) {
1162
+ depth++;
1163
+ continue;
1164
+ }
1165
+ if (!this.type.isAnonymous)
1166
+ mustLeave = true;
1167
+ }
1168
+ for (; ; ) {
1169
+ if (mustLeave && leave)
1170
+ leave(this);
1171
+ mustLeave = this.type.isAnonymous;
1172
+ if (this.nextSibling())
1173
+ break;
1174
+ if (!depth)
1175
+ return;
1176
+ this.parent();
1177
+ depth--;
1178
+ mustLeave = true;
1179
+ }
1180
+ }
1181
+ }
1182
+ /// Test whether the current node matches a given context—a sequence
1183
+ /// of direct parent node names. Empty strings in the context array
1184
+ /// are treated as wildcards.
1185
+ matchContext(context) {
1186
+ if (!this.buffer)
1187
+ return matchNodeContext(this.node, context);
1188
+ let { buffer } = this.buffer, { types } = buffer.set;
1189
+ for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1190
+ if (d < 0)
1191
+ return matchNodeContext(this.node, context, i);
1192
+ let type = types[buffer.buffer[this.stack[d]]];
1193
+ if (!type.isAnonymous) {
1194
+ if (context[i] && context[i] != type.name)
1195
+ return false;
1196
+ i--;
1197
+ }
1198
+ }
1199
+ return true;
1200
+ }
1201
+ };
1202
+ function hasChild(tree) {
1203
+ return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1204
+ }
1205
+ function buildTree(data) {
1206
+ var _a;
1207
+ let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1208
+ let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1209
+ let types = nodeSet.types;
1210
+ let contextHash = 0, lookAhead = 0;
1211
+ function takeNode(parentStart, minPos, children2, positions2, inRepeat) {
1212
+ let { id, start, end, size } = cursor;
1213
+ let lookAheadAtStart = lookAhead;
1214
+ while (size < 0) {
1215
+ cursor.next();
1216
+ if (size == -1) {
1217
+ let node2 = reused[id];
1218
+ children2.push(node2);
1219
+ positions2.push(start - parentStart);
1220
+ return;
1221
+ } else if (size == -3) {
1222
+ contextHash = id;
1223
+ return;
1224
+ } else if (size == -4) {
1225
+ lookAhead = id;
1226
+ return;
1227
+ } else {
1228
+ throw new RangeError(`Unrecognized record size: ${size}`);
1229
+ }
1230
+ }
1231
+ let type = types[id], node, buffer2;
1232
+ let startPos = start - parentStart;
1233
+ if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1234
+ let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1235
+ let endPos = cursor.pos - buffer2.size, index = data2.length;
1236
+ while (cursor.pos > endPos)
1237
+ index = copyToBuffer(buffer2.start, data2, index);
1238
+ node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1239
+ startPos = buffer2.start - parentStart;
1240
+ } else {
1241
+ let endPos = cursor.pos - size;
1242
+ cursor.next();
1243
+ let localChildren = [], localPositions = [];
1244
+ let localInRepeat = id >= minRepeatType ? id : -1;
1245
+ let lastGroup = 0, lastEnd = end;
1246
+ while (cursor.pos > endPos) {
1247
+ if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1248
+ if (cursor.end <= lastEnd - maxBufferLength) {
1249
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1250
+ lastGroup = localChildren.length;
1251
+ lastEnd = cursor.end;
1252
+ }
1253
+ cursor.next();
1254
+ } else {
1255
+ takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1256
+ }
1257
+ }
1258
+ if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1259
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1260
+ localChildren.reverse();
1261
+ localPositions.reverse();
1262
+ if (localInRepeat > -1 && lastGroup > 0) {
1263
+ let make = makeBalanced(type);
1264
+ node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1265
+ } else {
1266
+ node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1267
+ }
1268
+ }
1269
+ children2.push(node);
1270
+ positions2.push(startPos);
1271
+ }
1272
+ function makeBalanced(type) {
1273
+ return (children2, positions2, length2) => {
1274
+ let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1275
+ if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1276
+ if (!lastI && last.type == type && last.length == length2)
1277
+ return last;
1278
+ if (lookAheadProp = last.prop(NodeProp.lookAhead))
1279
+ lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1280
+ }
1281
+ return makeTree(type, children2, positions2, length2, lookAhead2);
1282
+ };
1283
+ }
1284
+ function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2) {
1285
+ let localChildren = [], localPositions = [];
1286
+ while (children2.length > i) {
1287
+ localChildren.push(children2.pop());
1288
+ localPositions.push(positions2.pop() + base - from);
1289
+ }
1290
+ children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
1291
+ positions2.push(from - base);
1292
+ }
1293
+ function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) {
1294
+ if (contextHash) {
1295
+ let pair2 = [NodeProp.contextHash, contextHash];
1296
+ props = props ? [pair2].concat(props) : [pair2];
1297
+ }
1298
+ if (lookAhead2 > 25) {
1299
+ let pair2 = [NodeProp.lookAhead, lookAhead2];
1300
+ props = props ? [pair2].concat(props) : [pair2];
1301
+ }
1302
+ return new Tree(type, children2, positions2, length2, props);
1303
+ }
1304
+ function findBufferSize(maxSize, inRepeat) {
1305
+ let fork = cursor.fork();
1306
+ let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1307
+ let result = { size: 0, start: 0, skip: 0 };
1308
+ scan:
1309
+ for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1310
+ let nodeSize2 = fork.size;
1311
+ if (fork.id == inRepeat && nodeSize2 >= 0) {
1312
+ result.size = size;
1313
+ result.start = start;
1314
+ result.skip = skip;
1315
+ skip += 4;
1316
+ size += 4;
1317
+ fork.next();
1318
+ continue;
1319
+ }
1320
+ let startPos = fork.pos - nodeSize2;
1321
+ if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1322
+ break;
1323
+ let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1324
+ let nodeStart = fork.start;
1325
+ fork.next();
1326
+ while (fork.pos > startPos) {
1327
+ if (fork.size < 0) {
1328
+ if (fork.size == -3)
1329
+ localSkipped += 4;
1330
+ else
1331
+ break scan;
1332
+ } else if (fork.id >= minRepeatType) {
1333
+ localSkipped += 4;
1334
+ }
1335
+ fork.next();
1336
+ }
1337
+ start = nodeStart;
1338
+ size += nodeSize2;
1339
+ skip += localSkipped;
1340
+ }
1341
+ if (inRepeat < 0 || size == maxSize) {
1342
+ result.size = size;
1343
+ result.start = start;
1344
+ result.skip = skip;
1345
+ }
1346
+ return result.size > 4 ? result : void 0;
1347
+ }
1348
+ function copyToBuffer(bufferStart, buffer2, index) {
1349
+ let { id, start, end, size } = cursor;
1350
+ cursor.next();
1351
+ if (size >= 0 && id < minRepeatType) {
1352
+ let startIndex = index;
1353
+ if (size > 4) {
1354
+ let endPos = cursor.pos - (size - 4);
1355
+ while (cursor.pos > endPos)
1356
+ index = copyToBuffer(bufferStart, buffer2, index);
1357
+ }
1358
+ buffer2[--index] = startIndex;
1359
+ buffer2[--index] = end - bufferStart;
1360
+ buffer2[--index] = start - bufferStart;
1361
+ buffer2[--index] = id;
1362
+ } else if (size == -3) {
1363
+ contextHash = id;
1364
+ } else if (size == -4) {
1365
+ lookAhead = id;
1366
+ }
1367
+ return index;
1368
+ }
1369
+ let children = [], positions = [];
1370
+ while (cursor.pos > 0)
1371
+ takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1372
+ let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1373
+ return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
26
1374
  }
1375
+ var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1376
+ function nodeSize(balanceType, node) {
1377
+ if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1378
+ return 1;
1379
+ let size = nodeSizeCache.get(node);
1380
+ if (size == null) {
1381
+ size = 1;
1382
+ for (let child of node.children) {
1383
+ if (child.type != balanceType || !(child instanceof Tree)) {
1384
+ size = 1;
1385
+ break;
1386
+ }
1387
+ size += nodeSize(balanceType, child);
1388
+ }
1389
+ nodeSizeCache.set(node, size);
1390
+ }
1391
+ return size;
1392
+ }
1393
+ function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1394
+ let total = 0;
1395
+ for (let i = from; i < to; i++)
1396
+ total += nodeSize(balanceType, children[i]);
1397
+ let maxChild = Math.ceil(
1398
+ total * 1.5 / 8
1399
+ /* Balance.BranchFactor */
1400
+ );
1401
+ let localChildren = [], localPositions = [];
1402
+ function divide(children2, positions2, from2, to2, offset) {
1403
+ for (let i = from2; i < to2; ) {
1404
+ let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1405
+ i++;
1406
+ for (; i < to2; i++) {
1407
+ let nextSize = nodeSize(balanceType, children2[i]);
1408
+ if (groupSize + nextSize >= maxChild)
1409
+ break;
1410
+ groupSize += nextSize;
1411
+ }
1412
+ if (i == groupFrom + 1) {
1413
+ if (groupSize > maxChild) {
1414
+ let only = children2[groupFrom];
1415
+ divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1416
+ continue;
1417
+ }
1418
+ localChildren.push(children2[groupFrom]);
1419
+ } else {
1420
+ let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1421
+ localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1422
+ }
1423
+ localPositions.push(groupStart + offset - start);
1424
+ }
1425
+ }
1426
+ divide(children, positions, from, to, 0);
1427
+ return (mkTop || mkTree)(localChildren, localPositions, length);
1428
+ }
1429
+ var Parser = class {
1430
+ /// Start a parse, returning a [partial parse](#common.PartialParse)
1431
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
1432
+ /// make the parse incremental.
1433
+ ///
1434
+ /// By default, the entire input is parsed. You can pass `ranges`,
1435
+ /// which should be a sorted array of non-empty, non-overlapping
1436
+ /// ranges, to parse only those ranges. The tree returned in that
1437
+ /// case will start at `ranges[0].from`.
1438
+ startParse(input, fragments, ranges) {
1439
+ if (typeof input == "string")
1440
+ input = new StringInput(input);
1441
+ ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map((r) => new Range(r.from, r.to)) : [new Range(0, 0)];
1442
+ return this.createParse(input, fragments || [], ranges);
1443
+ }
1444
+ /// Run a full parse, returning the resulting tree.
1445
+ parse(input, fragments, ranges) {
1446
+ let parse = this.startParse(input, fragments, ranges);
1447
+ for (; ; ) {
1448
+ let done = parse.advance();
1449
+ if (done)
1450
+ return done;
1451
+ }
1452
+ }
1453
+ };
1454
+ var StringInput = class {
1455
+ constructor(string) {
1456
+ this.string = string;
1457
+ }
1458
+ get length() {
1459
+ return this.string.length;
1460
+ }
1461
+ chunk(from) {
1462
+ return this.string.slice(from);
1463
+ }
1464
+ get lineChunks() {
1465
+ return false;
1466
+ }
1467
+ read(from, to) {
1468
+ return this.string.slice(from, to);
1469
+ }
1470
+ };
1471
+ var stoppedInner = new NodeProp({ perNode: true });
27
1472
 
28
- .saltIcon:active {
29
- --icon-color: var(--saltIcon-color-active, var(--salt-text-secondary-foreground));
1473
+ // ../../node_modules/@lezer/lr/dist/index.js
1474
+ var Stack = class {
1475
+ /// @internal
1476
+ constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) {
1477
+ this.p = p;
1478
+ this.stack = stack;
1479
+ this.state = state;
1480
+ this.reducePos = reducePos;
1481
+ this.pos = pos;
1482
+ this.score = score;
1483
+ this.buffer = buffer;
1484
+ this.bufferBase = bufferBase;
1485
+ this.curContext = curContext;
1486
+ this.lookAhead = lookAhead;
1487
+ this.parent = parent;
1488
+ }
1489
+ /// @internal
1490
+ toString() {
1491
+ return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
1492
+ }
1493
+ // Start an empty stack
1494
+ /// @internal
1495
+ static start(p, state, pos = 0) {
1496
+ let cx3 = p.parser.context;
1497
+ return new Stack(p, [], state, pos, pos, 0, [], 0, cx3 ? new StackContext(cx3, cx3.start) : null, 0, null);
1498
+ }
1499
+ /// The stack's current [context](#lr.ContextTracker) value, if
1500
+ /// any. Its type will depend on the context tracker's type
1501
+ /// parameter, or it will be `null` if there is no context
1502
+ /// tracker.
1503
+ get context() {
1504
+ return this.curContext ? this.curContext.context : null;
1505
+ }
1506
+ // Push a state onto the stack, tracking its start position as well
1507
+ // as the buffer base at that point.
1508
+ /// @internal
1509
+ pushState(state, start) {
1510
+ this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
1511
+ this.state = state;
1512
+ }
1513
+ // Apply a reduce action
1514
+ /// @internal
1515
+ reduce(action) {
1516
+ var _a;
1517
+ let depth = action >> 19, type = action & 65535;
1518
+ let { parser: parser2 } = this.p;
1519
+ let dPrec = parser2.dynamicPrecedence(type);
1520
+ if (dPrec)
1521
+ this.score += dPrec;
1522
+ if (depth == 0) {
1523
+ this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
1524
+ if (type < parser2.minRepeatTerm)
1525
+ this.storeNode(type, this.reducePos, this.reducePos, 4, true);
1526
+ this.reduceContext(type, this.reducePos);
1527
+ return;
1528
+ }
1529
+ let base = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
1530
+ let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
1531
+ if (size >= 2e3 && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
1532
+ if (start == this.p.lastBigReductionStart) {
1533
+ this.p.bigReductionCount++;
1534
+ this.p.lastBigReductionSize = size;
1535
+ } else if (this.p.lastBigReductionSize < size) {
1536
+ this.p.bigReductionCount = 1;
1537
+ this.p.lastBigReductionStart = start;
1538
+ this.p.lastBigReductionSize = size;
1539
+ }
1540
+ }
1541
+ let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
1542
+ if (type < parser2.minRepeatTerm || action & 131072) {
1543
+ let pos = parser2.stateFlag(
1544
+ this.state,
1545
+ 1
1546
+ /* StateFlag.Skipped */
1547
+ ) ? this.pos : this.reducePos;
1548
+ this.storeNode(type, start, pos, count + 4, true);
1549
+ }
1550
+ if (action & 262144) {
1551
+ this.state = this.stack[base];
1552
+ } else {
1553
+ let baseStateID = this.stack[base - 3];
1554
+ this.state = parser2.getGoto(baseStateID, type, true);
1555
+ }
1556
+ while (this.stack.length > base)
1557
+ this.stack.pop();
1558
+ this.reduceContext(type, start);
1559
+ }
1560
+ // Shift a value into the buffer
1561
+ /// @internal
1562
+ storeNode(term, start, end, size = 4, isReduce = false) {
1563
+ if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
1564
+ let cur = this, top = this.buffer.length;
1565
+ if (top == 0 && cur.parent) {
1566
+ top = cur.bufferBase - cur.parent.bufferBase;
1567
+ cur = cur.parent;
1568
+ }
1569
+ if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) {
1570
+ if (start == end)
1571
+ return;
1572
+ if (cur.buffer[top - 2] >= start) {
1573
+ cur.buffer[top - 2] = end;
1574
+ return;
1575
+ }
1576
+ }
1577
+ }
1578
+ if (!isReduce || this.pos == end) {
1579
+ this.buffer.push(term, start, end, size);
1580
+ } else {
1581
+ let index = this.buffer.length;
1582
+ if (index > 0 && this.buffer[index - 4] != 0)
1583
+ while (index > 0 && this.buffer[index - 2] > end) {
1584
+ this.buffer[index] = this.buffer[index - 4];
1585
+ this.buffer[index + 1] = this.buffer[index - 3];
1586
+ this.buffer[index + 2] = this.buffer[index - 2];
1587
+ this.buffer[index + 3] = this.buffer[index - 1];
1588
+ index -= 4;
1589
+ if (size > 4)
1590
+ size -= 4;
1591
+ }
1592
+ this.buffer[index] = term;
1593
+ this.buffer[index + 1] = start;
1594
+ this.buffer[index + 2] = end;
1595
+ this.buffer[index + 3] = size;
1596
+ }
1597
+ }
1598
+ // Apply a shift action
1599
+ /// @internal
1600
+ shift(action, next, nextEnd) {
1601
+ let start = this.pos;
1602
+ if (action & 131072) {
1603
+ this.pushState(action & 65535, this.pos);
1604
+ } else if ((action & 262144) == 0) {
1605
+ let nextState = action, { parser: parser2 } = this.p;
1606
+ if (nextEnd > this.pos || next <= parser2.maxNode) {
1607
+ this.pos = nextEnd;
1608
+ if (!parser2.stateFlag(
1609
+ nextState,
1610
+ 1
1611
+ /* StateFlag.Skipped */
1612
+ ))
1613
+ this.reducePos = nextEnd;
1614
+ }
1615
+ this.pushState(nextState, start);
1616
+ this.shiftContext(next, start);
1617
+ if (next <= parser2.maxNode)
1618
+ this.buffer.push(next, start, nextEnd, 4);
1619
+ } else {
1620
+ this.pos = nextEnd;
1621
+ this.shiftContext(next, start);
1622
+ if (next <= this.p.parser.maxNode)
1623
+ this.buffer.push(next, start, nextEnd, 4);
1624
+ }
1625
+ }
1626
+ // Apply an action
1627
+ /// @internal
1628
+ apply(action, next, nextEnd) {
1629
+ if (action & 65536)
1630
+ this.reduce(action);
1631
+ else
1632
+ this.shift(action, next, nextEnd);
1633
+ }
1634
+ // Add a prebuilt (reused) node into the buffer.
1635
+ /// @internal
1636
+ useNode(value, next) {
1637
+ let index = this.p.reused.length - 1;
1638
+ if (index < 0 || this.p.reused[index] != value) {
1639
+ this.p.reused.push(value);
1640
+ index++;
1641
+ }
1642
+ let start = this.pos;
1643
+ this.reducePos = this.pos = start + value.length;
1644
+ this.pushState(next, start);
1645
+ this.buffer.push(
1646
+ index,
1647
+ start,
1648
+ this.reducePos,
1649
+ -1
1650
+ /* size == -1 means this is a reused value */
1651
+ );
1652
+ if (this.curContext)
1653
+ this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
1654
+ }
1655
+ // Split the stack. Due to the buffer sharing and the fact
1656
+ // that `this.stack` tends to stay quite shallow, this isn't very
1657
+ // expensive.
1658
+ /// @internal
1659
+ split() {
1660
+ let parent = this;
1661
+ let off = parent.buffer.length;
1662
+ while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
1663
+ off -= 4;
1664
+ let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
1665
+ while (parent && base == parent.bufferBase)
1666
+ parent = parent.parent;
1667
+ return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
1668
+ }
1669
+ // Try to recover from an error by 'deleting' (ignoring) one token.
1670
+ /// @internal
1671
+ recoverByDelete(next, nextEnd) {
1672
+ let isNode = next <= this.p.parser.maxNode;
1673
+ if (isNode)
1674
+ this.storeNode(next, this.pos, nextEnd, 4);
1675
+ this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
1676
+ this.pos = this.reducePos = nextEnd;
1677
+ this.score -= 190;
1678
+ }
1679
+ /// Check if the given term would be able to be shifted (optionally
1680
+ /// after some reductions) on this stack. This can be useful for
1681
+ /// external tokenizers that want to make sure they only provide a
1682
+ /// given token when it applies.
1683
+ canShift(term) {
1684
+ for (let sim = new SimulatedStack(this); ; ) {
1685
+ let action = this.p.parser.stateSlot(
1686
+ sim.state,
1687
+ 4
1688
+ /* ParseState.DefaultReduce */
1689
+ ) || this.p.parser.hasAction(sim.state, term);
1690
+ if (action == 0)
1691
+ return false;
1692
+ if ((action & 65536) == 0)
1693
+ return true;
1694
+ sim.reduce(action);
1695
+ }
1696
+ }
1697
+ // Apply up to Recover.MaxNext recovery actions that conceptually
1698
+ // inserts some missing token or rule.
1699
+ /// @internal
1700
+ recoverByInsert(next) {
1701
+ if (this.stack.length >= 300)
1702
+ return [];
1703
+ let nextStates = this.p.parser.nextStates(this.state);
1704
+ if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
1705
+ let best = [];
1706
+ for (let i = 0, s; i < nextStates.length; i += 2) {
1707
+ if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
1708
+ best.push(nextStates[i], s);
1709
+ }
1710
+ if (this.stack.length < 120)
1711
+ for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
1712
+ let s = nextStates[i + 1];
1713
+ if (!best.some((v, i2) => i2 & 1 && v == s))
1714
+ best.push(nextStates[i], s);
1715
+ }
1716
+ nextStates = best;
1717
+ }
1718
+ let result = [];
1719
+ for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
1720
+ let s = nextStates[i + 1];
1721
+ if (s == this.state)
1722
+ continue;
1723
+ let stack = this.split();
1724
+ stack.pushState(s, this.pos);
1725
+ stack.storeNode(0, stack.pos, stack.pos, 4, true);
1726
+ stack.shiftContext(nextStates[i], this.pos);
1727
+ stack.score -= 200;
1728
+ result.push(stack);
1729
+ }
1730
+ return result;
1731
+ }
1732
+ // Force a reduce, if possible. Return false if that can't
1733
+ // be done.
1734
+ /// @internal
1735
+ forceReduce() {
1736
+ let { parser: parser2 } = this.p;
1737
+ let reduce = parser2.stateSlot(
1738
+ this.state,
1739
+ 5
1740
+ /* ParseState.ForcedReduce */
1741
+ );
1742
+ if ((reduce & 65536) == 0)
1743
+ return false;
1744
+ if (!parser2.validAction(this.state, reduce)) {
1745
+ let depth = reduce >> 19, term = reduce & 65535;
1746
+ let target = this.stack.length - depth * 3;
1747
+ if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0) {
1748
+ let backup = this.findForcedReduction();
1749
+ if (backup == null)
1750
+ return false;
1751
+ reduce = backup;
1752
+ }
1753
+ this.storeNode(0, this.pos, this.pos, 4, true);
1754
+ this.score -= 100;
1755
+ }
1756
+ this.reducePos = this.pos;
1757
+ this.reduce(reduce);
1758
+ return true;
1759
+ }
1760
+ /// Try to scan through the automaton to find some kind of reduction
1761
+ /// that can be applied. Used when the regular ForcedReduce field
1762
+ /// isn't a valid action. @internal
1763
+ findForcedReduction() {
1764
+ let { parser: parser2 } = this.p, seen = [];
1765
+ let explore = (state, depth) => {
1766
+ if (seen.includes(state))
1767
+ return;
1768
+ seen.push(state);
1769
+ return parser2.allActions(state, (action) => {
1770
+ if (action & (262144 | 131072))
1771
+ ;
1772
+ else if (action & 65536) {
1773
+ let rDepth = (action >> 19) - depth;
1774
+ if (rDepth > 1) {
1775
+ let term = action & 65535, target = this.stack.length - rDepth * 3;
1776
+ if (target >= 0 && parser2.getGoto(this.stack[target], term, false) >= 0)
1777
+ return rDepth << 19 | 65536 | term;
1778
+ }
1779
+ } else {
1780
+ let found = explore(action, depth + 1);
1781
+ if (found != null)
1782
+ return found;
1783
+ }
1784
+ });
1785
+ };
1786
+ return explore(this.state, 0);
1787
+ }
1788
+ /// @internal
1789
+ forceAll() {
1790
+ while (!this.p.parser.stateFlag(
1791
+ this.state,
1792
+ 2
1793
+ /* StateFlag.Accepting */
1794
+ )) {
1795
+ if (!this.forceReduce()) {
1796
+ this.storeNode(0, this.pos, this.pos, 4, true);
1797
+ break;
1798
+ }
1799
+ }
1800
+ return this;
1801
+ }
1802
+ /// Check whether this state has no further actions (assumed to be a direct descendant of the
1803
+ /// top state, since any other states must be able to continue
1804
+ /// somehow). @internal
1805
+ get deadEnd() {
1806
+ if (this.stack.length != 3)
1807
+ return false;
1808
+ let { parser: parser2 } = this.p;
1809
+ return parser2.data[parser2.stateSlot(
1810
+ this.state,
1811
+ 1
1812
+ /* ParseState.Actions */
1813
+ )] == 65535 && !parser2.stateSlot(
1814
+ this.state,
1815
+ 4
1816
+ /* ParseState.DefaultReduce */
1817
+ );
1818
+ }
1819
+ /// Restart the stack (put it back in its start state). Only safe
1820
+ /// when this.stack.length == 3 (state is directly below the top
1821
+ /// state). @internal
1822
+ restart() {
1823
+ this.state = this.stack[0];
1824
+ this.stack.length = 0;
1825
+ }
1826
+ /// @internal
1827
+ sameState(other) {
1828
+ if (this.state != other.state || this.stack.length != other.stack.length)
1829
+ return false;
1830
+ for (let i = 0; i < this.stack.length; i += 3)
1831
+ if (this.stack[i] != other.stack[i])
1832
+ return false;
1833
+ return true;
1834
+ }
1835
+ /// Get the parser used by this stack.
1836
+ get parser() {
1837
+ return this.p.parser;
1838
+ }
1839
+ /// Test whether a given dialect (by numeric ID, as exported from
1840
+ /// the terms file) is enabled.
1841
+ dialectEnabled(dialectID) {
1842
+ return this.p.parser.dialect.flags[dialectID];
1843
+ }
1844
+ shiftContext(term, start) {
1845
+ if (this.curContext)
1846
+ this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
1847
+ }
1848
+ reduceContext(term, start) {
1849
+ if (this.curContext)
1850
+ this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
1851
+ }
1852
+ /// @internal
1853
+ emitContext() {
1854
+ let last = this.buffer.length - 1;
1855
+ if (last < 0 || this.buffer[last] != -3)
1856
+ this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
1857
+ }
1858
+ /// @internal
1859
+ emitLookAhead() {
1860
+ let last = this.buffer.length - 1;
1861
+ if (last < 0 || this.buffer[last] != -4)
1862
+ this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
1863
+ }
1864
+ updateContext(context) {
1865
+ if (context != this.curContext.context) {
1866
+ let newCx = new StackContext(this.curContext.tracker, context);
1867
+ if (newCx.hash != this.curContext.hash)
1868
+ this.emitContext();
1869
+ this.curContext = newCx;
1870
+ }
1871
+ }
1872
+ /// @internal
1873
+ setLookAhead(lookAhead) {
1874
+ if (lookAhead > this.lookAhead) {
1875
+ this.emitLookAhead();
1876
+ this.lookAhead = lookAhead;
1877
+ }
1878
+ }
1879
+ /// @internal
1880
+ close() {
1881
+ if (this.curContext && this.curContext.tracker.strict)
1882
+ this.emitContext();
1883
+ if (this.lookAhead > 0)
1884
+ this.emitLookAhead();
1885
+ }
1886
+ };
1887
+ var StackContext = class {
1888
+ constructor(tracker, context) {
1889
+ this.tracker = tracker;
1890
+ this.context = context;
1891
+ this.hash = tracker.strict ? tracker.hash(context) : 0;
1892
+ }
1893
+ };
1894
+ var Recover;
1895
+ (function(Recover2) {
1896
+ Recover2[Recover2["Insert"] = 200] = "Insert";
1897
+ Recover2[Recover2["Delete"] = 190] = "Delete";
1898
+ Recover2[Recover2["Reduce"] = 100] = "Reduce";
1899
+ Recover2[Recover2["MaxNext"] = 4] = "MaxNext";
1900
+ Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
1901
+ Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
1902
+ Recover2[Recover2["MinBigReduction"] = 2e3] = "MinBigReduction";
1903
+ })(Recover || (Recover = {}));
1904
+ var SimulatedStack = class {
1905
+ constructor(start) {
1906
+ this.start = start;
1907
+ this.state = start.state;
1908
+ this.stack = start.stack;
1909
+ this.base = this.stack.length;
1910
+ }
1911
+ reduce(action) {
1912
+ let term = action & 65535, depth = action >> 19;
1913
+ if (depth == 0) {
1914
+ if (this.stack == this.start.stack)
1915
+ this.stack = this.stack.slice();
1916
+ this.stack.push(this.state, 0, 0);
1917
+ this.base += 3;
1918
+ } else {
1919
+ this.base -= (depth - 1) * 3;
1920
+ }
1921
+ let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
1922
+ this.state = goto;
1923
+ }
1924
+ };
1925
+ var StackBufferCursor = class {
1926
+ constructor(stack, pos, index) {
1927
+ this.stack = stack;
1928
+ this.pos = pos;
1929
+ this.index = index;
1930
+ this.buffer = stack.buffer;
1931
+ if (this.index == 0)
1932
+ this.maybeNext();
1933
+ }
1934
+ static create(stack, pos = stack.bufferBase + stack.buffer.length) {
1935
+ return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
1936
+ }
1937
+ maybeNext() {
1938
+ let next = this.stack.parent;
1939
+ if (next != null) {
1940
+ this.index = this.stack.bufferBase - next.bufferBase;
1941
+ this.stack = next;
1942
+ this.buffer = next.buffer;
1943
+ }
1944
+ }
1945
+ get id() {
1946
+ return this.buffer[this.index - 4];
1947
+ }
1948
+ get start() {
1949
+ return this.buffer[this.index - 3];
1950
+ }
1951
+ get end() {
1952
+ return this.buffer[this.index - 2];
1953
+ }
1954
+ get size() {
1955
+ return this.buffer[this.index - 1];
1956
+ }
1957
+ next() {
1958
+ this.index -= 4;
1959
+ this.pos -= 4;
1960
+ if (this.index == 0)
1961
+ this.maybeNext();
1962
+ }
1963
+ fork() {
1964
+ return new StackBufferCursor(this.stack, this.pos, this.index);
1965
+ }
1966
+ };
1967
+ function decodeArray(input, Type = Uint16Array) {
1968
+ if (typeof input != "string")
1969
+ return input;
1970
+ let array = null;
1971
+ for (let pos = 0, out = 0; pos < input.length; ) {
1972
+ let value = 0;
1973
+ for (; ; ) {
1974
+ let next = input.charCodeAt(pos++), stop = false;
1975
+ if (next == 126) {
1976
+ value = 65535;
1977
+ break;
1978
+ }
1979
+ if (next >= 92)
1980
+ next--;
1981
+ if (next >= 34)
1982
+ next--;
1983
+ let digit = next - 32;
1984
+ if (digit >= 46) {
1985
+ digit -= 46;
1986
+ stop = true;
1987
+ }
1988
+ value += digit;
1989
+ if (stop)
1990
+ break;
1991
+ value *= 46;
1992
+ }
1993
+ if (array)
1994
+ array[out++] = value;
1995
+ else
1996
+ array = new Type(value);
1997
+ }
1998
+ return array;
1999
+ }
2000
+ var CachedToken = class {
2001
+ constructor() {
2002
+ this.start = -1;
2003
+ this.value = -1;
2004
+ this.end = -1;
2005
+ this.extended = -1;
2006
+ this.lookAhead = 0;
2007
+ this.mask = 0;
2008
+ this.context = 0;
2009
+ }
2010
+ };
2011
+ var nullToken = new CachedToken();
2012
+ var InputStream = class {
2013
+ /// @internal
2014
+ constructor(input, ranges) {
2015
+ this.input = input;
2016
+ this.ranges = ranges;
2017
+ this.chunk = "";
2018
+ this.chunkOff = 0;
2019
+ this.chunk2 = "";
2020
+ this.chunk2Pos = 0;
2021
+ this.next = -1;
2022
+ this.token = nullToken;
2023
+ this.rangeIndex = 0;
2024
+ this.pos = this.chunkPos = ranges[0].from;
2025
+ this.range = ranges[0];
2026
+ this.end = ranges[ranges.length - 1].to;
2027
+ this.readNext();
2028
+ }
2029
+ /// @internal
2030
+ resolveOffset(offset, assoc) {
2031
+ let range = this.range, index = this.rangeIndex;
2032
+ let pos = this.pos + offset;
2033
+ while (pos < range.from) {
2034
+ if (!index)
2035
+ return null;
2036
+ let next = this.ranges[--index];
2037
+ pos -= range.from - next.to;
2038
+ range = next;
2039
+ }
2040
+ while (assoc < 0 ? pos > range.to : pos >= range.to) {
2041
+ if (index == this.ranges.length - 1)
2042
+ return null;
2043
+ let next = this.ranges[++index];
2044
+ pos += next.from - range.to;
2045
+ range = next;
2046
+ }
2047
+ return pos;
2048
+ }
2049
+ /// @internal
2050
+ clipPos(pos) {
2051
+ if (pos >= this.range.from && pos < this.range.to)
2052
+ return pos;
2053
+ for (let range of this.ranges)
2054
+ if (range.to > pos)
2055
+ return Math.max(pos, range.from);
2056
+ return this.end;
2057
+ }
2058
+ /// Look at a code unit near the stream position. `.peek(0)` equals
2059
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
2060
+ /// on.
2061
+ ///
2062
+ /// Note that looking around during tokenizing creates dependencies
2063
+ /// on potentially far-away content, which may reduce the
2064
+ /// effectiveness incremental parsing—when looking forward—or even
2065
+ /// cause invalid reparses when looking backward more than 25 code
2066
+ /// units, since the library does not track lookbehind.
2067
+ peek(offset) {
2068
+ let idx = this.chunkOff + offset, pos, result;
2069
+ if (idx >= 0 && idx < this.chunk.length) {
2070
+ pos = this.pos + offset;
2071
+ result = this.chunk.charCodeAt(idx);
2072
+ } else {
2073
+ let resolved = this.resolveOffset(offset, 1);
2074
+ if (resolved == null)
2075
+ return -1;
2076
+ pos = resolved;
2077
+ if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
2078
+ result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
2079
+ } else {
2080
+ let i = this.rangeIndex, range = this.range;
2081
+ while (range.to <= pos)
2082
+ range = this.ranges[++i];
2083
+ this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
2084
+ if (pos + this.chunk2.length > range.to)
2085
+ this.chunk2 = this.chunk2.slice(0, range.to - pos);
2086
+ result = this.chunk2.charCodeAt(0);
2087
+ }
2088
+ }
2089
+ if (pos >= this.token.lookAhead)
2090
+ this.token.lookAhead = pos + 1;
2091
+ return result;
2092
+ }
2093
+ /// Accept a token. By default, the end of the token is set to the
2094
+ /// current stream position, but you can pass an offset (relative to
2095
+ /// the stream position) to change that.
2096
+ acceptToken(token, endOffset = 0) {
2097
+ let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
2098
+ if (end == null || end < this.token.start)
2099
+ throw new RangeError("Token end out of bounds");
2100
+ this.token.value = token;
2101
+ this.token.end = end;
2102
+ }
2103
+ getChunk() {
2104
+ if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
2105
+ let { chunk, chunkPos } = this;
2106
+ this.chunk = this.chunk2;
2107
+ this.chunkPos = this.chunk2Pos;
2108
+ this.chunk2 = chunk;
2109
+ this.chunk2Pos = chunkPos;
2110
+ this.chunkOff = this.pos - this.chunkPos;
2111
+ } else {
2112
+ this.chunk2 = this.chunk;
2113
+ this.chunk2Pos = this.chunkPos;
2114
+ let nextChunk = this.input.chunk(this.pos);
2115
+ let end = this.pos + nextChunk.length;
2116
+ this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
2117
+ this.chunkPos = this.pos;
2118
+ this.chunkOff = 0;
2119
+ }
2120
+ }
2121
+ readNext() {
2122
+ if (this.chunkOff >= this.chunk.length) {
2123
+ this.getChunk();
2124
+ if (this.chunkOff == this.chunk.length)
2125
+ return this.next = -1;
2126
+ }
2127
+ return this.next = this.chunk.charCodeAt(this.chunkOff);
2128
+ }
2129
+ /// Move the stream forward N (defaults to 1) code units. Returns
2130
+ /// the new value of [`next`](#lr.InputStream.next).
2131
+ advance(n = 1) {
2132
+ this.chunkOff += n;
2133
+ while (this.pos + n >= this.range.to) {
2134
+ if (this.rangeIndex == this.ranges.length - 1)
2135
+ return this.setDone();
2136
+ n -= this.range.to - this.pos;
2137
+ this.range = this.ranges[++this.rangeIndex];
2138
+ this.pos = this.range.from;
2139
+ }
2140
+ this.pos += n;
2141
+ if (this.pos >= this.token.lookAhead)
2142
+ this.token.lookAhead = this.pos + 1;
2143
+ return this.readNext();
2144
+ }
2145
+ setDone() {
2146
+ this.pos = this.chunkPos = this.end;
2147
+ this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
2148
+ this.chunk = "";
2149
+ return this.next = -1;
2150
+ }
2151
+ /// @internal
2152
+ reset(pos, token) {
2153
+ if (token) {
2154
+ this.token = token;
2155
+ token.start = pos;
2156
+ token.lookAhead = pos + 1;
2157
+ token.value = token.extended = -1;
2158
+ } else {
2159
+ this.token = nullToken;
2160
+ }
2161
+ if (this.pos != pos) {
2162
+ this.pos = pos;
2163
+ if (pos == this.end) {
2164
+ this.setDone();
2165
+ return this;
2166
+ }
2167
+ while (pos < this.range.from)
2168
+ this.range = this.ranges[--this.rangeIndex];
2169
+ while (pos >= this.range.to)
2170
+ this.range = this.ranges[++this.rangeIndex];
2171
+ if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
2172
+ this.chunkOff = pos - this.chunkPos;
2173
+ } else {
2174
+ this.chunk = "";
2175
+ this.chunkOff = 0;
2176
+ }
2177
+ this.readNext();
2178
+ }
2179
+ return this;
2180
+ }
2181
+ /// @internal
2182
+ read(from, to) {
2183
+ if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
2184
+ return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
2185
+ if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
2186
+ return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
2187
+ if (from >= this.range.from && to <= this.range.to)
2188
+ return this.input.read(from, to);
2189
+ let result = "";
2190
+ for (let r of this.ranges) {
2191
+ if (r.from >= to)
2192
+ break;
2193
+ if (r.to > from)
2194
+ result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
2195
+ }
2196
+ return result;
2197
+ }
2198
+ };
2199
+ var TokenGroup = class {
2200
+ constructor(data, id) {
2201
+ this.data = data;
2202
+ this.id = id;
2203
+ }
2204
+ token(input, stack) {
2205
+ let { parser: parser2 } = stack.p;
2206
+ readToken(this.data, input, stack, this.id, parser2.data, parser2.tokenPrecTable);
2207
+ }
2208
+ };
2209
+ TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2210
+ var LocalTokenGroup = class {
2211
+ constructor(data, precTable, elseToken) {
2212
+ this.precTable = precTable;
2213
+ this.elseToken = elseToken;
2214
+ this.data = typeof data == "string" ? decodeArray(data) : data;
2215
+ }
2216
+ token(input, stack) {
2217
+ let start = input.pos, skipped = 0;
2218
+ for (; ; ) {
2219
+ let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
2220
+ readToken(this.data, input, stack, 0, this.data, this.precTable);
2221
+ if (input.token.value > -1)
2222
+ break;
2223
+ if (this.elseToken == null)
2224
+ return;
2225
+ if (!atEof)
2226
+ skipped++;
2227
+ if (nextPos == null)
2228
+ break;
2229
+ input.reset(nextPos, input.token);
2230
+ }
2231
+ if (skipped) {
2232
+ input.reset(start, input.token);
2233
+ input.acceptToken(this.elseToken, skipped);
2234
+ }
2235
+ }
2236
+ };
2237
+ LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2238
+ function readToken(data, input, stack, group, precTable, precOffset) {
2239
+ let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
2240
+ scan:
2241
+ for (; ; ) {
2242
+ if ((groupMask & data[state]) == 0)
2243
+ break;
2244
+ let accEnd = data[state + 1];
2245
+ for (let i = state + 3; i < accEnd; i += 2)
2246
+ if ((data[i + 1] & groupMask) > 0) {
2247
+ let term = data[i];
2248
+ if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
2249
+ input.acceptToken(term);
2250
+ break;
2251
+ }
2252
+ }
2253
+ let next = input.next, low = 0, high = data[state + 2];
2254
+ if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 && data[accEnd + high * 3 - 3] == 65535) {
2255
+ state = data[accEnd + high * 3 - 1];
2256
+ continue scan;
2257
+ }
2258
+ for (; low < high; ) {
2259
+ let mid = low + high >> 1;
2260
+ let index = accEnd + mid + (mid << 1);
2261
+ let from = data[index], to = data[index + 1] || 65536;
2262
+ if (next < from)
2263
+ high = mid;
2264
+ else if (next >= to)
2265
+ low = mid + 1;
2266
+ else {
2267
+ state = data[index + 2];
2268
+ input.advance();
2269
+ continue scan;
2270
+ }
2271
+ }
2272
+ break;
2273
+ }
2274
+ }
2275
+ function findOffset(data, start, term) {
2276
+ for (let i = start, next; (next = data[i]) != 65535; i++)
2277
+ if (next == term)
2278
+ return i - start;
2279
+ return -1;
2280
+ }
2281
+ function overrides(token, prev, tableData, tableOffset) {
2282
+ let iPrev = findOffset(tableData, tableOffset, prev);
2283
+ return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
2284
+ }
2285
+ var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
2286
+ var stackIDs = null;
2287
+ var Safety;
2288
+ (function(Safety2) {
2289
+ Safety2[Safety2["Margin"] = 25] = "Margin";
2290
+ })(Safety || (Safety = {}));
2291
+ function cutAt(tree, pos, side) {
2292
+ let cursor = tree.cursor(IterMode.IncludeAnonymous);
2293
+ cursor.moveTo(pos);
2294
+ for (; ; ) {
2295
+ if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
2296
+ for (; ; ) {
2297
+ if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
2298
+ return side < 0 ? Math.max(0, Math.min(
2299
+ cursor.to - 1,
2300
+ pos - 25
2301
+ /* Safety.Margin */
2302
+ )) : Math.min(tree.length, Math.max(
2303
+ cursor.from + 1,
2304
+ pos + 25
2305
+ /* Safety.Margin */
2306
+ ));
2307
+ if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
2308
+ break;
2309
+ if (!cursor.parent())
2310
+ return side < 0 ? 0 : tree.length;
2311
+ }
2312
+ }
2313
+ }
2314
+ var FragmentCursor = class {
2315
+ constructor(fragments, nodeSet) {
2316
+ this.fragments = fragments;
2317
+ this.nodeSet = nodeSet;
2318
+ this.i = 0;
2319
+ this.fragment = null;
2320
+ this.safeFrom = -1;
2321
+ this.safeTo = -1;
2322
+ this.trees = [];
2323
+ this.start = [];
2324
+ this.index = [];
2325
+ this.nextFragment();
2326
+ }
2327
+ nextFragment() {
2328
+ let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
2329
+ if (fr) {
2330
+ this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
2331
+ this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
2332
+ while (this.trees.length) {
2333
+ this.trees.pop();
2334
+ this.start.pop();
2335
+ this.index.pop();
2336
+ }
2337
+ this.trees.push(fr.tree);
2338
+ this.start.push(-fr.offset);
2339
+ this.index.push(0);
2340
+ this.nextStart = this.safeFrom;
2341
+ } else {
2342
+ this.nextStart = 1e9;
2343
+ }
2344
+ }
2345
+ // `pos` must be >= any previously given `pos` for this cursor
2346
+ nodeAt(pos) {
2347
+ if (pos < this.nextStart)
2348
+ return null;
2349
+ while (this.fragment && this.safeTo <= pos)
2350
+ this.nextFragment();
2351
+ if (!this.fragment)
2352
+ return null;
2353
+ for (; ; ) {
2354
+ let last = this.trees.length - 1;
2355
+ if (last < 0) {
2356
+ this.nextFragment();
2357
+ return null;
2358
+ }
2359
+ let top = this.trees[last], index = this.index[last];
2360
+ if (index == top.children.length) {
2361
+ this.trees.pop();
2362
+ this.start.pop();
2363
+ this.index.pop();
2364
+ continue;
2365
+ }
2366
+ let next = top.children[index];
2367
+ let start = this.start[last] + top.positions[index];
2368
+ if (start > pos) {
2369
+ this.nextStart = start;
2370
+ return null;
2371
+ }
2372
+ if (next instanceof Tree) {
2373
+ if (start == pos) {
2374
+ if (start < this.safeFrom)
2375
+ return null;
2376
+ let end = start + next.length;
2377
+ if (end <= this.safeTo) {
2378
+ let lookAhead = next.prop(NodeProp.lookAhead);
2379
+ if (!lookAhead || end + lookAhead < this.fragment.to)
2380
+ return next;
2381
+ }
2382
+ }
2383
+ this.index[last]++;
2384
+ if (start + next.length >= Math.max(this.safeFrom, pos)) {
2385
+ this.trees.push(next);
2386
+ this.start.push(start);
2387
+ this.index.push(0);
2388
+ }
2389
+ } else {
2390
+ this.index[last]++;
2391
+ this.nextStart = start + next.length;
2392
+ }
2393
+ }
2394
+ }
2395
+ };
2396
+ var TokenCache = class {
2397
+ constructor(parser2, stream) {
2398
+ this.stream = stream;
2399
+ this.tokens = [];
2400
+ this.mainToken = null;
2401
+ this.actions = [];
2402
+ this.tokens = parser2.tokenizers.map((_) => new CachedToken());
2403
+ }
2404
+ getActions(stack) {
2405
+ let actionIndex = 0;
2406
+ let main = null;
2407
+ let { parser: parser2 } = stack.p, { tokenizers } = parser2;
2408
+ let mask = parser2.stateSlot(
2409
+ stack.state,
2410
+ 3
2411
+ /* ParseState.TokenizerMask */
2412
+ );
2413
+ let context = stack.curContext ? stack.curContext.hash : 0;
2414
+ let lookAhead = 0;
2415
+ for (let i = 0; i < tokenizers.length; i++) {
2416
+ if ((1 << i & mask) == 0)
2417
+ continue;
2418
+ let tokenizer = tokenizers[i], token = this.tokens[i];
2419
+ if (main && !tokenizer.fallback)
2420
+ continue;
2421
+ if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
2422
+ this.updateCachedToken(token, tokenizer, stack);
2423
+ token.mask = mask;
2424
+ token.context = context;
2425
+ }
2426
+ if (token.lookAhead > token.end + 25)
2427
+ lookAhead = Math.max(token.lookAhead, lookAhead);
2428
+ if (token.value != 0) {
2429
+ let startIndex = actionIndex;
2430
+ if (token.extended > -1)
2431
+ actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
2432
+ actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
2433
+ if (!tokenizer.extend) {
2434
+ main = token;
2435
+ if (actionIndex > startIndex)
2436
+ break;
2437
+ }
2438
+ }
2439
+ }
2440
+ while (this.actions.length > actionIndex)
2441
+ this.actions.pop();
2442
+ if (lookAhead)
2443
+ stack.setLookAhead(lookAhead);
2444
+ if (!main && stack.pos == this.stream.end) {
2445
+ main = new CachedToken();
2446
+ main.value = stack.p.parser.eofTerm;
2447
+ main.start = main.end = stack.pos;
2448
+ actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
2449
+ }
2450
+ this.mainToken = main;
2451
+ return this.actions;
2452
+ }
2453
+ getMainToken(stack) {
2454
+ if (this.mainToken)
2455
+ return this.mainToken;
2456
+ let main = new CachedToken(), { pos, p } = stack;
2457
+ main.start = pos;
2458
+ main.end = Math.min(pos + 1, p.stream.end);
2459
+ main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
2460
+ return main;
2461
+ }
2462
+ updateCachedToken(token, tokenizer, stack) {
2463
+ let start = this.stream.clipPos(stack.pos);
2464
+ tokenizer.token(this.stream.reset(start, token), stack);
2465
+ if (token.value > -1) {
2466
+ let { parser: parser2 } = stack.p;
2467
+ for (let i = 0; i < parser2.specialized.length; i++)
2468
+ if (parser2.specialized[i] == token.value) {
2469
+ let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack);
2470
+ if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
2471
+ if ((result & 1) == 0)
2472
+ token.value = result >> 1;
2473
+ else
2474
+ token.extended = result >> 1;
2475
+ break;
2476
+ }
2477
+ }
2478
+ } else {
2479
+ token.value = 0;
2480
+ token.end = this.stream.clipPos(start + 1);
2481
+ }
2482
+ }
2483
+ putAction(action, token, end, index) {
2484
+ for (let i = 0; i < index; i += 3)
2485
+ if (this.actions[i] == action)
2486
+ return index;
2487
+ this.actions[index++] = action;
2488
+ this.actions[index++] = token;
2489
+ this.actions[index++] = end;
2490
+ return index;
2491
+ }
2492
+ addActions(stack, token, end, index) {
2493
+ let { state } = stack, { parser: parser2 } = stack.p, { data } = parser2;
2494
+ for (let set = 0; set < 2; set++) {
2495
+ for (let i = parser2.stateSlot(
2496
+ state,
2497
+ set ? 2 : 1
2498
+ /* ParseState.Actions */
2499
+ ); ; i += 3) {
2500
+ if (data[i] == 65535) {
2501
+ if (data[i + 1] == 1) {
2502
+ i = pair(data, i + 2);
2503
+ } else {
2504
+ if (index == 0 && data[i + 1] == 2)
2505
+ index = this.putAction(pair(data, i + 2), token, end, index);
2506
+ break;
2507
+ }
2508
+ }
2509
+ if (data[i] == token)
2510
+ index = this.putAction(pair(data, i + 1), token, end, index);
2511
+ }
2512
+ }
2513
+ return index;
2514
+ }
2515
+ };
2516
+ var Rec;
2517
+ (function(Rec2) {
2518
+ Rec2[Rec2["Distance"] = 5] = "Distance";
2519
+ Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
2520
+ Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
2521
+ Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit";
2522
+ Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth";
2523
+ Rec2[Rec2["CutTo"] = 9e3] = "CutTo";
2524
+ Rec2[Rec2["MaxLeftAssociativeReductionCount"] = 300] = "MaxLeftAssociativeReductionCount";
2525
+ Rec2[Rec2["MaxStackCount"] = 12] = "MaxStackCount";
2526
+ })(Rec || (Rec = {}));
2527
+ var Parse = class {
2528
+ constructor(parser2, input, fragments, ranges) {
2529
+ this.parser = parser2;
2530
+ this.input = input;
2531
+ this.ranges = ranges;
2532
+ this.recovering = 0;
2533
+ this.nextStackID = 9812;
2534
+ this.minStackPos = 0;
2535
+ this.reused = [];
2536
+ this.stoppedAt = null;
2537
+ this.lastBigReductionStart = -1;
2538
+ this.lastBigReductionSize = 0;
2539
+ this.bigReductionCount = 0;
2540
+ this.stream = new InputStream(input, ranges);
2541
+ this.tokens = new TokenCache(parser2, this.stream);
2542
+ this.topTerm = parser2.top[1];
2543
+ let { from } = ranges[0];
2544
+ this.stacks = [Stack.start(this, parser2.top[0], from)];
2545
+ this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
2546
+ }
2547
+ get parsedPos() {
2548
+ return this.minStackPos;
2549
+ }
2550
+ // Move the parser forward. This will process all parse stacks at
2551
+ // `this.pos` and try to advance them to a further position. If no
2552
+ // stack for such a position is found, it'll start error-recovery.
2553
+ //
2554
+ // When the parse is finished, this will return a syntax tree. When
2555
+ // not, it returns `null`.
2556
+ advance() {
2557
+ let stacks = this.stacks, pos = this.minStackPos;
2558
+ let newStacks = this.stacks = [];
2559
+ let stopped, stoppedTokens;
2560
+ if (this.bigReductionCount > 300 && stacks.length == 1) {
2561
+ let [s] = stacks;
2562
+ while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
2563
+ }
2564
+ this.bigReductionCount = this.lastBigReductionSize = 0;
2565
+ }
2566
+ for (let i = 0; i < stacks.length; i++) {
2567
+ let stack = stacks[i];
2568
+ for (; ; ) {
2569
+ this.tokens.mainToken = null;
2570
+ if (stack.pos > pos) {
2571
+ newStacks.push(stack);
2572
+ } else if (this.advanceStack(stack, newStacks, stacks)) {
2573
+ continue;
2574
+ } else {
2575
+ if (!stopped) {
2576
+ stopped = [];
2577
+ stoppedTokens = [];
2578
+ }
2579
+ stopped.push(stack);
2580
+ let tok = this.tokens.getMainToken(stack);
2581
+ stoppedTokens.push(tok.value, tok.end);
2582
+ }
2583
+ break;
2584
+ }
2585
+ }
2586
+ if (!newStacks.length) {
2587
+ let finished = stopped && findFinished(stopped);
2588
+ if (finished)
2589
+ return this.stackToTree(finished);
2590
+ if (this.parser.strict) {
2591
+ if (verbose && stopped)
2592
+ console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
2593
+ throw new SyntaxError("No parse at " + pos);
2594
+ }
2595
+ if (!this.recovering)
2596
+ this.recovering = 5;
2597
+ }
2598
+ if (this.recovering && stopped) {
2599
+ let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
2600
+ if (finished)
2601
+ return this.stackToTree(finished.forceAll());
2602
+ }
2603
+ if (this.recovering) {
2604
+ let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
2605
+ if (newStacks.length > maxRemaining) {
2606
+ newStacks.sort((a, b) => b.score - a.score);
2607
+ while (newStacks.length > maxRemaining)
2608
+ newStacks.pop();
2609
+ }
2610
+ if (newStacks.some((s) => s.reducePos > pos))
2611
+ this.recovering--;
2612
+ } else if (newStacks.length > 1) {
2613
+ outer:
2614
+ for (let i = 0; i < newStacks.length - 1; i++) {
2615
+ let stack = newStacks[i];
2616
+ for (let j = i + 1; j < newStacks.length; j++) {
2617
+ let other = newStacks[j];
2618
+ if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
2619
+ if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
2620
+ newStacks.splice(j--, 1);
2621
+ } else {
2622
+ newStacks.splice(i--, 1);
2623
+ continue outer;
2624
+ }
2625
+ }
2626
+ }
2627
+ }
2628
+ if (newStacks.length > 12)
2629
+ newStacks.splice(
2630
+ 12,
2631
+ newStacks.length - 12
2632
+ /* Rec.MaxStackCount */
2633
+ );
2634
+ }
2635
+ this.minStackPos = newStacks[0].pos;
2636
+ for (let i = 1; i < newStacks.length; i++)
2637
+ if (newStacks[i].pos < this.minStackPos)
2638
+ this.minStackPos = newStacks[i].pos;
2639
+ return null;
2640
+ }
2641
+ stopAt(pos) {
2642
+ if (this.stoppedAt != null && this.stoppedAt < pos)
2643
+ throw new RangeError("Can't move stoppedAt forward");
2644
+ this.stoppedAt = pos;
2645
+ }
2646
+ // Returns an updated version of the given stack, or null if the
2647
+ // stack can't advance normally. When `split` and `stacks` are
2648
+ // given, stacks split off by ambiguous operations will be pushed to
2649
+ // `split`, or added to `stacks` if they move `pos` forward.
2650
+ advanceStack(stack, stacks, split) {
2651
+ let start = stack.pos, { parser: parser2 } = this;
2652
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2653
+ if (this.stoppedAt != null && start > this.stoppedAt)
2654
+ return stack.forceReduce() ? stack : null;
2655
+ if (this.fragments) {
2656
+ let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
2657
+ for (let cached = this.fragments.nodeAt(start); cached; ) {
2658
+ let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack.state, cached.type.id) : -1;
2659
+ if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
2660
+ stack.useNode(cached, match);
2661
+ if (verbose)
2662
+ console.log(base + this.stackID(stack) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
2663
+ return true;
2664
+ }
2665
+ if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
2666
+ break;
2667
+ let inner = cached.children[0];
2668
+ if (inner instanceof Tree && cached.positions[0] == 0)
2669
+ cached = inner;
2670
+ else
2671
+ break;
2672
+ }
2673
+ }
2674
+ let defaultReduce = parser2.stateSlot(
2675
+ stack.state,
2676
+ 4
2677
+ /* ParseState.DefaultReduce */
2678
+ );
2679
+ if (defaultReduce > 0) {
2680
+ stack.reduce(defaultReduce);
2681
+ if (verbose)
2682
+ console.log(base + this.stackID(stack) + ` (via always-reduce ${parser2.getName(
2683
+ defaultReduce & 65535
2684
+ /* Action.ValueMask */
2685
+ )})`);
2686
+ return true;
2687
+ }
2688
+ if (stack.stack.length >= 15e3) {
2689
+ while (stack.stack.length > 9e3 && stack.forceReduce()) {
2690
+ }
2691
+ }
2692
+ let actions = this.tokens.getActions(stack);
2693
+ for (let i = 0; i < actions.length; ) {
2694
+ let action = actions[i++], term = actions[i++], end = actions[i++];
2695
+ let last = i == actions.length || !split;
2696
+ let localStack = last ? stack : stack.split();
2697
+ localStack.apply(action, term, end);
2698
+ if (verbose)
2699
+ console.log(base + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
2700
+ action & 65535
2701
+ /* Action.ValueMask */
2702
+ )}`} for ${parser2.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
2703
+ if (last)
2704
+ return true;
2705
+ else if (localStack.pos > start)
2706
+ stacks.push(localStack);
2707
+ else
2708
+ split.push(localStack);
2709
+ }
2710
+ return false;
2711
+ }
2712
+ // Advance a given stack forward as far as it will go. Returns the
2713
+ // (possibly updated) stack if it got stuck, or null if it moved
2714
+ // forward and was given to `pushStackDedup`.
2715
+ advanceFully(stack, newStacks) {
2716
+ let pos = stack.pos;
2717
+ for (; ; ) {
2718
+ if (!this.advanceStack(stack, null, null))
2719
+ return false;
2720
+ if (stack.pos > pos) {
2721
+ pushStackDedup(stack, newStacks);
2722
+ return true;
2723
+ }
2724
+ }
2725
+ }
2726
+ runRecovery(stacks, tokens, newStacks) {
2727
+ let finished = null, restarted = false;
2728
+ for (let i = 0; i < stacks.length; i++) {
2729
+ let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
2730
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2731
+ if (stack.deadEnd) {
2732
+ if (restarted)
2733
+ continue;
2734
+ restarted = true;
2735
+ stack.restart();
2736
+ if (verbose)
2737
+ console.log(base + this.stackID(stack) + " (restarted)");
2738
+ let done = this.advanceFully(stack, newStacks);
2739
+ if (done)
2740
+ continue;
2741
+ }
2742
+ let force = stack.split(), forceBase = base;
2743
+ for (let j = 0; force.forceReduce() && j < 10; j++) {
2744
+ if (verbose)
2745
+ console.log(forceBase + this.stackID(force) + " (via force-reduce)");
2746
+ let done = this.advanceFully(force, newStacks);
2747
+ if (done)
2748
+ break;
2749
+ if (verbose)
2750
+ forceBase = this.stackID(force) + " -> ";
2751
+ }
2752
+ for (let insert of stack.recoverByInsert(token)) {
2753
+ if (verbose)
2754
+ console.log(base + this.stackID(insert) + " (via recover-insert)");
2755
+ this.advanceFully(insert, newStacks);
2756
+ }
2757
+ if (this.stream.end > stack.pos) {
2758
+ if (tokenEnd == stack.pos) {
2759
+ tokenEnd++;
2760
+ token = 0;
2761
+ }
2762
+ stack.recoverByDelete(token, tokenEnd);
2763
+ if (verbose)
2764
+ console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
2765
+ pushStackDedup(stack, newStacks);
2766
+ } else if (!finished || finished.score < stack.score) {
2767
+ finished = stack;
2768
+ }
2769
+ }
2770
+ return finished;
2771
+ }
2772
+ // Convert the stack's buffer to a syntax tree.
2773
+ stackToTree(stack) {
2774
+ stack.close();
2775
+ return Tree.build({
2776
+ buffer: StackBufferCursor.create(stack),
2777
+ nodeSet: this.parser.nodeSet,
2778
+ topID: this.topTerm,
2779
+ maxBufferLength: this.parser.bufferLength,
2780
+ reused: this.reused,
2781
+ start: this.ranges[0].from,
2782
+ length: stack.pos - this.ranges[0].from,
2783
+ minRepeatType: this.parser.minRepeatTerm
2784
+ });
2785
+ }
2786
+ stackID(stack) {
2787
+ let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
2788
+ if (!id)
2789
+ stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
2790
+ return id + stack;
2791
+ }
2792
+ };
2793
+ function pushStackDedup(stack, newStacks) {
2794
+ for (let i = 0; i < newStacks.length; i++) {
2795
+ let other = newStacks[i];
2796
+ if (other.pos == stack.pos && other.sameState(stack)) {
2797
+ if (newStacks[i].score < stack.score)
2798
+ newStacks[i] = stack;
2799
+ return;
2800
+ }
2801
+ }
2802
+ newStacks.push(stack);
2803
+ }
2804
+ var Dialect = class {
2805
+ constructor(source, flags, disabled) {
2806
+ this.source = source;
2807
+ this.flags = flags;
2808
+ this.disabled = disabled;
2809
+ }
2810
+ allows(term) {
2811
+ return !this.disabled || this.disabled[term] == 0;
2812
+ }
2813
+ };
2814
+ var LRParser = class extends Parser {
2815
+ /// @internal
2816
+ constructor(spec) {
2817
+ super();
2818
+ this.wrappers = [];
2819
+ if (spec.version != 14)
2820
+ throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
2821
+ let nodeNames = spec.nodeNames.split(" ");
2822
+ this.minRepeatTerm = nodeNames.length;
2823
+ for (let i = 0; i < spec.repeatNodeCount; i++)
2824
+ nodeNames.push("");
2825
+ let topTerms = Object.keys(spec.topRules).map((r) => spec.topRules[r][1]);
2826
+ let nodeProps = [];
2827
+ for (let i = 0; i < nodeNames.length; i++)
2828
+ nodeProps.push([]);
2829
+ function setProp(nodeID, prop, value) {
2830
+ nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
2831
+ }
2832
+ if (spec.nodeProps)
2833
+ for (let propSpec of spec.nodeProps) {
2834
+ let prop = propSpec[0];
2835
+ if (typeof prop == "string")
2836
+ prop = NodeProp[prop];
2837
+ for (let i = 1; i < propSpec.length; ) {
2838
+ let next = propSpec[i++];
2839
+ if (next >= 0) {
2840
+ setProp(next, prop, propSpec[i++]);
2841
+ } else {
2842
+ let value = propSpec[i + -next];
2843
+ for (let j = -next; j > 0; j--)
2844
+ setProp(propSpec[i++], prop, value);
2845
+ i++;
2846
+ }
2847
+ }
2848
+ }
2849
+ this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
2850
+ name: i >= this.minRepeatTerm ? void 0 : name,
2851
+ id: i,
2852
+ props: nodeProps[i],
2853
+ top: topTerms.indexOf(i) > -1,
2854
+ error: i == 0,
2855
+ skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
2856
+ })));
2857
+ if (spec.propSources)
2858
+ this.nodeSet = this.nodeSet.extend(...spec.propSources);
2859
+ this.strict = false;
2860
+ this.bufferLength = DefaultBufferLength;
2861
+ let tokenArray = decodeArray(spec.tokenData);
2862
+ this.context = spec.context;
2863
+ this.specializerSpecs = spec.specialized || [];
2864
+ this.specialized = new Uint16Array(this.specializerSpecs.length);
2865
+ for (let i = 0; i < this.specializerSpecs.length; i++)
2866
+ this.specialized[i] = this.specializerSpecs[i].term;
2867
+ this.specializers = this.specializerSpecs.map(getSpecializer);
2868
+ this.states = decodeArray(spec.states, Uint32Array);
2869
+ this.data = decodeArray(spec.stateData);
2870
+ this.goto = decodeArray(spec.goto);
2871
+ this.maxTerm = spec.maxTerm;
2872
+ this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
2873
+ this.topRules = spec.topRules;
2874
+ this.dialects = spec.dialects || {};
2875
+ this.dynamicPrecedences = spec.dynamicPrecedences || null;
2876
+ this.tokenPrecTable = spec.tokenPrec;
2877
+ this.termNames = spec.termNames || null;
2878
+ this.maxNode = this.nodeSet.types.length - 1;
2879
+ this.dialect = this.parseDialect();
2880
+ this.top = this.topRules[Object.keys(this.topRules)[0]];
2881
+ }
2882
+ createParse(input, fragments, ranges) {
2883
+ let parse = new Parse(this, input, fragments, ranges);
2884
+ for (let w of this.wrappers)
2885
+ parse = w(parse, input, fragments, ranges);
2886
+ return parse;
2887
+ }
2888
+ /// Get a goto table entry @internal
2889
+ getGoto(state, term, loose = false) {
2890
+ let table = this.goto;
2891
+ if (term >= table[0])
2892
+ return -1;
2893
+ for (let pos = table[term + 1]; ; ) {
2894
+ let groupTag = table[pos++], last = groupTag & 1;
2895
+ let target = table[pos++];
2896
+ if (last && loose)
2897
+ return target;
2898
+ for (let end = pos + (groupTag >> 1); pos < end; pos++)
2899
+ if (table[pos] == state)
2900
+ return target;
2901
+ if (last)
2902
+ return -1;
2903
+ }
2904
+ }
2905
+ /// Check if this state has an action for a given terminal @internal
2906
+ hasAction(state, terminal) {
2907
+ let data = this.data;
2908
+ for (let set = 0; set < 2; set++) {
2909
+ for (let i = this.stateSlot(
2910
+ state,
2911
+ set ? 2 : 1
2912
+ /* ParseState.Actions */
2913
+ ), next; ; i += 3) {
2914
+ if ((next = data[i]) == 65535) {
2915
+ if (data[i + 1] == 1)
2916
+ next = data[i = pair(data, i + 2)];
2917
+ else if (data[i + 1] == 2)
2918
+ return pair(data, i + 2);
2919
+ else
2920
+ break;
2921
+ }
2922
+ if (next == terminal || next == 0)
2923
+ return pair(data, i + 1);
2924
+ }
2925
+ }
2926
+ return 0;
2927
+ }
2928
+ /// @internal
2929
+ stateSlot(state, slot) {
2930
+ return this.states[state * 6 + slot];
2931
+ }
2932
+ /// @internal
2933
+ stateFlag(state, flag) {
2934
+ return (this.stateSlot(
2935
+ state,
2936
+ 0
2937
+ /* ParseState.Flags */
2938
+ ) & flag) > 0;
2939
+ }
2940
+ /// @internal
2941
+ validAction(state, action) {
2942
+ return !!this.allActions(state, (a) => a == action ? true : null);
2943
+ }
2944
+ /// @internal
2945
+ allActions(state, action) {
2946
+ let deflt = this.stateSlot(
2947
+ state,
2948
+ 4
2949
+ /* ParseState.DefaultReduce */
2950
+ );
2951
+ let result = deflt ? action(deflt) : void 0;
2952
+ for (let i = this.stateSlot(
2953
+ state,
2954
+ 1
2955
+ /* ParseState.Actions */
2956
+ ); result == null; i += 3) {
2957
+ if (this.data[i] == 65535) {
2958
+ if (this.data[i + 1] == 1)
2959
+ i = pair(this.data, i + 2);
2960
+ else
2961
+ break;
2962
+ }
2963
+ result = action(pair(this.data, i + 1));
2964
+ }
2965
+ return result;
2966
+ }
2967
+ /// Get the states that can follow this one through shift actions or
2968
+ /// goto jumps. @internal
2969
+ nextStates(state) {
2970
+ let result = [];
2971
+ for (let i = this.stateSlot(
2972
+ state,
2973
+ 1
2974
+ /* ParseState.Actions */
2975
+ ); ; i += 3) {
2976
+ if (this.data[i] == 65535) {
2977
+ if (this.data[i + 1] == 1)
2978
+ i = pair(this.data, i + 2);
2979
+ else
2980
+ break;
2981
+ }
2982
+ if ((this.data[i + 2] & 65536 >> 16) == 0) {
2983
+ let value = this.data[i + 1];
2984
+ if (!result.some((v, i2) => i2 & 1 && v == value))
2985
+ result.push(this.data[i], value);
2986
+ }
2987
+ }
2988
+ return result;
2989
+ }
2990
+ /// Configure the parser. Returns a new parser instance that has the
2991
+ /// given settings modified. Settings not provided in `config` are
2992
+ /// kept from the original parser.
2993
+ configure(config) {
2994
+ let copy = Object.assign(Object.create(LRParser.prototype), this);
2995
+ if (config.props)
2996
+ copy.nodeSet = this.nodeSet.extend(...config.props);
2997
+ if (config.top) {
2998
+ let info = this.topRules[config.top];
2999
+ if (!info)
3000
+ throw new RangeError(`Invalid top rule name ${config.top}`);
3001
+ copy.top = info;
3002
+ }
3003
+ if (config.tokenizers)
3004
+ copy.tokenizers = this.tokenizers.map((t) => {
3005
+ let found = config.tokenizers.find((r) => r.from == t);
3006
+ return found ? found.to : t;
3007
+ });
3008
+ if (config.specializers) {
3009
+ copy.specializers = this.specializers.slice();
3010
+ copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
3011
+ let found = config.specializers.find((r) => r.from == s.external);
3012
+ if (!found)
3013
+ return s;
3014
+ let spec = Object.assign(Object.assign({}, s), { external: found.to });
3015
+ copy.specializers[i] = getSpecializer(spec);
3016
+ return spec;
3017
+ });
3018
+ }
3019
+ if (config.contextTracker)
3020
+ copy.context = config.contextTracker;
3021
+ if (config.dialect)
3022
+ copy.dialect = this.parseDialect(config.dialect);
3023
+ if (config.strict != null)
3024
+ copy.strict = config.strict;
3025
+ if (config.wrap)
3026
+ copy.wrappers = copy.wrappers.concat(config.wrap);
3027
+ if (config.bufferLength != null)
3028
+ copy.bufferLength = config.bufferLength;
3029
+ return copy;
3030
+ }
3031
+ /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
3032
+ /// are registered for this parser.
3033
+ hasWrappers() {
3034
+ return this.wrappers.length > 0;
3035
+ }
3036
+ /// Returns the name associated with a given term. This will only
3037
+ /// work for all terms when the parser was generated with the
3038
+ /// `--names` option. By default, only the names of tagged terms are
3039
+ /// stored.
3040
+ getName(term) {
3041
+ return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
3042
+ }
3043
+ /// The eof term id is always allocated directly after the node
3044
+ /// types. @internal
3045
+ get eofTerm() {
3046
+ return this.maxNode + 1;
3047
+ }
3048
+ /// The type of top node produced by the parser.
3049
+ get topNode() {
3050
+ return this.nodeSet.types[this.top[1]];
3051
+ }
3052
+ /// @internal
3053
+ dynamicPrecedence(term) {
3054
+ let prec = this.dynamicPrecedences;
3055
+ return prec == null ? 0 : prec[term] || 0;
3056
+ }
3057
+ /// @internal
3058
+ parseDialect(dialect) {
3059
+ let values = Object.keys(this.dialects), flags = values.map(() => false);
3060
+ if (dialect)
3061
+ for (let part of dialect.split(" ")) {
3062
+ let id = values.indexOf(part);
3063
+ if (id >= 0)
3064
+ flags[id] = true;
3065
+ }
3066
+ let disabled = null;
3067
+ for (let i = 0; i < values.length; i++)
3068
+ if (!flags[i]) {
3069
+ for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535; )
3070
+ (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
3071
+ }
3072
+ return new Dialect(dialect, flags, disabled);
3073
+ }
3074
+ /// Used by the output of the parser generator. Not available to
3075
+ /// user code. @hide
3076
+ static deserialize(spec) {
3077
+ return new LRParser(spec);
3078
+ }
3079
+ };
3080
+ function pair(data, off) {
3081
+ return data[off] | data[off + 1] << 16;
3082
+ }
3083
+ function findFinished(stacks) {
3084
+ let best = null;
3085
+ for (let stack of stacks) {
3086
+ let stopped = stack.p.stoppedAt;
3087
+ if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
3088
+ stack.state,
3089
+ 2
3090
+ /* StateFlag.Accepting */
3091
+ ) && (!best || best.score < stack.score))
3092
+ best = stack;
3093
+ }
3094
+ return best;
3095
+ }
3096
+ function getSpecializer(spec) {
3097
+ if (spec.external) {
3098
+ let mask = spec.extend ? 1 : 0;
3099
+ return (value, stack) => spec.external(value, stack) << 1 | mask;
3100
+ }
3101
+ return spec.get;
30
3102
  }
31
- `;At(Hr);var $r=o=>(...e)=>[o,...e].join("-"),jr=$r("saltIcon"),Gr=1,Rt=(0,Nt.forwardRef)(function({children:e,className:t,size:r=Gr,style:n,...i},s){let l={...n,"--saltIcon-size-multiplier":`${r}`};return(0,Ke.jsx)("svg",{className:Tt(jr(),t),style:l,role:"img",...i,ref:s,children:(0,Ke.jsx)("g",{"aria-hidden":!0,children:e})})});var ye=require("react/jsx-runtime"),Et=require("react");var Je=(0,Et.forwardRef)(function(e,t){return(0,ye.jsxs)(Rt,{"data-testid":"DeleteIcon","aria-label":"delete",viewBox:"0 0 12 12",ref:t,...e,children:[(0,ye.jsx)("path",{d:"M5 4v6H4V4h1Zm2 0v6H6V4h1Z"}),(0,ye.jsx)("path",{fillRule:"evenodd",d:"M4 0a1 1 0 0 0-1 1v1H0v1h1v7a2 2 0 0 0 2 2h5.25A1.75 1.75 0 0 0 10 10.25V3h1V2H8V1a1 1 0 0 0-1-1H4Zm5 3H2v7a1 1 0 0 0 1 1h5.25a.75.75 0 0 0 .75-.75V3ZM7 2H4v-.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 .5.5V2Z",clipRule:"evenodd"})]})});var fe=require("@heswell/salt-lab");var P=require("@vuu-ui/vuu-utils"),D="and",Me="=",Xr=">",Zr="<",Dt="or",et="starts",Yr="ends",Mt="in",Bt=(o,e=[])=>(o&&((0,P.isMultiClauseFilter)(o)?o.filters.forEach(t=>e.push(...Bt(t))):e.push(o)),e),qr={combineWith:"and"},ve=(o,e,{combineWith:t=D}=qr)=>{var r;if(rt(e))(0,P.isMultiClauseFilter)(e)||(o=tt(o,{name:e.column}));else if(Kr(e))return(0,P.isMultiClauseFilter)(e),tt(o,{name:(r=e.column)!=null?r:""});if(!o)return e;if(!e)return o;if(o.op===D&&e.op===D)return{op:D,filters:to(o.filters,e.filters)};if(o.op===D){let n=Jr(o.filters,e);return n.length>1?{op:D,filters:n}:n[0]}return e.op===D?{op:D,filters:e.filters.concat(o)}:Be(o,e,!0)?e:Vt(o,e)?eo(o,e):{op:t,filters:[o,e]}},rt=o=>o?(0,P.isInFilter)(o)&&o.values.length===0?!0:(0,P.isAndFilter)(o)&&o.filters.some(e=>rt(e)):!1,Kr=o=>o?o.op===et&&o.value===""?!0:o.op===et&&o.value==="":!1,Jr=(o,e)=>o.concat(e),eo=(o,e)=>rt(e)?e:(0,P.isInFilter)(o)&&(0,P.isInFilter)(e)?{...o,values:[...o.values,...e.values.filter(t=>!o.values.includes(t))]}:(0,P.isInFilter)(o)&&e.op===Me?{...o,values:o.values.concat([e.value])}:o.op===Me&&e.op===Me?{column:o.column,op:Mt,values:[o.value,e.value]}:e,to=(o,e)=>{let t=({op:i},{op:s})=>i===s||i[0]===s[0],r=(i,s)=>i.column===s.column&&t(i,s),n=i=>e.some(s=>r(i,s))===!1;return o.filter(n).concat(e)},ro=(o,e)=>{if(Be(o,e,!0))return null;if(o.op!==D)throw Error(`removeFilter cannot remove ${JSON.stringify(e)} from ${JSON.stringify(o)}`);let t=o.filters.filter(r=>!Be(r,e));return t.length>0?{type:D,filters:t}:null},oo=(o,e)=>{if(!e)return[void 0,void 0];if(e.column===o)return[e,void 0];if(e.op!==D)return[void 0,e];let[[t=void 0],r]=(0,P.partition)(e.filters,n=>n.column===o);return r.length===1?[t,r[0]]:[t,{op:D,filters:r}]},zt=(o,e)=>(0,P.isMultiClauseFilter)(o)?{op:o.op,filters:o.filters.map(t=>zt(t,e))}:{...o,column:e},Qt=(o,e)=>{if(!o)return!1;let{op:t,column:r}=o;switch(t){case D:case Dt:return o.filters!=null&&o.filters.some(n=>Qt(n,e));default:return r===e.name}},tt=(o,e)=>{let t=e.name;if(o&&o.column!==t){if((0,P.isAndFilter)(o)||(0,P.isOrFilter)(o)){let{op:r}=o,i=o.filters.filter(s=>s.column!==t);switch(i.length){case 0:return;case 1:return i[0];default:return{op:r,filters:i}}}return o}},Vt=(o,e)=>o.column===e.column&&(o.op==="="||o.op==="in")&&(e.op==="="||e.op==="in"),no=(o,e)=>{if(o===e)return!0;if(o.length===e.length){let t=o.slice().sort(),r=e.slice().sort();return t.join("|")===r.join("|")}return!1},Be=(o,e,t=!1)=>t?o&&e&&Vt(o,e)?o.op===e.op&&((0,P.isSingleValueFilter)(o)&&(0,P.isSingleValueFilter)(e)&&o.value===e.value||(0,P.isMultiValueFilter)(o)&&(0,P.isMultiValueFilter)(e)&&no(o.values,e.values)):!1:!0,Lt=(o,e,t)=>{if(o&&e){if(t==="replace")return e;if(o.op==="and")return{...o,filters:o.filters.concat(e)};let{column:r}=e;if(r&&(e.column?(0,P.extractFilterForColumn)(o,r):void 0)&&r){let i=tt(o,{name:r});return Lt(i,e,"add")}return{op:"and",filters:[o,e]}}return e||o};var Ce=o=>/\.\.\.$/.test(o),_t=(o,e,t)=>{if(e.length!==0){if(t){let r=e[0].substring(0,e[0].length-3);return{column:o,op:"starts",value:`"${r}"`}}return{column:o,op:"in",values:e.map(r=>`"${r}"`)}}},ot=(o,e,t)=>{let r=e===void 0?void 0:{column:o,op:">",value:e-1},n=t===void 0?void 0:{column:o,op:"<",value:t+1};return n===void 0?r:ve(r,n,{combineWith:"and"})};var se=require("react/jsx-runtime"),Ut=({defaultTypeaheadParams:o,filterValues:e,onChange:t})=>{var s,l;let r=o[1],n=a=>{let u=parseFloat(a.target.value),f={start:isNaN(u)?void 0:u,end:e==null?void 0:e.end},h=ot(r,f.start,f.end);t(f,h)},i=a=>{let u=parseFloat(a.target.value),f={start:e==null?void 0:e.start,end:isNaN(u)?void 0:u},h=ot(r,f.start,f.end);t(f,h)};return(0,se.jsxs)("div",{style:{display:"flex",flexDirection:"row"},children:[(0,se.jsx)(fe.ToolbarField,{label:"From",children:(0,se.jsx)(fe.Input,{onChange:n,value:((s=e==null?void 0:e.start)==null?void 0:s.toString())||"",type:"number"})}),(0,se.jsx)(fe.ToolbarField,{label:"To",children:(0,se.jsx)(fe.Input,{onChange:i,value:((l=e==null?void 0:e.end)==null?void 0:l.toString())||"",type:"number"})})]})};var Wt=require("@vuu-ui/vuu-data-react"),Ht=require("@heswell/salt-lab"),re=require("react");var jt=require("react/jsx-runtime"),$t=({defaultTypeaheadParams:o,filterValues:e=[],onChange:t})=>{let[r,n]=o,[i,s]=(0,re.useState)(""),[l,a]=(0,re.useState)([]),u=(0,Wt.useTypeaheadSuggestions)();(0,re.useEffect)(()=>{let c=i?[r,n,i]:o,p=!0;return u(c).then(d=>{p&&(Ce(e[0])&&d.unshift(e[0]),i&&d.unshift(`${i}...`),d.concat(e),a(d))}),()=>{p=!1}},[e,i,n,r,u,o]);let f=(0,re.useCallback)(c=>{let p=c.target.value;s(p)},[]),h=(0,re.useCallback)((c,p)=>{if(s(""),p===null)return;p.some(Ce)&&(p=p.filter(Ce).slice(-1));let d=_t(n,p,Ce(p[0]));t(p,d)},[n,t]);return(0,jt.jsx)(Ht.ComboBoxDeprecated,{multiSelect:!0,onInputChange:f,onChange:h,source:l,style:{minWidth:200},inputValue:i,selectedItem:e},n)};var Gt=require("react"),ze=require("@heswell/salt-lab"),ke=require("react/jsx-runtime"),Xt=o=>(0,ke.jsx)(io,{...o}),io=(0,Gt.memo)(function({item:e,itemTextHighlightPattern:t,...r}){return(0,ke.jsx)(ze.ListItem,{...r,children:(0,ke.jsx)("span",{style:{marginLeft:10},children:(0,ke.jsx)(ze.Highlighter,{matchPattern:t,text:e==null?void 0:e.name})})})});var Zt=require("@vuu-ui/vuu-utils"),G=require("react");var nt=(o,e,t)=>o.filter(r=>r[t]!==e[t]).concat(e),Yt=o=>{var F,T;let[e,t]=(0,G.useState)(""),[r,n]=(0,G.useState)([]),[i,s]=(0,G.useState)([]),[l,a]=(0,G.useState)([]),u=()=>{t(""),s([]),a([]),n([]),o({filter:""})},f=(0,G.useCallback)(S=>{let y=nt(r,{column:e,filter:S},"column");n(y);let x=y.map(m=>m.filter).reduce((m,b)=>b===void 0?m:ve(m,b,{combineWith:D}),void 0),C=x===void 0?"":(0,Zt.filterAsQuery)(x);o({filter:C,filterStruct:x})},[e,o,r]),h=(0,G.useCallback)((S,y)=>{a(nt(l,{column:e,value:S},"column")),f(y)},[e,l,f]),c=(0,G.useCallback)((S,y)=>{s(nt(i,{column:e,value:S},"column")),f(y)},[e,i,f]),p=(0,G.useCallback)(S=>t((S==null?void 0:S.name)||""),[]),d=(F=i.filter(S=>S.column===e)[0])==null?void 0:F.value,g=(T=l.filter(S=>S.column===e)[0])==null?void 0:T.value;return{clear:u,selectedColumnName:e,rangeValue:d,typeaheadValue:g,onSelectedColumnChange:p,onRangeChange:c,onTypeaheadChange:h}};var Q=require("react/jsx-runtime"),so=({className:o,table:e,columns:t,onFilterSubmit:r,...n})=>{let{clear:i,onTypeaheadChange:s,onRangeChange:l,onSelectedColumnChange:a,selectedColumnName:u,rangeValue:f,typeaheadValue:h}=Yt(r);return(0,Q.jsxs)(U.Toolbar,{...n,style:{alignItems:"center",height:"36px"},children:[(0,Q.jsx)(U.ToolbarField,{label:"Select a column to filter",labelPlacement:"top",style:{width:180},children:(0,Q.jsx)(U.Dropdown,{source:t,ListItem:Xt,itemToString:p=>p.name,onSelectionChange:(p,d)=>a(d)})}),u&&(()=>{var g;let p=[e,u];switch((g=t.find(F=>F.name===u))==null?void 0:g.serverDataType){case"string":case"char":return(0,Q.jsx)(U.ToolbarField,{label:"Start typing to select a filter",labelPlacement:"top",children:(0,Q.jsx)($t,{defaultTypeaheadParams:p,filterValues:h,onChange:s})});case"int":case"long":case"double":return(0,Q.jsx)(U.ToolbarField,{label:"Select a range",labelPlacement:"top",children:(0,Q.jsx)(Ut,{defaultTypeaheadParams:p,filterValues:f,onChange:l})});default:return(0,Q.jsx)(U.ToolbarField,{children:(0,Q.jsx)(qt.Text,{children:"Data type unsupported"})})}})(),(0,Q.jsx)(U.ToolbarButton,{onClick:i,children:(0,Q.jsx)(Je,{})})]})};var yt=require("@salt-ds/core");var w=require("@vuu-ui/vuu-codemirror");var lo=0,Pe=class{constructor(e,t){this.from=e,this.to=t}},k=class{constructor(e={}){this.id=lo++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=B.match(e)),t=>{let r=e(t);return r===void 0?null:[this,r]}}};k.closedBy=new k({deserialize:o=>o.split(" ")});k.openedBy=new k({deserialize:o=>o.split(" ")});k.group=new k({deserialize:o=>o.split(" ")});k.contextHash=new k({perNode:!0});k.lookAhead=new k({perNode:!0});k.mounted=new k({perNode:!0});var ao=Object.create(null),B=class{constructor(e,t,r,n=0){this.name=e,this.props=t,this.id=r,this.flags=n}static define(e){let t=e.props&&e.props.length?Object.create(null):ao,r=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),n=new B(e.name||"",t,e.id,r);if(e.props){for(let i of e.props)if(Array.isArray(i)||(i=i(n)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[i[0].id]=i[1]}}return n}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(k.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let r in e)for(let n of r.split(" "))t[n]=e[r];return r=>{for(let n=r.prop(k.group),i=-1;i<(n?n.length:0);i++){let s=t[i<0?r.name:n[i]];if(s)return s}}}};B.none=new B("",Object.create(null),0,8);var ce=class{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let t=[];for(let r of this.types){let n=null;for(let i of e){let s=i(r);s&&(n||(n=Object.assign({},r.props)),n[s[0].id]=s[1])}t.push(n?new B(r.name,n,r.id,r.flags):r)}return new ce(t)}},Qe=new WeakMap,Kt=new WeakMap,R;(function(o){o[o.ExcludeBuffers=1]="ExcludeBuffers",o[o.IncludeAnonymous=2]="IncludeAnonymous",o[o.IgnoreMounts=4]="IgnoreMounts",o[o.IgnoreOverlays=8]="IgnoreOverlays"})(R||(R={}));var E=class{constructor(e,t,r,n,i){if(this.type=e,this.children=t,this.positions=r,this.length=n,this.props=null,i&&i.length){this.props=Object.create(null);for(let[s,l]of i)this.props[typeof s=="number"?s:s.id]=l}}toString(){let e=this.prop(k.mounted);if(e&&!e.overlay)return e.tree.toString();let t="";for(let r of this.children){let n=r.toString();n&&(t&&(t+=","),t+=n)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new de(this.topNode,e)}cursorAt(e,t=0,r=0){let n=Qe.get(this)||this.topNode,i=new de(n);return i.moveTo(e,t),Qe.set(this,i._tree),i}get topNode(){return new W(this,0,0,null)}resolve(e,t=0){let r=pe(Qe.get(this)||this.topNode,e,t,!1);return Qe.set(this,r),r}resolveInner(e,t=0){let r=pe(Kt.get(this)||this.topNode,e,t,!0);return Kt.set(this,r),r}iterate(e){let{enter:t,leave:r,from:n=0,to:i=this.length}=e,s=e.mode||0,l=(s&R.IncludeAnonymous)>0;for(let a=this.cursor(s|R.IncludeAnonymous);;){let u=!1;if(a.from<=i&&a.to>=n&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;u=!0}for(;u&&r&&(l||!a.type.isAnonymous)&&r(a),!a.nextSibling();){if(!a.parent())return;u=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:at(B.none,this.children,this.positions,0,this.children.length,0,this.length,(t,r,n)=>new E(this.type,t,r,n,this.propValues),e.makeTree||((t,r,n)=>new E(B.none,t,r,n)))}static build(e){return uo(e)}};E.empty=new E(B.none,[],[],0);var Oe=class{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Oe(this.buffer,this.index)}},K=class{constructor(e,t,r){this.buffer=e,this.length=t,this.set=r}get type(){return B.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],r=this.buffer[e+3],n=this.set.types[t],i=n.name;if(/\W/.test(i)&&!n.isError&&(i=JSON.stringify(i)),e+=4,r==e)return i;let s=[];for(;e<r;)s.push(this.childString(e)),e=this.buffer[e+3];return i+"("+s.join(",")+")"}findChild(e,t,r,n,i){let{buffer:s}=this,l=-1;for(let a=e;a!=t&&!(er(i,n,s[a+1],s[a+2])&&(l=a,r>0));a=s[a+3]);return l}slice(e,t,r){let n=this.buffer,i=new Uint16Array(t-e),s=0;for(let l=e,a=0;l<t;){i[a++]=n[l++],i[a++]=n[l++]-r;let u=i[a++]=n[l++]-r;i[a++]=n[l++]-e,s=Math.max(s,u)}return new K(i,s,this.set)}};function er(o,e,t,r){switch(o){case-2:return t<e;case-1:return r>=e&&t<e;case 0:return t<e&&r>e;case 1:return t<=e&&r>e;case 2:return r>e;case 4:return!0}}function tr(o,e){let t=o.childBefore(e);for(;t;){let r=t.lastChild;if(!r||r.to!=t.to)break;r.type.isError&&r.from==r.to?(o=t,t=r.prevSibling):t=r}return o}function pe(o,e,t,r){for(var n;o.from==o.to||(t<1?o.from>=e:o.from>e)||(t>-1?o.to<=e:o.to<e);){let s=!r&&o instanceof W&&o.index<0?null:o.parent;if(!s)return o;o=s}let i=r?0:R.IgnoreOverlays;if(r)for(let s=o,l=s.parent;l;s=l,l=s.parent)s instanceof W&&s.index<0&&((n=l.enter(e,t,i))===null||n===void 0?void 0:n.from)!=s.from&&(o=l);for(;;){let s=o.enter(e,t,i);if(!s)return o;o=s}}var W=class{constructor(e,t,r,n){this._tree=e,this.from=t,this.index=r,this._parent=n}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,r,n,i=0){for(let s=this;;){for(let{children:l,positions:a}=s._tree,u=t>0?l.length:-1;e!=u;e+=t){let f=l[e],h=a[e]+s.from;if(er(n,r,h,h+f.length)){if(f instanceof K){if(i&R.ExcludeBuffers)continue;let c=f.findChild(0,f.buffer.length,t,r-h,n);if(c>-1)return new X(new it(s,f,e,h),null,c)}else if(i&R.IncludeAnonymous||!f.type.isAnonymous||lt(f)){let c;if(!(i&R.IgnoreMounts)&&f.props&&(c=f.prop(k.mounted))&&!c.overlay)return new W(c.tree,h,e,s);let p=new W(f,h,e,s);return i&R.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?f.children.length-1:0,t,r,n)}}}if(i&R.IncludeAnonymous||!s.type.isAnonymous||(s.index>=0?e=s.index+t:e=t<0?-1:s._parent._tree.children.length,s=s._parent,!s))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,r=0){let n;if(!(r&R.IgnoreOverlays)&&(n=this._tree.prop(k.mounted))&&n.overlay){let i=e-this.from;for(let{from:s,to:l}of n.overlay)if((t>0?s<=i:s<i)&&(t<0?l>=i:l>i))return new W(n.tree,n.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new de(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return pe(this,e,t,!1)}resolveInner(e,t=0){return pe(this,e,t,!0)}enterUnfinishedNodesBefore(e){return tr(this,e)}getChild(e,t=null,r=null){let n=Le(this,e,t,r);return n.length?n[0]:null}getChildren(e,t=null,r=null){return Le(this,e,t,r)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return _e(this,e)}};function Le(o,e,t,r){let n=o.cursor(),i=[];if(!n.firstChild())return i;if(t!=null){for(;!n.type.is(t);)if(!n.nextSibling())return i}for(;;){if(r!=null&&n.type.is(r))return i;if(n.type.is(e)&&i.push(n.node),!n.nextSibling())return r==null?i:[]}}function _e(o,e,t=e.length-1){for(let r=o.parent;t>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(e[t]&&e[t]!=r.name)return!1;t--}}return!0}var it=class{constructor(e,t,r,n){this.parent=e,this.buffer=t,this.index=r,this.start=n}},X=class{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,r){this.context=e,this._parent=t,this.index=r,this.type=e.buffer.set.types[e.buffer.buffer[r]]}child(e,t,r){let{buffer:n}=this.context,i=n.findChild(this.index+4,n.buffer[this.index+3],e,t-this.context.start,r);return i<0?null:new X(this.context,this,i)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,r=0){if(r&R.ExcludeBuffers)return null;let{buffer:n}=this.context,i=n.findChild(this.index+4,n.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new X(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new X(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new X(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new de(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:r}=this.context,n=this.index+4,i=r.buffer[this.index+3];if(i>n){let s=r.buffer[this.index+1];e.push(r.slice(n,i,s)),t.push(0)}return new E(this.type,e,t,this.to-this.from)}resolve(e,t=0){return pe(this,e,t,!1)}resolveInner(e,t=0){return pe(this,e,t,!0)}enterUnfinishedNodesBefore(e){return tr(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,r=null){let n=Le(this,e,t,r);return n.length?n[0]:null}getChildren(e,t=null,r=null){return Le(this,e,t,r)}get node(){return this}matchContext(e){return _e(this,e)}},de=class{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof W)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let r=e._parent;r;r=r._parent)this.stack.unshift(r.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:r,buffer:n}=this.buffer;return this.type=t||n.set.types[n.buffer[e]],this.from=r+n.buffer[e+1],this.to=r+n.buffer[e+2],!0}yield(e){return e?e instanceof W?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,r){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,r,this.mode));let{buffer:n}=this.buffer,i=n.findChild(this.index+4,n.buffer[this.index+3],e,t-this.buffer.start,r);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,r=this.mode){return this.buffer?r&R.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,r))}parent(){if(!this.buffer)return this.yieldNode(this.mode&R.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&R.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,r=this.stack.length-1;if(e<0){let n=r<0?0:this.stack[r]+4;if(this.index!=n)return this.yieldBuf(t.findChild(n,this.index,-1,0,4))}else{let n=t.buffer[this.index+3];if(n<(r<0?t.buffer.length:t.buffer[this.stack[r]+3]))return this.yieldBuf(n)}return r<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,r,{buffer:n}=this;if(n){if(e>0){if(this.index<n.buffer.buffer.length)return!1}else for(let i=0;i<this.index;i++)if(n.buffer.buffer[i+3]<this.index)return!1;({index:t,parent:r}=n)}else({index:t,_parent:r}=this._tree);for(;r;{index:t,_parent:r}=r)if(t>-1)for(let i=t+e,s=e<0?-1:r._tree.children.length;i!=s;i+=e){let l=r._tree.children[i];if(this.mode&R.IncludeAnonymous||l instanceof K||!l.type.isAnonymous||lt(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,r=0;if(e&&e.context==this.buffer)e:for(let n=this.index,i=this.stack.length;i>=0;){for(let s=e;s;s=s._parent)if(s.index==n){if(n==this.index)return s;t=s,r=i+1;break e}n=this.stack[--i]}for(let n=r;n<this.stack.length;n++)t=new X(this.buffer,t,this.stack[n]);return this.bufferNode=new X(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let r=0;;){let n=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){r++;continue}this.type.isAnonymous||(n=!0)}for(;n&&t&&t(this),n=this.type.isAnonymous,!this.nextSibling();){if(!r)return;this.parent(),r--,n=!0}}}matchContext(e){if(!this.buffer)return _e(this.node,e);let{buffer:t}=this.buffer,{types:r}=t.set;for(let n=e.length-1,i=this.stack.length-1;n>=0;i--){if(i<0)return _e(this.node,e,n);let s=r[t.buffer[this.stack[i]]];if(!s.isAnonymous){if(e[n]&&e[n]!=s.name)return!1;n--}}return!0}};function lt(o){return o.children.some(e=>e instanceof K||!e.type.isAnonymous||lt(e))}function uo(o){var e;let{buffer:t,nodeSet:r,maxBufferLength:n=1024,reused:i=[],minRepeatType:s=r.types.length}=o,l=Array.isArray(t)?new Oe(t,t.length):t,a=r.types,u=0,f=0;function h(x,C,m,b,A){let{id:v,start:I,end:O,size:M}=l,L=f;for(;M<0;)if(l.next(),M==-1){let te=i[v];m.push(te),b.push(I-x);return}else if(M==-3){u=v;return}else if(M==-4){f=v;return}else throw new RangeError(`Unrecognized record size: ${M}`);let ue=a[v],ee,Y,vt=I-x;if(O-I<=n&&(Y=g(l.pos-C,A))){let te=new Uint16Array(Y.size-Y.skip),_=l.pos-Y.size,q=te.length;for(;l.pos>_;)q=F(Y.start,te,q);ee=new K(te,O-Y.start,r),vt=Y.start-x}else{let te=l.pos-M;l.next();let _=[],q=[],ie=v>=s?v:-1,he=0,Ee=O;for(;l.pos>te;)ie>=0&&l.id==ie&&l.size>=0?(l.end<=Ee-n&&(p(_,q,I,he,l.end,Ee,ie,L),he=_.length,Ee=l.end),l.next()):h(I,te,_,q,ie);if(ie>=0&&he>0&&he<_.length&&p(_,q,I,he,I,Ee,ie,L),_.reverse(),q.reverse(),ie>-1&&he>0){let Ct=c(ue);ee=at(ue,_,q,0,_.length,0,O-I,Ct,Ct)}else ee=d(ue,_,q,O-I,L-O)}m.push(ee),b.push(vt)}function c(x){return(C,m,b)=>{let A=0,v=C.length-1,I,O;if(v>=0&&(I=C[v])instanceof E){if(!v&&I.type==x&&I.length==b)return I;(O=I.prop(k.lookAhead))&&(A=m[v]+I.length+O)}return d(x,C,m,b,A)}}function p(x,C,m,b,A,v,I,O){let M=[],L=[];for(;x.length>b;)M.push(x.pop()),L.push(C.pop()+m-A);x.push(d(r.types[I],M,L,v-A,O-v)),C.push(A-m)}function d(x,C,m,b,A=0,v){if(u){let I=[k.contextHash,u];v=v?[I].concat(v):[I]}if(A>25){let I=[k.lookAhead,A];v=v?[I].concat(v):[I]}return new E(x,C,m,b,v)}function g(x,C){let m=l.fork(),b=0,A=0,v=0,I=m.end-n,O={size:0,start:0,skip:0};e:for(let M=m.pos-x;m.pos>M;){let L=m.size;if(m.id==C&&L>=0){O.size=b,O.start=A,O.skip=v,v+=4,b+=4,m.next();continue}let ue=m.pos-L;if(L<0||ue<M||m.start<I)break;let ee=m.id>=s?4:0,Y=m.start;for(m.next();m.pos>ue;){if(m.size<0)if(m.size==-3)ee+=4;else break e;else m.id>=s&&(ee+=4);m.next()}A=Y,b+=L,v+=ee}return(C<0||b==x)&&(O.size=b,O.start=A,O.skip=v),O.size>4?O:void 0}function F(x,C,m){let{id:b,start:A,end:v,size:I}=l;if(l.next(),I>=0&&b<s){let O=m;if(I>4){let M=l.pos-(I-4);for(;l.pos>M;)m=F(x,C,m)}C[--m]=O,C[--m]=v-x,C[--m]=A-x,C[--m]=b}else I==-3?u=b:I==-4&&(f=b);return m}let T=[],S=[];for(;l.pos>0;)h(o.start||0,o.bufferStart||0,T,S,-1);let y=(e=o.length)!==null&&e!==void 0?e:T.length?S[0]+T[0].length:0;return new E(a[o.topID],T.reverse(),S.reverse(),y)}var Jt=new WeakMap;function Ve(o,e){if(!o.isAnonymous||e instanceof K||e.type!=o)return 1;let t=Jt.get(e);if(t==null){t=1;for(let r of e.children){if(r.type!=o||!(r instanceof E)){t=1;break}t+=Ve(o,r)}Jt.set(e,t)}return t}function at(o,e,t,r,n,i,s,l,a){let u=0;for(let d=r;d<n;d++)u+=Ve(o,e[d]);let f=Math.ceil(u*1.5/8),h=[],c=[];function p(d,g,F,T,S){for(let y=F;y<T;){let x=y,C=g[y],m=Ve(o,d[y]);for(y++;y<T;y++){let b=Ve(o,d[y]);if(m+b>=f)break;m+=b}if(y==x+1){if(m>f){let b=d[x];p(b.children,b.positions,0,b.children.length,g[x]+S);continue}h.push(d[x])}else{let b=g[y-1]+d[y-1].length-C;h.push(at(o,d,g,x,y,C,b,null,a))}c.push(C+S-i)}}return p(e,t,r,n,0),(l||a)(h,c,s)}var Ue=class{startParse(e,t,r){return typeof e=="string"&&(e=new st(e)),r=r?r.length?r.map(n=>new Pe(n.from,n.to)):[new Pe(0,0)]:[new Pe(0,e.length)],this.createParse(e,t||[],r)}parse(e,t,r){let n=this.startParse(e,t,r);for(;;){let i=n.advance();if(i)return i}}},st=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Sn=new k({perNode:!0});var ge=class{constructor(e,t,r,n,i,s,l,a,u,f=0,h){this.p=e,this.stack=t,this.state=r,this.reducePos=n,this.pos=i,this.score=s,this.buffer=l,this.bufferBase=a,this.curContext=u,this.lookAhead=f,this.parent=h}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,r=0){let n=e.parser.context;return new ge(e,[],t,r,r,0,[],0,n?new We(n,n.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let r=e>>19,n=e&65535,{parser:i}=this.p,s=i.dynamicPrecedence(n);if(s&&(this.score+=s),r==0){this.pushState(i.getGoto(this.state,n,!0),this.reducePos),n<i.minRepeatTerm&&this.storeNode(n,this.reducePos,this.reducePos,4,!0),this.reduceContext(n,this.reducePos);return}let l=this.stack.length-(r-1)*3-(e&262144?6:0),a=l?this.stack[l-2]:this.p.ranges[0].from,u=this.reducePos-a;u>=2e3&&!(!((t=this.p.parser.nodeSet.types[n])===null||t===void 0)&&t.isAnonymous)&&(a==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=u):this.p.lastBigReductionSize<u&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=a,this.p.lastBigReductionSize=u));let f=l?this.stack[l-1]:0,h=this.bufferBase+this.buffer.length-f;if(n<i.minRepeatTerm||e&131072){let c=i.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(n,a,c,h+4,!0)}if(e&262144)this.state=this.stack[l];else{let c=this.stack[l-3];this.state=i.getGoto(c,n,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(n,a)}storeNode(e,t,r,n=4,i=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let s=this,l=this.buffer.length;if(l==0&&s.parent&&(l=s.bufferBase-s.parent.bufferBase,s=s.parent),l>0&&s.buffer[l-4]==0&&s.buffer[l-1]>-1){if(t==r)return;if(s.buffer[l-2]>=t){s.buffer[l-2]=r;return}}}if(!i||this.pos==r)this.buffer.push(e,t,r,n);else{let s=this.buffer.length;if(s>0&&this.buffer[s-4]!=0)for(;s>0&&this.buffer[s-2]>r;)this.buffer[s]=this.buffer[s-4],this.buffer[s+1]=this.buffer[s-3],this.buffer[s+2]=this.buffer[s-2],this.buffer[s+3]=this.buffer[s-1],s-=4,n>4&&(n-=4);this.buffer[s]=e,this.buffer[s+1]=t,this.buffer[s+2]=r,this.buffer[s+3]=n}}shift(e,t,r){let n=this.pos;if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,r,4);else{let i=e,{parser:s}=this.p;(r>this.pos||t<=s.maxNode)&&(this.pos=r,s.stateFlag(i,1)||(this.reducePos=r)),this.pushState(i,n),this.shiftContext(t,n),t<=s.maxNode&&this.buffer.push(t,n,r,4)}}apply(e,t,r){e&65536?this.reduce(e):this.shift(e,t,r)}useNode(e,t){let r=this.p.reused.length-1;(r<0||this.p.reused[r]!=e)&&(this.p.reused.push(e),r++);let n=this.pos;this.reducePos=this.pos=n+e.length,this.pushState(t,n),this.buffer.push(r,n,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let r=e.buffer.slice(t),n=e.bufferBase+t;for(;e&&n==e.bufferBase;)e=e.parent;return new ge(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,r,n,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let r=e<=this.p.parser.maxNode;r&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,r?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new ht(this);;){let r=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(r==0)return!1;if(!(r&65536))return!0;t.reduce(r)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>4<<1||this.stack.length>=120){let n=[];for(let i=0,s;i<t.length;i+=2)(s=t[i+1])!=this.state&&this.p.parser.hasAction(s,e)&&n.push(t[i],s);if(this.stack.length<120)for(let i=0;n.length<4<<1&&i<t.length;i+=2){let s=t[i+1];n.some((l,a)=>a&1&&l==s)||n.push(t[i],s)}t=n}let r=[];for(let n=0;n<t.length&&r.length<4;n+=2){let i=t[n+1];if(i==this.state)continue;let s=this.split();s.pushState(i,this.pos),s.storeNode(0,s.pos,s.pos,4,!0),s.shiftContext(t[n],this.pos),s.score-=200,r.push(s)}return r}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if(!(t&65536))return!1;if(!e.validAction(this.state,t)){let r=t>>19,n=t&65535,i=this.stack.length-r*3;if(i<0||e.getGoto(this.stack[i],n,!1)<0){let s=this.findForcedReduction();if(s==null)return!1;t=s}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],r=(n,i)=>{if(!t.includes(n))return t.push(n),e.allActions(n,s=>{if(!(s&393216))if(s&65536){let l=(s>>19)-i;if(l>1){let a=s&65535,u=this.stack.length-l*3;if(u>=0&&e.getGoto(this.stack[u],a,!1)>=0)return l<<19|65536|a}}else{let l=r(s,i+1);if(l!=null)return l}})};return r(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new We(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){e>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},We=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},rr;(function(o){o[o.Insert=200]="Insert",o[o.Delete=190]="Delete",o[o.Reduce=100]="Reduce",o[o.MaxNext=4]="MaxNext",o[o.MaxInsertStackDepth=300]="MaxInsertStackDepth",o[o.DampenInsertStackDepth=120]="DampenInsertStackDepth",o[o.MinBigReduction=2e3]="MinBigReduction"})(rr||(rr={}));var ht=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,r=e>>19;r==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(r-1)*3;let n=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=n}},xe=class{constructor(e,t,r){this.stack=e,this.pos=t,this.index=r,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new xe(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new xe(this.stack,this.pos,this.index)}};function Fe(o,e=Uint16Array){if(typeof o!="string")return o;let t=null;for(let r=0,n=0;r<o.length;){let i=0;for(;;){let s=o.charCodeAt(r++),l=!1;if(s==126){i=65535;break}s>=92&&s--,s>=34&&s--;let a=s-32;if(a>=46&&(a-=46,l=!0),i+=a,l)break;i*=46}t?t[n++]=i:t=new e(i)}return t}var me=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},or=new me,ft=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=or,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let r=this.range,n=this.rangeIndex,i=this.pos+e;for(;i<r.from;){if(!n)return null;let s=this.ranges[--n];i-=r.from-s.to,r=s}for(;t<0?i>r.to:i>=r.to;){if(n==this.ranges.length-1)return null;let s=this.ranges[++n];i+=s.from-r.to,r=s}return i}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,r,n;if(t>=0&&t<this.chunk.length)r=this.pos+e,n=this.chunk.charCodeAt(t);else{let i=this.resolveOffset(e,1);if(i==null)return-1;if(r=i,r>=this.chunk2Pos&&r<this.chunk2Pos+this.chunk2.length)n=this.chunk2.charCodeAt(r-this.chunk2Pos);else{let s=this.rangeIndex,l=this.range;for(;l.to<=r;)l=this.ranges[++s];this.chunk2=this.input.chunk(this.chunk2Pos=r),r+this.chunk2.length>l.to&&(this.chunk2=this.chunk2.slice(0,l.to-r)),n=this.chunk2.charCodeAt(0)}}return r>=this.token.lookAhead&&(this.token.lookAhead=r+1),n}acceptToken(e,t=0){let r=t?this.resolveOffset(t,-1):this.pos;if(r==null||r<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=e,this.token.end=r}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=or,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let r="";for(let n of this.ranges){if(n.from>=t)break;n.to>e&&(r+=this.input.read(Math.max(n.from,e),Math.min(n.to,t)))}return r}},oe=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:r}=t.p;hr(this.data,e,t,this.id,r.data,r.tokenPrecTable)}};oe.prototype.contextual=oe.prototype.fallback=oe.prototype.extend=!1;var ct=class{constructor(e,t,r){this.precTable=t,this.elseToken=r,this.data=typeof e=="string"?Fe(e):e}token(e,t){let r=e.pos,n=0;for(;;){let i=e.next<0,s=e.resolveOffset(1,1);if(hr(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(i||n++,s==null)break;e.reset(s,e.token)}n&&(e.reset(r,e.token),e.acceptToken(this.elseToken,n))}};ct.prototype.contextual=oe.prototype.fallback=oe.prototype.extend=!1;function hr(o,e,t,r,n,i){let s=0,l=1<<r,{dialect:a}=t.p.parser;e:for(;l&o[s];){let u=o[s+1];for(let p=s+3;p<u;p+=2)if((o[p+1]&l)>0){let d=o[p];if(a.allows(d)&&(e.token.value==-1||e.token.value==d||fo(d,e.token.value,n,i))){e.acceptToken(d);break}}let f=e.next,h=0,c=o[s+2];if(e.next<0&&c>h&&o[u+c*3-3]==65535&&o[u+c*3-3]==65535){s=o[u+c*3-1];continue e}for(;h<c;){let p=h+c>>1,d=u+p+(p<<1),g=o[d],F=o[d+1]||65536;if(f<g)c=p;else if(f>=F)h=p+1;else{s=o[d+2],e.advance();continue e}}break}}function nr(o,e,t){for(let r=e,n;(n=o[r])!=65535;r++)if(n==t)return r-e;return-1}function fo(o,e,t,r){let n=nr(t,r,e);return n<0||nr(t,r,o)<n}var H=typeof process<"u"&&process.env&&/\bparse\b/.test(process.env.LOG),ut=null,ir;(function(o){o[o.Margin=25]="Margin"})(ir||(ir={}));function sr(o,e,t){let r=o.cursor(R.IncludeAnonymous);for(r.moveTo(e);;)if(!(t<0?r.childBefore(e):r.childAfter(e)))for(;;){if((t<0?r.to<e:r.from>e)&&!r.type.isError)return t<0?Math.max(0,Math.min(r.to-1,e-25)):Math.min(o.length,Math.max(r.from+1,e+25));if(t<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return t<0?0:o.length}}var pt=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?sr(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?sr(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let r=this.trees[t],n=this.index[t];if(n==r.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let i=r.children[n],s=this.start[t]+r.positions[n];if(s>e)return this.nextStart=s,null;if(i instanceof E){if(s==e){if(s<this.safeFrom)return null;let l=s+i.length;if(l<=this.safeTo){let a=i.prop(k.lookAhead);if(!a||l+a<this.fragment.to)return i}}this.index[t]++,s+i.length>=Math.max(this.safeFrom,e)&&(this.trees.push(i),this.start.push(s),this.index.push(0))}else this.index[t]++,this.nextStart=s+i.length}}},dt=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(r=>new me)}getActions(e){let t=0,r=null,{parser:n}=e.p,{tokenizers:i}=n,s=n.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let u=0;u<i.length;u++){if(!(1<<u&s))continue;let f=i[u],h=this.tokens[u];if(!(r&&!f.fallback)&&((f.contextual||h.start!=e.pos||h.mask!=s||h.context!=l)&&(this.updateCachedToken(h,f,e),h.mask=s,h.context=l),h.lookAhead>h.end+25&&(a=Math.max(h.lookAhead,a)),h.value!=0)){let c=t;if(h.extended>-1&&(t=this.addActions(e,h.extended,h.end,t)),t=this.addActions(e,h.value,h.end,t),!f.extend&&(r=h,t>c))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!r&&e.pos==this.stream.end&&(r=new me,r.value=e.p.parser.eofTerm,r.start=r.end=e.pos,t=this.addActions(e,r.value,r.end,t)),this.mainToken=r,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new me,{pos:r,p:n}=e;return t.start=r,t.end=Math.min(r+1,n.stream.end),t.value=r==n.stream.end?n.parser.eofTerm:0,t}updateCachedToken(e,t,r){let n=this.stream.clipPos(r.pos);if(t.token(this.stream.reset(n,e),r),e.value>-1){let{parser:i}=r.p;for(let s=0;s<i.specialized.length;s++)if(i.specialized[s]==e.value){let l=i.specializers[s](this.stream.read(e.start,e.end),r);if(l>=0&&r.p.parser.dialect.allows(l>>1)){l&1?e.extended=l>>1:e.value=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(n+1)}putAction(e,t,r,n){for(let i=0;i<n;i+=3)if(this.actions[i]==e)return n;return this.actions[n++]=e,this.actions[n++]=t,this.actions[n++]=r,n}addActions(e,t,r,n){let{state:i}=e,{parser:s}=e.p,{data:l}=s;for(let a=0;a<2;a++)for(let u=s.stateSlot(i,a?2:1);;u+=3){if(l[u]==65535)if(l[u+1]==1)u=J(l,u+2);else{n==0&&l[u+1]==2&&(n=this.putAction(J(l,u+2),t,r,n));break}l[u]==t&&(n=this.putAction(J(l,u+1),t,r,n))}return n}},lr;(function(o){o[o.Distance=5]="Distance",o[o.MaxRemainingPerStep=3]="MaxRemainingPerStep",o[o.MinBufferLengthPrune=500]="MinBufferLengthPrune",o[o.ForceReduceLimit=10]="ForceReduceLimit",o[o.CutDepth=15e3]="CutDepth",o[o.CutTo=9e3]="CutTo",o[o.MaxLeftAssociativeReductionCount=300]="MaxLeftAssociativeReductionCount",o[o.MaxStackCount=12]="MaxStackCount"})(lr||(lr={}));var mt=class{constructor(e,t,r,n){this.parser=e,this.input=t,this.ranges=n,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new ft(t,n),this.tokens=new dt(e,this.stream),this.topTerm=e.top[1];let{from:i}=n[0];this.stacks=[ge.start(this,e.top[0],i)],this.fragments=r.length&&this.stream.end-i>e.bufferLength*4?new pt(r,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,r=this.stacks=[],n,i;if(this.bigReductionCount>300&&e.length==1){let[s]=e;for(;s.forceReduce()&&s.stack.length&&s.stack[s.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let s=0;s<e.length;s++){let l=e[s];for(;;){if(this.tokens.mainToken=null,l.pos>t)r.push(l);else{if(this.advanceStack(l,r,e))continue;{n||(n=[],i=[]),n.push(l);let a=this.tokens.getMainToken(l);i.push(a.value,a.end)}}break}}if(!r.length){let s=n&&co(n);if(s)return this.stackToTree(s);if(this.parser.strict)throw H&&n&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&n){let s=this.stoppedAt!=null&&n[0].pos>this.stoppedAt?n[0]:this.runRecovery(n,i,r);if(s)return this.stackToTree(s.forceAll())}if(this.recovering){let s=this.recovering==1?1:this.recovering*3;if(r.length>s)for(r.sort((l,a)=>a.score-l.score);r.length>s;)r.pop();r.some(l=>l.reducePos>t)&&this.recovering--}else if(r.length>1){e:for(let s=0;s<r.length-1;s++){let l=r[s];for(let a=s+1;a<r.length;a++){let u=r[a];if(l.sameState(u)||l.buffer.length>500&&u.buffer.length>500)if((l.score-u.score||l.buffer.length-u.buffer.length)>0)r.splice(a--,1);else{r.splice(s--,1);continue e}}}r.length>12&&r.splice(12,r.length-12)}this.minStackPos=r[0].pos;for(let s=1;s<r.length;s++)r[s].pos<this.minStackPos&&(this.minStackPos=r[s].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}advanceStack(e,t,r){let n=e.pos,{parser:i}=this,s=H?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&n>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let u=e.curContext&&e.curContext.tracker.strict,f=u?e.curContext.hash:0;for(let h=this.fragments.nodeAt(n);h;){let c=this.parser.nodeSet.types[h.type.id]==h.type?i.getGoto(e.state,h.type.id):-1;if(c>-1&&h.length&&(!u||(h.prop(k.contextHash)||0)==f))return e.useNode(h,c),H&&console.log(s+this.stackID(e)+` (via reuse of ${i.getName(h.type.id)})`),!0;if(!(h instanceof E)||h.children.length==0||h.positions[0]>0)break;let p=h.children[0];if(p instanceof E&&h.positions[0]==0)h=p;else break}}let l=i.stateSlot(e.state,4);if(l>0)return e.reduce(l),H&&console.log(s+this.stackID(e)+` (via always-reduce ${i.getName(l&65535)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let u=0;u<a.length;){let f=a[u++],h=a[u++],c=a[u++],p=u==a.length||!r,d=p?e:e.split();if(d.apply(f,h,c),H&&console.log(s+this.stackID(d)+` (via ${f&65536?`reduce of ${i.getName(f&65535)}`:"shift"} for ${i.getName(h)} @ ${n}${d==e?"":", split"})`),p)return!0;d.pos>n?t.push(d):r.push(d)}return!1}advanceFully(e,t){let r=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>r)return ar(e,t),!0}}runRecovery(e,t,r){let n=null,i=!1;for(let s=0;s<e.length;s++){let l=e[s],a=t[s<<1],u=t[(s<<1)+1],f=H?this.stackID(l)+" -> ":"";if(l.deadEnd&&(i||(i=!0,l.restart(),H&&console.log(f+this.stackID(l)+" (restarted)"),this.advanceFully(l,r))))continue;let h=l.split(),c=f;for(let p=0;h.forceReduce()&&p<10&&(H&&console.log(c+this.stackID(h)+" (via force-reduce)"),!this.advanceFully(h,r));p++)H&&(c=this.stackID(h)+" -> ");for(let p of l.recoverByInsert(a))H&&console.log(f+this.stackID(p)+" (via recover-insert)"),this.advanceFully(p,r);this.stream.end>l.pos?(u==l.pos&&(u++,a=0),l.recoverByDelete(a,u),H&&console.log(f+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),ar(l,r)):(!n||n.score<l.score)&&(n=l)}return n}stackToTree(e){return e.close(),E.build({buffer:xe.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(ut||(ut=new WeakMap)).get(e);return t||ut.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function ar(o,e){for(let t=0;t<e.length;t++){let r=e[t];if(r.pos==o.pos&&r.sameState(o)){e[t].score<o.score&&(e[t]=o);return}}e.push(o)}var gt=class{constructor(e,t,r){this.source=e,this.flags=t,this.disabled=r}allows(e){return!this.disabled||this.disabled[e]==0}};var le=class extends Ue{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;l<e.repeatNodeCount;l++)t.push("");let r=Object.keys(e.topRules).map(l=>e.topRules[l][1]),n=[];for(let l=0;l<t.length;l++)n.push([]);function i(l,a,u){n[l].push([a,a.deserialize(String(u))])}if(e.nodeProps)for(let l of e.nodeProps){let a=l[0];typeof a=="string"&&(a=k[a]);for(let u=1;u<l.length;){let f=l[u++];if(f>=0)i(f,a,l[u++]);else{let h=l[u+-f];for(let c=-f;c>0;c--)i(l[u++],a,h);u++}}}this.nodeSet=new ce(t.map((l,a)=>B.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:n[a],top:r.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let s=Fe(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;l<this.specializerSpecs.length;l++)this.specialized[l]=this.specializerSpecs[l].term;this.specializers=this.specializerSpecs.map(ur),this.states=Fe(e.states,Uint32Array),this.data=Fe(e.stateData),this.goto=Fe(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(l=>typeof l=="number"?new oe(s,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,r){let n=new mt(this,e,t,r);for(let i of this.wrappers)n=i(n,e,t,r);return n}getGoto(e,t,r=!1){let n=this.goto;if(t>=n[0])return-1;for(let i=n[t+1];;){let s=n[i++],l=s&1,a=n[i++];if(l&&r)return a;for(let u=i+(s>>1);i<u;i++)if(n[i]==e)return a;if(l)return-1}}hasAction(e,t){let r=this.data;for(let n=0;n<2;n++)for(let i=this.stateSlot(e,n?2:1),s;;i+=3){if((s=r[i])==65535)if(r[i+1]==1)s=r[i=J(r,i+2)];else{if(r[i+1]==2)return J(r,i+2);break}if(s==t||s==0)return J(r,i+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,r=>r==t?!0:null)}allActions(e,t){let r=this.stateSlot(e,4),n=r?t(r):void 0;for(let i=this.stateSlot(e,1);n==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=J(this.data,i+2);else break;n=t(J(this.data,i+1))}return n}nextStates(e){let t=[];for(let r=this.stateSlot(e,1);;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=J(this.data,r+2);else break;if(!(this.data[r+2]&1)){let n=this.data[r+1];t.some((i,s)=>s&1&&i==n)||t.push(this.data[r],n)}}return t}configure(e){let t=Object.assign(Object.create(le.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let r=this.topRules[e.top];if(!r)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=r}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(r=>{let n=e.tokenizers.find(i=>i.from==r);return n?n.to:r})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((r,n)=>{let i=e.specializers.find(l=>l.from==r.external);if(!i)return r;let s=Object.assign(Object.assign({},r),{external:i.to});return t.specializers[n]=ur(s),s})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),r=t.map(()=>!1);if(e)for(let i of e.split(" ")){let s=t.indexOf(i);s>=0&&(r[s]=!0)}let n=null;for(let i=0;i<t.length;i++)if(!r[i])for(let s=this.dialects[t[i]],l;(l=this.data[s++])!=65535;)(n||(n=new Uint8Array(this.maxTerm+1)))[l]=1;return new gt(e,r,n)}static deserialize(e){return new le(e)}};function J(o,e){return o[e]|o[e+1]<<16}function co(o){let e=null;for(let t of o){let r=t.p.stoppedAt;(t.pos==t.p.stream.end||r!=null&&t.pos>r)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.score<t.score)&&(e=t)}return e}function ur(o){if(o.external){let e=o.extend?1:0;return(t,r)=>o.external(t,r)<<1|e}return o.get}var we=le.deserialize({version:14,states:"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",stateData:"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",goto:"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",nodeNames:"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",maxTerm:39,skippedNodes:[0],repeatNodeCount:1,tokenData:"6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",tokenizers:[0,1],topRules:{Filter:[0,1]},tokenPrec:0});var Z=require("@vuu-ui/vuu-utils");var z,xt=class{constructor(){Ft(this,z,void 0)}setFilterCombinatorOp(e,t=j(this,z)){(0,Z.isMultiClauseFilter)(t)&&t.op===e||qe(this,z,{op:e,filters:[j(this,z)]})}add(e){if(j(this,z)===void 0)qe(this,z,e);else if((0,Z.isMultiClauseFilter)(j(this,z)))j(this,z).filters.push(e);else throw Error("Invalid filter passed to FilterExpression")}setColumn(e,t=j(this,z)){if((0,Z.isMultiClauseFilter)(t)){let r=t.filters.at(-1);r&&this.setColumn(e,r)}else t&&(t.column=e)}setOp(e,t=j(this,z)){if((0,Z.isMultiClauseFilter)(t)){let r=t.filters.at(-1);r&&this.setOp(e,r)}else t&&(t.op=e)}setValue(e,t=j(this,z)){var r;if((0,Z.isMultiClauseFilter)(t)){let n=t.filters.at(-1);n&&this.setValue(e,n)}else(0,Z.isMultiValueFilter)(t)?((r=t.values)!=null||(t.values=[]),t.values.push(e)):(0,Z.isSingleValueFilter)(t)&&(t.value=e)}toJSON(e=j(this,z)){return this.name?{...e,name:this.name}:e}};z=new WeakMap;var He=(o,e)=>{let t=new xt,r=o.cursor();do{let{name:n,from:i,to:s}=r;switch(n){case"ColumnValueExpression":t.add({});break;case"ColumnSetExpression":t.add({op:"in"});break;case"Or":case"And":t.setFilterCombinatorOp(e.substring(i,s));break;case"Column":t.setColumn(e.substring(i,s));break;case"Operator":t.setOp(e.substring(i,s));break;case"String":t.setValue(e.substring(i+1,s-1));break;case"Number":t.setValue(parseFloat(e.substring(i,s)));break;case"True":t.setValue(!0);break;case"False":t.setValue(!1);break;case"FilterName":t.name=e.substring(i,s);break;default:}}while(r.next());return t.toJSON()};var Tn=we.configure({strict:!0});var Ir=Pt(bt(),1),ne=require("react");var $=require("@vuu-ui/vuu-codemirror");var mo=$.LRLanguage.define({name:"VuuFilterQuery",parser:we.configure({props:[(0,$.styleTags)({Identifier:$.tags.variableName,String:$.tags.string,Or:$.tags.emphasis,Operator:$.tags.operator})]})}),fr=()=>new $.LanguageSupport(mo);var ae=require("@vuu-ui/vuu-codemirror"),go=ae.HighlightStyle.define([{tag:ae.tags.variableName,color:"var(--vuuFilterEditor-variableColor)"},{tag:ae.tags.comment,color:"green",fontStyle:"italic"}]),cr=(0,ae.syntaxHighlighting)(go);var pr=require("@vuu-ui/vuu-codemirror"),dr=pr.EditorView.theme({"&":{color:"var(--vuuFilterEditor-color)",backgroundColor:"var(--vuuFilterEditor-background)",fontSize:"var(--vuuFilterEditor-fontSize)"},".cm-content":{caretColor:"var(--vuuFilterEditor-cursorColor)",padding:0},".cm-line":{lineHeight:"var(--vuuFilterEditor-lineHeight)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--vuuFilterEditor-cursorColor)"},"&.cm-focused .cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-scroller":{fontFamily:"var(--vuuFilterEditor-fontFamily)"},".cm-tooltip":{background:"var(--vuuFilterEditor-tooltipBackground)",border:"var(--vuuFilterEditor-tooltipBorder)",boxShadow:"var(--vuuFilterEditor-tooltipElevation)","&.cm-tooltip-autocomplete > ul":{fontFamily:"var(--vuuFilterEditor-fontFamily)",fontSize:"var(--vuuFilterEditor-fontSize)",maxHeight:"240px"},"&.cm-tooltip-autocomplete > ul > li":{alignItems:"center",display:"flex",height:"var(--vuuFilterEditor-suggestion-height)",padding:"0 3px",lineHeight:"var(--vuuFilterEditor-suggestion-height)"},"&.cm-tooltip-autocomplete li[aria-selected]":{background:"var(--vuuFilterEditor-suggestion-selectedBackground)",color:"var(--vuuFilterEditor-suggestion-selectedColor)"}},".cm-completionIcon":{height:"18px",flex:"0 0 16px"},".cm-completionLabel":{flex:"1 1 auto"},".cm-completionIcon-filter":{position:"relative","&:after":{background:"var(--salt-text-secondary-foreground)",content:"''","-webkit-mask":"var(--svg-filter) center center/13px 13px","-webkit-mask-repeat":"no-repeat",position:"absolute",height:"18px",left:"0px",top:"0px",width:"16px"}}},{dark:!1});var N=require("@vuu-ui/vuu-codemirror"),St=require("react"),mr=(o,e)=>{let t=o.prevSibling||o.parent;for(;t&&!["Column","Operator","In"].includes(t.name);)t=t.prevSibling||t.parent;if((t==null?void 0:t.name)==="In"||(t==null?void 0:t.name)==="Operator")return(0,N.getValue)(t,e)},xo=(o,e,t)=>{let r=(0,N.getValue)(o,e);if(!(t===void 0||r===t)&&["contains","ends","starts"].some(n=>n.startsWith(r.toLowerCase())))return r},gr=(o,e)=>{let t=o.prevSibling||o.parent||o.lastChild;for(;t&&t.name==="\u26A0";)t=t.prevSibling;if(t&&["As","Or","And"].includes(t.name))return(0,N.getValue)(t,e)},xr=(o,e)=>{if(o.name==="FilterName")return(0,N.getValue)(o,e);{let t=o.prevSibling||o.parent||o.lastChild;for(;t&&t.name!=="FilterName";)t=t.prevSibling;if(t&&t.name==="FilterName")return(0,N.getValue)(o,e)}},br=(o,e)=>{let t=o.prevSibling;if((t==null?void 0:t.name)==="Column")return(0,N.getValue)(t,e);if((t==null?void 0:t.name)==="Operator")return br(t,e)},bo=(o,e)=>{let t=o.lastChild,r=[];for(;t&&t.name!=="In";){let n=(0,N.getValue)(t,e);if(n)r.push(n);else break;t=t.prevSibling}return r};var Sr=(o,e,t)=>{let r=(0,St.useCallback)(async(n,i,s={})=>{let{startsWith:l=""}=s,a=await o.getSuggestions(i,s);return{from:n.pos-l.length,options:a}},[o]);return(0,St.useCallback)(async n=>{var f,h;let{state:i,pos:s}=n,l=(f=n.matchBefore(/\w*/))!=null?f:{from:0,to:0,text:void 0},u=(0,N.syntaxTree)(i).resolveInner(s,-1);switch(console.log({nodeBeforeName:u.name}),u.name){case"Filter":if(n.pos===0)return r(n,"column");if(gr(u,i)==="as")return r(n,"name");{let p=xr(u,i);return r(n,"save",{onSubmit:e.current,existingFilter:t,filterName:p})}case"String":{let c=mr(u,i),p=br(u,i),{from:d,to:g}=u;if(g-d===2&&n.pos===d+1){if(p&&c)return r(n,"columnValue",{columnName:p,operator:c,quoted:!0,startsWith:l.text})}else console.log(`we have a string, column is ${p} ${d} ${g}`)}break;case"As":return r(n,"name");case"FilterName":return r(n,"save",{onSubmit:e.current,existingFilter:t,filterName:xr(u,i)});case"Column":{let c=(0,N.getValue)(u,i);return await o.isPartialMatch("column",void 0,c)?r(n,"column",{startsWith:c}):r(n,"operator",{columnName:c})}case"\u26A0":{let c=(0,N.getNodeByName)(u,i),p=mr(u,i),d=p?void 0:xo(u,i,c);return d?r(n,"operator",{columnName:c,startsWith:d}):r(n,"columnValue",{columnName:c,operator:p,startsWith:l.text})}case"Identifier":if(gr(u,i)==="as")return{from:n.pos,options:[{label:"press ENTER to apply filter and save",apply:()=>e.current(),boost:5}]};break;case"ColumnSetExpression":case"Values":{let c=(0,N.getNodeByName)(u,i),p=bo(u,i);return r(n,"columnValue",{columnName:c,selection:p})}case"Comma":case"LBrack":{let c=(0,N.getNodeByName)(u,i);return r(n,"columnValue",{columnName:c})}case"ColumnValueExpression":{let c=(h=u.lastChild)==null?void 0:h.prevSibling;if((c==null?void 0:c.name)==="Column")return r(n,"operator",{columnName:(0,N.getNodeByName)(u,i)});if((c==null?void 0:c.name)==="Operator")return r(n,"columnValue",{columnName:(0,N.getNodeByName)(c,i),operator:(0,N.getValue)(c,i)})}break;case"In":return{from:n.pos,options:[{label:"[",apply:" [",type:"text"}]};case"Eq":return r(n,"columnValue",{columnName:(0,N.getNodeByName)(u,i)});case"AndExpression":case"OrExpression":return r(n,"column");default:}},[t,r,e,o])};var Te=o=>{if(o.current==null)throw Error("EditorView not defined");return o.current},So=o=>(0,Ir.default)("vuuSuggestion",{vuuIllustration:o.isIllustration}),Io=o=>{let e=o.lastIndexOf(" as ");return e!==-1?o.slice(0,e):o},yo=()=>console.log("noooop"),It=({existingFilter:o,onSubmitFilter:e,suggestionProvider:t})=>{let r=(0,ne.useRef)(null),n=(0,ne.useRef)(yo),i=(0,ne.useRef)(),s=Sr(t,n,o),[l,a]=(0,ne.useMemo)(()=>{let u=()=>{let g=Te(i),F=g.state.doc.toString(),T=(0,w.ensureSyntaxTree)(g.state,g.state.doc.length,5e3);if(T){let S=He(T,F);return[S,Io(F),S.name]}else return[void 0,"",void 0]},f=()=>{Te(i).setState(d())},h=g=>{let[F,T,S]=u();e==null||e(F,T,g,S),f()},c=g=>w.keymap.of([{key:g,run(){return h(),!0}}]),p=g=>w.keymap.of([{key:g,run(){return(0,w.startCompletion)(Te(i)),!0}}]),d=()=>w.EditorState.create({doc:"",extensions:[w.minimalSetup,(0,w.autocompletion)({override:[s],optionClass:So}),fr(),w.keymap.of(w.defaultKeymap),c("Ctrl-Enter"),p("ArrowDown"),w.EditorView.updateListener.of(g=>{let F=Te(i);g.docChanged&&(0,w.startCompletion)(F)}),w.EditorState.transactionFilter.of(g=>g.newDoc.lines>1?[]:g),dr,cr]});return n.current=g=>{h(g),setTimeout(()=>{Te(i).focus()},100)},[d,f]},[s,e]);return(0,ne.useEffect)(()=>{if(!r.current)throw Error("editor not in dom");return i.current=new w.EditorView({state:l(),parent:r.current}),()=>{var u;(u=i.current)==null||u.destroy()}},[s,l]),{editorRef:r,clearInput:a}};var be=require("react/jsx-runtime"),je="vuuFilterInput",vo=({existingFilter:o,iconName:e="filter",namedFilters:t,onSubmitFilter:r,suggestionProvider:n,...i})=>{let{editorRef:s,clearInput:l}=It({existingFilter:o,onSubmitFilter:r,suggestionProvider:n});return(0,be.jsxs)("div",{...i,className:je,children:[(0,be.jsx)(yt.Button,{className:`${je}-FilterButton`,"data-icon":e,tabIndex:-1}),(0,be.jsx)("div",{className:`${je}-Editor`,ref:s}),(0,be.jsx)(yt.Button,{className:`${je}-ClearButton`,"data-icon":"close-circle",onClick:l})]})};var V=require("@vuu-ui/vuu-codemirror"),Xe=require("@vuu-ui/vuu-data-react"),Ne=require("react");var Ae=require("@vuu-ui/vuu-utils"),yr=(o,e)=>{let t=(0,Ae.createEl)("div","vuuFunctionDoc"),r=(0,Ae.createEl)("div","function-heading"),n=(0,Ae.createEl)("span","function-name",o);r.appendChild(n);let i=(0,Ae.createEl)("p",void 0,e);return t.appendChild(r),t.appendChild(i),t};var Co=[],ko={},Po=o=>[{label:"Press ENTER to create TAB",apply:()=>o("tab"),boost:6}],vr=(o,e,t=!0)=>{let r=e?[{label:"REPLACE existing filter",apply:()=>o("replace"),boost:8},{label:"AND existing filter",apply:()=>o("and"),boost:7},{label:"OR existing filter",apply:()=>o("or"),boost:7}]:[{label:"Press ENTER to submit",apply:()=>o(),boost:6}];return t?r.concat(V.booleanJoinSuggestions).concat(V.asNameSuggestion):r},Oo=(o,e)=>vr(o,e,!0),Fo=o=>vr(o,void 0),wo=({existingFilter:o,filterName:e,onSubmit:t,saveOptions:r})=>{let n=e&&r.allowSaveAsTab,i=o?Oo(t,o):Fo(t);return n?i.concat(Po(t)):i},To=o=>o.map(e=>({boost:5,label:e.name})),Ao=o=>o?Array.from(o.entries()).map(([e,t])=>({info:()=>yr(e,t),label:e,type:"filter"})):Co,No={label:"Done",apply:"] ",type:"keyword",boost:10},Ge=(o,e="")=>o.filter(t=>e===""||t.label.startsWith(e)).map(t=>({...t,apply:t.label+" "})),Ro={allowReplace:!0},Eo=({columns:o,namedFilters:e,saveOptions:t=Ro,table:r,typeaheadHook:n=Xe.useTypeaheadSuggestions})=>{let i=(0,Ne.useRef)(),s=n(),l=(0,Ne.useCallback)(async(u,f=ko)=>{let{columnName:h,existingFilter:c,filterName:p,operator:d,quoted:g,onSubmit:F,startsWith:T,selection:S}=f;switch(u){case"operator":{let y=o.find(x=>x.name===h);if(y)switch(y.serverDataType){case"string":case"char":return Ge(V.stringOperators,T);case"int":case"long":case"double":return Ge(V.numericOperators)}else console.warn(`'${h}' does not match any column name`)}break;case"column":{let y=await To(o),x=await Ao(e);return(i.current=Ge(y)).concat(Ge(x))}case"columnValue":if(h){let y=o.find(A=>A.name===h);if(!y)throw Error(`useFilterSUggestionProvider no column ${h}`);let x=Array.isArray(S)?S.length===0?"[":",":"",C=(0,Xe.getTypeaheadParams)(r,h,T),m=await s(C),b=d==="starts";return i.current=(0,V.toSuggestions)(m,{moveCursorToEnd:g,quoted:(y==null?void 0:y.serverDataType)==="string"&&!g,suffix:g?"":" ",prefix:b?T:x,isIllustration:b}),Array.isArray(S)&&(S==null?void 0:S.length)>1?[No,...i.current]:i.current}break;case"save":{if(typeof F!="function")throw Error("useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions");return await wo({existingFilter:c,filterName:p,onSubmit:F,saveOptions:t})}case"name":return await(0,V.getNamePrompt)("filter");default:}return[]},[o,s,e,t,r]),a=(0,Ne.useCallback)(async(u,f,h)=>{let c=await l(u,{columnName:f});if(h&&c)for(let p of c){if(p.label===h)return!1;if(p.label.startsWith(h))return!0}return!1},[l]);return{getSuggestions:l,isPartialMatch:a}};var Er=require("@heswell/salt-lab"),Dr=Pt(bt(),1);var Ie=require("@vuu-ui/vuu-utils"),Re=require("@heswell/salt-lab");var Cr=require("@heswell/salt-lab"),Ze=require("react"),Or=require("react/jsx-runtime"),Do=o=>typeof o=="string",kr=o=>Do(o)?o.startsWith('"')&&o.endsWith('"')?o.slice(1,-1):o:o.map(kr),Pr=({column:o,selected:e,suggestionProvider:t,...r})=>{let n=e!=null?kr(e):void 0,i=Array.isArray(n)?n:n!=null?[n]:[],[s,l]=(0,Ze.useState)(i);console.log({initialValues:i});let a=(0,Ze.useCallback)(async u=>{if(u){let f=await t.getSuggestions("columnValue",{columnName:o});console.log({values:f}),l(f.map(h=>h.label))}},[o,t]);return(0,Or.jsx)(Cr.Dropdown,{...r,onOpenChange:a,selected:n,source:s})};var Fr=require("@heswell/salt-lab"),Ye=require("react"),Ar=require("react/jsx-runtime"),Mo=o=>typeof o=="string",wr=o=>{if(o!==void 0)return Mo(o)?o.startsWith('"')&&o.endsWith('"')?o.slice(1,-1):o:o.map(wr)},Tr=({column:o,selected:e,suggestionProvider:t,...r})=>{let n=wr(e),i=Array.isArray(n)?n:n!=null?[n]:[],[s,l]=(0,Ye.useState)(i),a=(0,Ye.useCallback)(async u=>{if(u){let f=await t.getSuggestions("columnValue",{columnName:o});console.log({values:f}),l(f.map(h=>h.label))}},[o,t]);return(0,Ar.jsx)(Fr.Dropdown,{...r,onOpenChange:a,selected:n,selectionStrategy:"multiple",source:s})};var Se=require("react/jsx-runtime"),Nr=(o,e)=>{if((0,Ie.isNamedFilter)(o))return(0,Se.jsx)(Re.ToggleButton,{className:"vuuToggleButton",toggled:!0,variant:"secondary",children:o.name});if((0,Ie.isSingleValueFilter)(o)){let{column:t,value:r}=o;return(0,Se.jsx)(Re.ToolbarField,{className:"vuuFilterDropdown",label:t,labelPlacement:"top",children:(0,Se.jsx)(Pr,{column:t,selected:r.toString(),selectionStrategy:"default",source:[r.toString()],suggestionProvider:e,style:{width:100}})},t)}if((0,Ie.isMultiValueFilter)(o)){let t=o.values.map(r=>r.toString());return(0,Se.jsx)(Re.ToolbarField,{className:"vuuFilterDropdown",label:o.column,labelPlacement:"top",children:(0,Se.jsx)(Tr,{column:o.column,selected:t,source:t,suggestionProvider:e,style:{width:100}})},o.column)}return o.filters.map(t=>Nr(t,e))},Rr=({filter:o,suggestionProvider:e})=>o?Nr(o,e):[];var Mr=require("react/jsx-runtime"),Bo=({className:o,filter:e,suggestionProvider:t,...r})=>{console.log(`FilterToolbar ${JSON.stringify(e,null,2)}`);let n=Rr({filter:e,suggestionProvider:t});return(0,Mr.jsx)(Er.Toolbar,{className:(0,Dr.default)("vuuFilterToolbar",o),...r,children:n})};
3103
+
3104
+ // ../vuu-filter-parser/src/generated/filter-parser.js
3105
+ var parser = LRParser.deserialize({
3106
+ version: 14,
3107
+ states: "%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",
3108
+ stateData: "#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",
3109
+ goto: "#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",
3110
+ nodeNames: "\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",
3111
+ maxTerm: 39,
3112
+ skippedNodes: [0],
3113
+ repeatNodeCount: 1,
3114
+ tokenData: "6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",
3115
+ tokenizers: [0, 1],
3116
+ topRules: { "Filter": [0, 1] },
3117
+ tokenPrec: 0
3118
+ });
3119
+
3120
+ // ../vuu-filter-parser/src/FilterTreeWalker.ts
3121
+ var import_vuu_utils = require("@vuu-ui/vuu-utils");
3122
+ var _filter;
3123
+ var FilterExpression = class {
3124
+ constructor() {
3125
+ __privateAdd(this, _filter, void 0);
3126
+ }
3127
+ setFilterCombinatorOp(op, filter = __privateGet(this, _filter)) {
3128
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter) && filter.op === op) {
3129
+ return;
3130
+ } else {
3131
+ __privateSet(this, _filter, {
3132
+ op,
3133
+ filters: [__privateGet(this, _filter)]
3134
+ });
3135
+ }
3136
+ }
3137
+ add(filter) {
3138
+ if (__privateGet(this, _filter) === void 0) {
3139
+ __privateSet(this, _filter, filter);
3140
+ } else if ((0, import_vuu_utils.isMultiClauseFilter)(__privateGet(this, _filter))) {
3141
+ __privateGet(this, _filter).filters.push(filter);
3142
+ } else {
3143
+ throw Error(`Invalid filter passed to FilterExpression`);
3144
+ }
3145
+ }
3146
+ setColumn(column, filter = __privateGet(this, _filter)) {
3147
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3148
+ const target = filter.filters.at(-1);
3149
+ if (target) {
3150
+ this.setColumn(column, target);
3151
+ }
3152
+ } else if (filter) {
3153
+ filter.column = column;
3154
+ }
3155
+ }
3156
+ setOp(value, filter = __privateGet(this, _filter)) {
3157
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3158
+ const target = filter.filters.at(-1);
3159
+ if (target) {
3160
+ this.setOp(value, target);
3161
+ }
3162
+ } else if (filter) {
3163
+ filter.op = value;
3164
+ }
3165
+ }
3166
+ setValue(value, filter = __privateGet(this, _filter)) {
3167
+ var _a;
3168
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3169
+ const target = filter.filters.at(-1);
3170
+ if (target) {
3171
+ this.setValue(value, target);
3172
+ }
3173
+ } else if ((0, import_vuu_utils.isMultiValueFilter)(filter)) {
3174
+ (_a = filter.values) != null ? _a : filter.values = [];
3175
+ filter.values.push(value);
3176
+ } else if ((0, import_vuu_utils.isSingleValueFilter)(filter)) {
3177
+ filter.value = value;
3178
+ }
3179
+ }
3180
+ toJSON(filter = __privateGet(this, _filter)) {
3181
+ if (this.name) {
3182
+ return {
3183
+ ...filter,
3184
+ name: this.name
3185
+ };
3186
+ } else {
3187
+ return filter;
3188
+ }
3189
+ }
3190
+ };
3191
+ _filter = new WeakMap();
3192
+ var walkTree = (tree, source) => {
3193
+ const filterExpression = new FilterExpression();
3194
+ const cursor = tree.cursor();
3195
+ do {
3196
+ const { name, from, to } = cursor;
3197
+ switch (name) {
3198
+ case "ColumnValueExpression":
3199
+ filterExpression.add({});
3200
+ break;
3201
+ case "ColumnSetExpression":
3202
+ filterExpression.add({ op: "in" });
3203
+ break;
3204
+ case "Or":
3205
+ case "And":
3206
+ filterExpression.setFilterCombinatorOp(source.substring(from, to));
3207
+ break;
3208
+ case "Column":
3209
+ filterExpression.setColumn(source.substring(from, to));
3210
+ break;
3211
+ case "Operator":
3212
+ filterExpression.setOp(source.substring(from, to));
3213
+ break;
3214
+ case "String":
3215
+ filterExpression.setValue(source.substring(from + 1, to - 1));
3216
+ break;
3217
+ case "Number":
3218
+ filterExpression.setValue(parseFloat(source.substring(from, to)));
3219
+ break;
3220
+ case "True":
3221
+ filterExpression.setValue(true);
3222
+ break;
3223
+ case "False":
3224
+ filterExpression.setValue(false);
3225
+ break;
3226
+ case "FilterName":
3227
+ filterExpression.name = source.substring(from, to);
3228
+ break;
3229
+ default:
3230
+ }
3231
+ } while (cursor.next());
3232
+ return filterExpression.toJSON();
3233
+ };
3234
+
3235
+ // ../vuu-filter-parser/src/FilterParser.ts
3236
+ var strictParser = parser.configure({ strict: true });
3237
+
3238
+ // src/filter-input/useCodeMirrorEditor.ts
3239
+ var import_classnames = __toESM(require_classnames(), 1);
3240
+ var import_react2 = require("react");
3241
+
3242
+ // src/filter-input/FilterLanguage.ts
3243
+ var import_vuu_codemirror = require("@vuu-ui/vuu-codemirror");
3244
+ var filterLanguage = import_vuu_codemirror.LRLanguage.define({
3245
+ name: "VuuFilterQuery",
3246
+ parser: parser.configure({
3247
+ props: [
3248
+ (0, import_vuu_codemirror.styleTags)({
3249
+ Identifier: import_vuu_codemirror.tags.variableName,
3250
+ String: import_vuu_codemirror.tags.string,
3251
+ Or: import_vuu_codemirror.tags.emphasis,
3252
+ Operator: import_vuu_codemirror.tags.operator
3253
+ })
3254
+ ]
3255
+ })
3256
+ });
3257
+ var filterLanguageSupport = () => {
3258
+ return new import_vuu_codemirror.LanguageSupport(filterLanguage);
3259
+ };
3260
+
3261
+ // src/filter-input/highlighting.ts
3262
+ var import_vuu_codemirror2 = require("@vuu-ui/vuu-codemirror");
3263
+ var myHighlightStyle = import_vuu_codemirror2.HighlightStyle.define([
3264
+ { tag: import_vuu_codemirror2.tags.variableName, color: "var(--vuuFilterEditor-variableColor)" },
3265
+ { tag: import_vuu_codemirror2.tags.comment, color: "green", fontStyle: "italic" }
3266
+ ]);
3267
+ var vuuHighlighting = (0, import_vuu_codemirror2.syntaxHighlighting)(myHighlightStyle);
3268
+
3269
+ // src/filter-input/theme.ts
3270
+ var import_vuu_codemirror3 = require("@vuu-ui/vuu-codemirror");
3271
+ var vuuTheme = import_vuu_codemirror3.EditorView.theme(
3272
+ {
3273
+ "&": {
3274
+ color: "var(--vuuFilterEditor-color)",
3275
+ backgroundColor: "var(--vuuFilterEditor-background)",
3276
+ fontSize: "var(--vuuFilterEditor-fontSize)"
3277
+ },
3278
+ ".cm-content": {
3279
+ caretColor: "var(--vuuFilterEditor-cursorColor)",
3280
+ padding: 0
3281
+ },
3282
+ ".cm-line": {
3283
+ lineHeight: "var(--vuuFilterEditor-lineHeight)"
3284
+ },
3285
+ "&.cm-focused .cm-cursor": {
3286
+ borderLeftColor: "var(--vuuFilterEditor-cursorColor)"
3287
+ },
3288
+ "&.cm-focused .cm-selectionBackground, ::selection": {
3289
+ backgroundColor: "var(--vuuFilterEditor-selectionBackground)"
3290
+ },
3291
+ ".cm-selectionBackground, ::selection": {
3292
+ backgroundColor: "var(--vuuFilterEditor-selectionBackground)"
3293
+ },
3294
+ ".cm-scroller": {
3295
+ fontFamily: "var(--vuuFilterEditor-fontFamily)"
3296
+ },
3297
+ ".cm-tooltip": {
3298
+ background: "var(--vuuFilterEditor-tooltipBackground)",
3299
+ border: "var(--vuuFilterEditor-tooltipBorder)",
3300
+ boxShadow: "var(--vuuFilterEditor-tooltipElevation)",
3301
+ "&.cm-tooltip-autocomplete > ul": {
3302
+ fontFamily: "var(--vuuFilterEditor-fontFamily)",
3303
+ fontSize: "var(--vuuFilterEditor-fontSize)",
3304
+ maxHeight: "240px"
3305
+ },
3306
+ "&.cm-tooltip-autocomplete > ul > li": {
3307
+ alignItems: "center",
3308
+ display: "flex",
3309
+ height: "var(--vuuFilterEditor-suggestion-height)",
3310
+ padding: "0 3px",
3311
+ lineHeight: "var(--vuuFilterEditor-suggestion-height)"
3312
+ },
3313
+ "&.cm-tooltip-autocomplete li[aria-selected]": {
3314
+ background: "var(--vuuFilterEditor-suggestion-selectedBackground)",
3315
+ color: "var(--vuuFilterEditor-suggestion-selectedColor)"
3316
+ }
3317
+ },
3318
+ ".cm-completionIcon": {
3319
+ height: "18px",
3320
+ flex: "0 0 16px"
3321
+ },
3322
+ ".cm-completionLabel": {
3323
+ flex: "1 1 auto"
3324
+ },
3325
+ ".cm-completionIcon-filter": {
3326
+ position: "relative",
3327
+ "&:after": {
3328
+ background: "var(--salt-text-secondary-foreground)",
3329
+ content: "''",
3330
+ "-webkit-mask": "var(--svg-filter) center center/13px 13px",
3331
+ "-webkit-mask-repeat": "no-repeat",
3332
+ position: "absolute",
3333
+ height: "18px",
3334
+ left: "0px",
3335
+ top: "0px",
3336
+ width: "16px"
3337
+ }
3338
+ }
3339
+ },
3340
+ { dark: false }
3341
+ );
3342
+
3343
+ // src/filter-input/useFilterAutoComplete.ts
3344
+ var import_vuu_codemirror4 = require("@vuu-ui/vuu-codemirror");
3345
+ var import_react = require("react");
3346
+ var getOperator = (node, state) => {
3347
+ let maybeColumnNode = node.prevSibling || node.parent;
3348
+ while (maybeColumnNode && !["Column", "Operator", "In"].includes(maybeColumnNode.name)) {
3349
+ maybeColumnNode = maybeColumnNode.prevSibling || maybeColumnNode.parent;
3350
+ }
3351
+ if ((maybeColumnNode == null ? void 0 : maybeColumnNode.name) === "In" || (maybeColumnNode == null ? void 0 : maybeColumnNode.name) === "Operator") {
3352
+ return (0, import_vuu_codemirror4.getValue)(maybeColumnNode, state);
3353
+ } else {
3354
+ return void 0;
3355
+ }
3356
+ };
3357
+ var getPartialOperator = (maybeOperatorNode, state, columnName) => {
3358
+ const value = (0, import_vuu_codemirror4.getValue)(maybeOperatorNode, state);
3359
+ if (columnName === void 0 || value === columnName) {
3360
+ return;
3361
+ }
3362
+ if (["contains", "ends", "starts"].some(
3363
+ (val) => val.startsWith(value.toLowerCase())
3364
+ )) {
3365
+ return value;
3366
+ } else {
3367
+ return void 0;
3368
+ }
3369
+ };
3370
+ var getClauseOperator = (node, state) => {
3371
+ let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;
3372
+ while (maybeTargetNode && maybeTargetNode.name === "\u26A0")
3373
+ maybeTargetNode = maybeTargetNode.prevSibling;
3374
+ if (maybeTargetNode && ["As", "Or", "And"].includes(maybeTargetNode.name)) {
3375
+ return (0, import_vuu_codemirror4.getValue)(maybeTargetNode, state);
3376
+ } else {
3377
+ return void 0;
3378
+ }
3379
+ };
3380
+ var getFilterName = (node, state) => {
3381
+ if (node.name === "FilterName") {
3382
+ return (0, import_vuu_codemirror4.getValue)(node, state);
3383
+ } else {
3384
+ let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;
3385
+ while (maybeTargetNode && maybeTargetNode.name !== "FilterName")
3386
+ maybeTargetNode = maybeTargetNode.prevSibling;
3387
+ if (maybeTargetNode && maybeTargetNode.name === "FilterName") {
3388
+ return (0, import_vuu_codemirror4.getValue)(node, state);
3389
+ }
3390
+ }
3391
+ };
3392
+ var getColumnName = (node, state) => {
3393
+ const prevNode = node.prevSibling;
3394
+ if ((prevNode == null ? void 0 : prevNode.name) === "Column") {
3395
+ return (0, import_vuu_codemirror4.getValue)(prevNode, state);
3396
+ } else if ((prevNode == null ? void 0 : prevNode.name) === "Operator") {
3397
+ return getColumnName(prevNode, state);
3398
+ }
3399
+ };
3400
+ var getSetValues = (node, state) => {
3401
+ let maybeTargetNode = node.lastChild;
3402
+ const values = [];
3403
+ while (maybeTargetNode && maybeTargetNode.name !== "In") {
3404
+ const value = (0, import_vuu_codemirror4.getValue)(maybeTargetNode, state);
3405
+ if (value) {
3406
+ values.push(value);
3407
+ } else {
3408
+ break;
3409
+ }
3410
+ maybeTargetNode = maybeTargetNode.prevSibling;
3411
+ }
3412
+ return values;
3413
+ };
3414
+ var useAutoComplete = (suggestionProvider, onSubmit, existingFilter) => {
3415
+ const makeSuggestions = (0, import_react.useCallback)(
3416
+ async (context, suggestionType, optionalArgs = {}) => {
3417
+ const { startsWith = "" } = optionalArgs;
3418
+ const options = await suggestionProvider.getSuggestions(
3419
+ suggestionType,
3420
+ optionalArgs
3421
+ );
3422
+ return { from: context.pos - startsWith.length, options };
3423
+ },
3424
+ [suggestionProvider]
3425
+ );
3426
+ return (0, import_react.useCallback)(
3427
+ async (context) => {
3428
+ var _a, _b;
3429
+ const { state, pos } = context;
3430
+ const word = (_a = context.matchBefore(/\w*/)) != null ? _a : {
3431
+ from: 0,
3432
+ to: 0,
3433
+ text: void 0
3434
+ };
3435
+ const tree = (0, import_vuu_codemirror4.syntaxTree)(state);
3436
+ const nodeBefore = tree.resolveInner(pos, -1);
3437
+ console.log({ nodeBeforeName: nodeBefore.name });
3438
+ switch (nodeBefore.name) {
3439
+ case "Filter":
3440
+ if (context.pos === 0) {
3441
+ return makeSuggestions(context, "column");
3442
+ } else {
3443
+ const clauseOperator = getClauseOperator(nodeBefore, state);
3444
+ if (clauseOperator === "as") {
3445
+ return makeSuggestions(context, "name");
3446
+ } else {
3447
+ const filterName = getFilterName(nodeBefore, state);
3448
+ return makeSuggestions(context, "save", {
3449
+ onSubmit: onSubmit.current,
3450
+ existingFilter,
3451
+ filterName
3452
+ });
3453
+ }
3454
+ }
3455
+ case "String":
3456
+ {
3457
+ const operator = getOperator(nodeBefore, state);
3458
+ const columnName = getColumnName(nodeBefore, state);
3459
+ const { from, to } = nodeBefore;
3460
+ if (to - from === 2 && context.pos === from + 1) {
3461
+ if (columnName && operator) {
3462
+ return makeSuggestions(context, "columnValue", {
3463
+ columnName,
3464
+ operator,
3465
+ quoted: true,
3466
+ startsWith: word.text
3467
+ });
3468
+ }
3469
+ } else {
3470
+ console.log(
3471
+ `we have a string, column is ${columnName} ${from} ${to}`
3472
+ );
3473
+ }
3474
+ }
3475
+ break;
3476
+ case "As":
3477
+ return makeSuggestions(context, "name");
3478
+ case "FilterName":
3479
+ return makeSuggestions(context, "save", {
3480
+ onSubmit: onSubmit.current,
3481
+ existingFilter,
3482
+ filterName: getFilterName(nodeBefore, state)
3483
+ });
3484
+ case "Column": {
3485
+ const columnName = (0, import_vuu_codemirror4.getValue)(nodeBefore, state);
3486
+ const isPartialMatch = await suggestionProvider.isPartialMatch(
3487
+ "column",
3488
+ void 0,
3489
+ columnName
3490
+ );
3491
+ if (isPartialMatch) {
3492
+ return makeSuggestions(context, "column", {
3493
+ startsWith: columnName
3494
+ });
3495
+ } else {
3496
+ return makeSuggestions(context, "operator", { columnName });
3497
+ }
3498
+ }
3499
+ case "\u26A0": {
3500
+ const columnName = (0, import_vuu_codemirror4.getNodeByName)(nodeBefore, state);
3501
+ const operator = getOperator(nodeBefore, state);
3502
+ const partialOperator = operator ? void 0 : getPartialOperator(nodeBefore, state, columnName);
3503
+ if (partialOperator) {
3504
+ return makeSuggestions(context, "operator", {
3505
+ columnName,
3506
+ startsWith: partialOperator
3507
+ });
3508
+ } else {
3509
+ return makeSuggestions(context, "columnValue", {
3510
+ columnName,
3511
+ operator,
3512
+ startsWith: word.text
3513
+ });
3514
+ }
3515
+ }
3516
+ case "Identifier":
3517
+ {
3518
+ const clauseOperator = getClauseOperator(nodeBefore, state);
3519
+ if (clauseOperator === "as") {
3520
+ return {
3521
+ from: context.pos,
3522
+ options: [
3523
+ {
3524
+ label: "press ENTER to apply filter and save",
3525
+ apply: () => onSubmit.current(),
3526
+ boost: 5
3527
+ }
3528
+ ]
3529
+ };
3530
+ }
3531
+ }
3532
+ break;
3533
+ case "ColumnSetExpression":
3534
+ case "Values": {
3535
+ const columnName = (0, import_vuu_codemirror4.getNodeByName)(nodeBefore, state);
3536
+ const selection = getSetValues(nodeBefore, state);
3537
+ return makeSuggestions(context, "columnValue", {
3538
+ columnName,
3539
+ selection
3540
+ });
3541
+ }
3542
+ case "Comma":
3543
+ case "LBrack": {
3544
+ const columnName = (0, import_vuu_codemirror4.getNodeByName)(nodeBefore, state);
3545
+ return makeSuggestions(context, "columnValue", { columnName });
3546
+ }
3547
+ case "ColumnValueExpression":
3548
+ {
3549
+ const lastToken = (_b = nodeBefore.lastChild) == null ? void 0 : _b.prevSibling;
3550
+ if ((lastToken == null ? void 0 : lastToken.name) === "Column") {
3551
+ return makeSuggestions(context, "operator", {
3552
+ columnName: (0, import_vuu_codemirror4.getNodeByName)(nodeBefore, state)
3553
+ });
3554
+ } else if ((lastToken == null ? void 0 : lastToken.name) === "Operator") {
3555
+ return makeSuggestions(context, "columnValue", {
3556
+ columnName: (0, import_vuu_codemirror4.getNodeByName)(lastToken, state),
3557
+ operator: (0, import_vuu_codemirror4.getValue)(lastToken, state)
3558
+ });
3559
+ }
3560
+ }
3561
+ break;
3562
+ case "In": {
3563
+ return {
3564
+ from: context.pos,
3565
+ options: [{ label: "[", apply: " [", type: "text" }]
3566
+ };
3567
+ }
3568
+ case "Eq": {
3569
+ return makeSuggestions(context, "columnValue", {
3570
+ columnName: (0, import_vuu_codemirror4.getNodeByName)(nodeBefore, state)
3571
+ });
3572
+ }
3573
+ case "AndExpression":
3574
+ case "OrExpression": {
3575
+ return makeSuggestions(context, "column");
3576
+ }
3577
+ default:
3578
+ }
3579
+ },
3580
+ [existingFilter, makeSuggestions, onSubmit, suggestionProvider]
3581
+ );
3582
+ };
3583
+
3584
+ // src/filter-input/useCodeMirrorEditor.ts
3585
+ var getView = (ref) => {
3586
+ if (ref.current == void 0) {
3587
+ throw Error("EditorView not defined");
3588
+ }
3589
+ return ref.current;
3590
+ };
3591
+ var getOptionClass = (completion) => {
3592
+ return (0, import_classnames.default)("vuuSuggestion", {
3593
+ vuuIllustration: completion.isIllustration
3594
+ });
3595
+ };
3596
+ var stripName = (filterQuery) => {
3597
+ const pos = filterQuery.lastIndexOf(" as ");
3598
+ if (pos !== -1) {
3599
+ return filterQuery.slice(0, pos);
3600
+ } else {
3601
+ return filterQuery;
3602
+ }
3603
+ };
3604
+ var noop = () => console.log("noooop");
3605
+ var useCodeMirrorEditor = ({
3606
+ existingFilter,
3607
+ onSubmitFilter,
3608
+ suggestionProvider
3609
+ }) => {
3610
+ const editorRef = (0, import_react2.useRef)(null);
3611
+ const onSubmit = (0, import_react2.useRef)(noop);
3612
+ const viewRef = (0, import_react2.useRef)();
3613
+ const completionFn = useAutoComplete(
3614
+ suggestionProvider,
3615
+ onSubmit,
3616
+ existingFilter
3617
+ );
3618
+ const [createState, clearInput] = (0, import_react2.useMemo)(() => {
3619
+ const parseFilter2 = () => {
3620
+ const view = getView(viewRef);
3621
+ const source = view.state.doc.toString();
3622
+ const tree = (0, import_vuu_codemirror5.ensureSyntaxTree)(view.state, view.state.doc.length, 5e3);
3623
+ if (tree) {
3624
+ const filter = walkTree(tree, source);
3625
+ return [filter, stripName(source), filter.name];
3626
+ } else {
3627
+ return [void 0, "", void 0];
3628
+ }
3629
+ };
3630
+ const clearInput2 = () => {
3631
+ getView(viewRef).setState(createState2());
3632
+ };
3633
+ const submitFilterAndClearInput = (mode) => {
3634
+ const [filter, filterQuery, filterName] = parseFilter2();
3635
+ onSubmitFilter == null ? void 0 : onSubmitFilter(filter, filterQuery, mode, filterName);
3636
+ clearInput2();
3637
+ };
3638
+ const submitFilter = (key) => {
3639
+ return import_vuu_codemirror5.keymap.of([
3640
+ {
3641
+ key,
3642
+ run() {
3643
+ submitFilterAndClearInput();
3644
+ return true;
3645
+ }
3646
+ }
3647
+ ]);
3648
+ };
3649
+ const showSuggestions = (key) => {
3650
+ return import_vuu_codemirror5.keymap.of([
3651
+ {
3652
+ key,
3653
+ run() {
3654
+ (0, import_vuu_codemirror5.startCompletion)(getView(viewRef));
3655
+ return true;
3656
+ }
3657
+ }
3658
+ ]);
3659
+ };
3660
+ const createState2 = () => import_vuu_codemirror5.EditorState.create({
3661
+ doc: "",
3662
+ extensions: [
3663
+ import_vuu_codemirror5.minimalSetup,
3664
+ (0, import_vuu_codemirror5.autocompletion)({
3665
+ override: [completionFn],
3666
+ optionClass: getOptionClass
3667
+ }),
3668
+ filterLanguageSupport(),
3669
+ import_vuu_codemirror5.keymap.of(import_vuu_codemirror5.defaultKeymap),
3670
+ submitFilter("Ctrl-Enter"),
3671
+ showSuggestions("ArrowDown"),
3672
+ import_vuu_codemirror5.EditorView.updateListener.of((v) => {
3673
+ const view = getView(viewRef);
3674
+ if (v.docChanged) {
3675
+ (0, import_vuu_codemirror5.startCompletion)(view);
3676
+ }
3677
+ }),
3678
+ import_vuu_codemirror5.EditorState.transactionFilter.of(
3679
+ (tr) => tr.newDoc.lines > 1 ? [] : tr
3680
+ ),
3681
+ vuuTheme,
3682
+ vuuHighlighting
3683
+ ]
3684
+ });
3685
+ onSubmit.current = (mode) => {
3686
+ submitFilterAndClearInput(mode);
3687
+ setTimeout(() => {
3688
+ getView(viewRef).focus();
3689
+ }, 100);
3690
+ };
3691
+ return [createState2, clearInput2];
3692
+ }, [completionFn, onSubmitFilter]);
3693
+ (0, import_react2.useEffect)(() => {
3694
+ if (!editorRef.current) {
3695
+ throw Error("editor not in dom");
3696
+ }
3697
+ viewRef.current = new import_vuu_codemirror5.EditorView({
3698
+ state: createState(),
3699
+ parent: editorRef.current
3700
+ });
3701
+ return () => {
3702
+ var _a;
3703
+ (_a = viewRef.current) == null ? void 0 : _a.destroy();
3704
+ };
3705
+ }, [completionFn, createState]);
3706
+ return { editorRef, clearInput };
3707
+ };
3708
+
3709
+ // src/filter-input/FilterInput.tsx
3710
+ var import_jsx_runtime = require("react/jsx-runtime");
3711
+ var classBase = "vuuFilterInput";
3712
+ var FilterInput = ({
3713
+ existingFilter,
3714
+ iconName = "filter",
3715
+ namedFilters,
3716
+ onSubmitFilter,
3717
+ suggestionProvider,
3718
+ ...props
3719
+ }) => {
3720
+ const { editorRef, clearInput } = useCodeMirrorEditor({
3721
+ existingFilter,
3722
+ onSubmitFilter,
3723
+ suggestionProvider
3724
+ });
3725
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { ...props, className: classBase, children: [
3726
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
3727
+ import_core.Button,
3728
+ {
3729
+ className: `${classBase}-FilterButton`,
3730
+ "data-icon": iconName,
3731
+ tabIndex: -1
3732
+ }
3733
+ ),
3734
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `${classBase}-Editor`, ref: editorRef }),
3735
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
3736
+ import_core.Button,
3737
+ {
3738
+ className: `${classBase}-ClearButton`,
3739
+ "data-icon": "close-circle",
3740
+ onClick: clearInput
3741
+ }
3742
+ )
3743
+ ] });
3744
+ };
3745
+
3746
+ // src/filter-input/useFilterSuggestionProvider.ts
3747
+ var import_vuu_codemirror6 = require("@vuu-ui/vuu-codemirror");
3748
+ var import_vuu_data_react = require("@vuu-ui/vuu-data-react");
3749
+ var import_react3 = require("react");
3750
+
3751
+ // src/filter-input/filterInfo.ts
3752
+ var import_vuu_utils2 = require("@vuu-ui/vuu-utils");
3753
+ var filterInfo = (filterName, filterQuery) => {
3754
+ const rootElement = (0, import_vuu_utils2.createEl)("div", "vuuFunctionDoc");
3755
+ const headingElement = (0, import_vuu_utils2.createEl)("div", "function-heading");
3756
+ const nameElement = (0, import_vuu_utils2.createEl)("span", "function-name", filterName);
3757
+ headingElement.appendChild(nameElement);
3758
+ const child2 = (0, import_vuu_utils2.createEl)("p", void 0, filterQuery);
3759
+ rootElement.appendChild(headingElement);
3760
+ rootElement.appendChild(child2);
3761
+ return rootElement;
3762
+ };
3763
+
3764
+ // src/filter-input/useFilterSuggestionProvider.ts
3765
+ var NO_NAMED_FILTERS = [];
3766
+ var NONE = {};
3767
+ var saveAsTab = (onSubmit) => [
3768
+ {
3769
+ label: "Press ENTER to create TAB",
3770
+ apply: () => onSubmit("tab"),
3771
+ boost: 6
3772
+ }
3773
+ ];
3774
+ var makeSaveOrExtendSuggestions = (onSubmit, existingFilter, withJoinSuggestions = true) => {
3775
+ const result = existingFilter ? [
3776
+ {
3777
+ label: "REPLACE existing filter",
3778
+ apply: () => onSubmit("replace"),
3779
+ boost: 8
3780
+ },
3781
+ {
3782
+ label: "AND existing filter",
3783
+ apply: () => onSubmit("and"),
3784
+ boost: 7
3785
+ },
3786
+ {
3787
+ label: "OR existing filter",
3788
+ apply: () => onSubmit("or"),
3789
+ boost: 7
3790
+ }
3791
+ ] : [
3792
+ {
3793
+ label: "Press ENTER to submit",
3794
+ apply: () => onSubmit(),
3795
+ boost: 6
3796
+ }
3797
+ ];
3798
+ return withJoinSuggestions ? result.concat(import_vuu_codemirror6.booleanJoinSuggestions).concat(import_vuu_codemirror6.asNameSuggestion) : result;
3799
+ };
3800
+ var promptToSaveOrExtend = (onSubmit, existingFilter) => makeSaveOrExtendSuggestions(onSubmit, existingFilter, true);
3801
+ var promptToSave = (onSubmit) => makeSaveOrExtendSuggestions(onSubmit, void 0);
3802
+ var getSaveSuggestions = ({
3803
+ existingFilter,
3804
+ filterName,
3805
+ onSubmit,
3806
+ saveOptions
3807
+ }) => {
3808
+ const includeTabSuggestion = filterName && saveOptions.allowSaveAsTab;
3809
+ const result = existingFilter ? promptToSaveOrExtend(onSubmit, existingFilter) : promptToSave(onSubmit);
3810
+ if (includeTabSuggestion) {
3811
+ return result.concat(saveAsTab(onSubmit));
3812
+ } else {
3813
+ return result;
3814
+ }
3815
+ };
3816
+ var suggestColumns = (columns) => columns.map((column) => ({
3817
+ boost: 5,
3818
+ label: column.name
3819
+ }));
3820
+ var suggestNamedFilters = (namedFilters) => namedFilters ? Array.from(namedFilters.entries()).map(([filterName, filterQuery]) => ({
3821
+ info: () => filterInfo(filterName, filterQuery),
3822
+ label: filterName,
3823
+ type: "filter"
3824
+ })) : NO_NAMED_FILTERS;
3825
+ var doneCommand = {
3826
+ label: "Done",
3827
+ apply: "] ",
3828
+ type: "keyword",
3829
+ boost: 10
3830
+ };
3831
+ var withApplySpace = (suggestions, startsWith = "") => suggestions.filter((sugg) => startsWith === "" || sugg.label.startsWith(startsWith)).map((suggestion) => ({
3832
+ ...suggestion,
3833
+ apply: suggestion.label + " "
3834
+ }));
3835
+ var defaultSaveOptions = {
3836
+ allowReplace: true
3837
+ };
3838
+ var useFilterSuggestionProvider = ({
3839
+ columns,
3840
+ namedFilters,
3841
+ saveOptions = defaultSaveOptions,
3842
+ table,
3843
+ typeaheadHook: useTypeahead = import_vuu_data_react.useTypeaheadSuggestions
3844
+ }) => {
3845
+ const latestSuggestionsRef = (0, import_react3.useRef)();
3846
+ const getTypeaheadSuggestions = useTypeahead();
3847
+ const getSuggestions = (0, import_react3.useCallback)(
3848
+ async (suggestionType, options = NONE) => {
3849
+ const {
3850
+ columnName,
3851
+ existingFilter,
3852
+ filterName,
3853
+ operator,
3854
+ quoted: autoQuoted,
3855
+ onSubmit,
3856
+ startsWith,
3857
+ selection
3858
+ } = options;
3859
+ switch (suggestionType) {
3860
+ case "operator":
3861
+ {
3862
+ const column = columns.find((col) => col.name === columnName);
3863
+ if (column) {
3864
+ switch (column.serverDataType) {
3865
+ case "string":
3866
+ case "char":
3867
+ return withApplySpace(import_vuu_codemirror6.stringOperators, startsWith);
3868
+ case "int":
3869
+ case "long":
3870
+ case "double":
3871
+ return withApplySpace(import_vuu_codemirror6.numericOperators);
3872
+ }
3873
+ } else {
3874
+ console.warn(`'${columnName}' does not match any column name`);
3875
+ }
3876
+ }
3877
+ break;
3878
+ case "column": {
3879
+ const columnSuggestions = await suggestColumns(columns);
3880
+ const filterSuggestions = await suggestNamedFilters(namedFilters);
3881
+ return (latestSuggestionsRef.current = withApplySpace(columnSuggestions)).concat(
3882
+ withApplySpace(filterSuggestions)
3883
+ );
3884
+ }
3885
+ case "columnValue":
3886
+ {
3887
+ if (columnName) {
3888
+ const column = columns.find((col) => col.name === columnName);
3889
+ if (!column) {
3890
+ throw Error(
3891
+ `useFilterSUggestionProvider no column ${columnName}`
3892
+ );
3893
+ }
3894
+ const prefix = Array.isArray(selection) ? selection.length === 0 ? "[" : "," : "";
3895
+ const params = (0, import_vuu_data_react.getTypeaheadParams)(
3896
+ table,
3897
+ columnName,
3898
+ startsWith
3899
+ );
3900
+ const suggestions = await getTypeaheadSuggestions(params);
3901
+ const isIllustration = operator === "starts";
3902
+ latestSuggestionsRef.current = (0, import_vuu_codemirror6.toSuggestions)(suggestions, {
3903
+ moveCursorToEnd: autoQuoted,
3904
+ quoted: (column == null ? void 0 : column.serverDataType) === "string" && !autoQuoted,
3905
+ suffix: autoQuoted ? "" : " ",
3906
+ prefix: isIllustration ? startsWith : prefix,
3907
+ isIllustration
3908
+ });
3909
+ if (Array.isArray(selection) && (selection == null ? void 0 : selection.length) > 1) {
3910
+ return [doneCommand, ...latestSuggestionsRef.current];
3911
+ }
3912
+ return latestSuggestionsRef.current;
3913
+ }
3914
+ }
3915
+ break;
3916
+ case "save": {
3917
+ if (typeof onSubmit !== "function") {
3918
+ throw Error(
3919
+ "useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions"
3920
+ );
3921
+ }
3922
+ return await getSaveSuggestions({
3923
+ existingFilter,
3924
+ filterName,
3925
+ onSubmit,
3926
+ saveOptions
3927
+ });
3928
+ }
3929
+ case "name":
3930
+ return await (0, import_vuu_codemirror6.getNamePrompt)("filter");
3931
+ default:
3932
+ }
3933
+ return [];
3934
+ },
3935
+ [columns, getTypeaheadSuggestions, namedFilters, saveOptions, table]
3936
+ );
3937
+ const isPartialMatch = (0, import_react3.useCallback)(
3938
+ async (valueType, columnName, pattern) => {
3939
+ const suggestions = (
3940
+ // latestSuggestions && latestSuggestions.length > 0
3941
+ // ? latestSuggestions
3942
+ await getSuggestions(valueType, { columnName })
3943
+ );
3944
+ if (pattern && suggestions) {
3945
+ for (const option of suggestions) {
3946
+ if (option.label === pattern) {
3947
+ return false;
3948
+ } else if (option.label.startsWith(pattern)) {
3949
+ return true;
3950
+ }
3951
+ }
3952
+ }
3953
+ return false;
3954
+ },
3955
+ [getSuggestions]
3956
+ );
3957
+ return {
3958
+ getSuggestions,
3959
+ isPartialMatch
3960
+ };
3961
+ };
3962
+
3963
+ // src/filter-toolbar/FilterToolbar.tsx
3964
+ var import_salt_lab4 = require("@heswell/salt-lab");
3965
+ var import_classnames2 = __toESM(require_classnames(), 1);
3966
+
3967
+ // src/filter-toolbar/useFilterToolbar.tsx
3968
+ var import_vuu_utils3 = require("@vuu-ui/vuu-utils");
3969
+ var import_salt_lab3 = require("@heswell/salt-lab");
3970
+
3971
+ // src/filter-toolbar/FilterDropdown.tsx
3972
+ var import_salt_lab = require("@heswell/salt-lab");
3973
+ var import_react4 = require("react");
3974
+ var import_jsx_runtime2 = require("react/jsx-runtime");
3975
+ var isString = (s) => typeof s === "string";
3976
+ var stripQuotes = (selected) => {
3977
+ if (isString(selected)) {
3978
+ if (selected.startsWith('"') && selected.endsWith('"')) {
3979
+ return selected.slice(1, -1);
3980
+ } else {
3981
+ return selected;
3982
+ }
3983
+ } else {
3984
+ return selected.map(stripQuotes);
3985
+ }
3986
+ };
3987
+ var FilterDropdown = ({
3988
+ column,
3989
+ selected: selectedProp,
3990
+ suggestionProvider,
3991
+ ...props
3992
+ }) => {
3993
+ const selected = selectedProp != null ? stripQuotes(selectedProp) : void 0;
3994
+ const initialValues = Array.isArray(selected) ? selected : selected != null ? [selected] : [];
3995
+ const [values, setValues] = (0, import_react4.useState)(initialValues);
3996
+ console.log({ initialValues });
3997
+ const handleOpenChange = (0, import_react4.useCallback)(
3998
+ async (isOpen) => {
3999
+ if (isOpen) {
4000
+ const values2 = await suggestionProvider.getSuggestions("columnValue", {
4001
+ columnName: column
4002
+ });
4003
+ console.log({ values: values2 });
4004
+ setValues(values2.map((suggestion) => suggestion.label));
4005
+ }
4006
+ },
4007
+ [column, suggestionProvider]
4008
+ );
4009
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
4010
+ import_salt_lab.Dropdown,
4011
+ {
4012
+ ...props,
4013
+ onOpenChange: handleOpenChange,
4014
+ selected,
4015
+ source: values
4016
+ }
4017
+ );
4018
+ };
4019
+
4020
+ // src/filter-toolbar/FilterDropdownMultiSelect.tsx
4021
+ var import_salt_lab2 = require("@heswell/salt-lab");
4022
+ var import_react5 = require("react");
4023
+ var import_jsx_runtime3 = require("react/jsx-runtime");
4024
+ var isString2 = (s) => typeof s === "string";
4025
+ var stripQuotes2 = (selected) => {
4026
+ if (selected === void 0) {
4027
+ return void 0;
4028
+ } else if (isString2(selected)) {
4029
+ if (selected.startsWith('"') && selected.endsWith('"')) {
4030
+ return selected.slice(1, -1);
4031
+ } else {
4032
+ return selected;
4033
+ }
4034
+ } else {
4035
+ return selected.map(stripQuotes2);
4036
+ }
4037
+ };
4038
+ var FilterDropdownMultiSelect = ({
4039
+ column,
4040
+ selected: selectedProp,
4041
+ suggestionProvider,
4042
+ ...props
4043
+ }) => {
4044
+ const selected = stripQuotes2(selectedProp);
4045
+ const initialValues = Array.isArray(selected) ? selected : selected != null ? [selected] : [];
4046
+ const [values, setValues] = (0, import_react5.useState)(initialValues);
4047
+ const handleOpenChange = (0, import_react5.useCallback)(
4048
+ async (isOpen) => {
4049
+ if (isOpen) {
4050
+ const values2 = await suggestionProvider.getSuggestions("columnValue", {
4051
+ columnName: column
4052
+ });
4053
+ console.log({ values: values2 });
4054
+ setValues(values2.map((suggestion) => suggestion.label));
4055
+ }
4056
+ },
4057
+ [column, suggestionProvider]
4058
+ );
4059
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
4060
+ import_salt_lab2.Dropdown,
4061
+ {
4062
+ ...props,
4063
+ onOpenChange: handleOpenChange,
4064
+ selected,
4065
+ selectionStrategy: "multiple",
4066
+ source: values
4067
+ }
4068
+ );
4069
+ };
4070
+
4071
+ // src/filter-toolbar/useFilterToolbar.tsx
4072
+ var import_jsx_runtime4 = require("react/jsx-runtime");
4073
+ var filterToControl = (filter, suggestionProvider) => {
4074
+ if ((0, import_vuu_utils3.isNamedFilter)(filter)) {
4075
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4076
+ import_salt_lab3.ToggleButton,
4077
+ {
4078
+ className: "vuuToggleButton",
4079
+ toggled: true,
4080
+ variant: "secondary",
4081
+ children: filter.name
4082
+ }
4083
+ );
4084
+ }
4085
+ if ((0, import_vuu_utils3.isSingleValueFilter)(filter)) {
4086
+ const { column, value } = filter;
4087
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4088
+ import_salt_lab3.ToolbarField,
4089
+ {
4090
+ className: "vuuFilterDropdown",
4091
+ label: column,
4092
+ labelPlacement: "top",
4093
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4094
+ FilterDropdown,
4095
+ {
4096
+ column,
4097
+ selected: value.toString(),
4098
+ selectionStrategy: "default",
4099
+ source: [value.toString()],
4100
+ suggestionProvider,
4101
+ style: { width: 100 }
4102
+ }
4103
+ )
4104
+ },
4105
+ column
4106
+ );
4107
+ }
4108
+ if ((0, import_vuu_utils3.isMultiValueFilter)(filter)) {
4109
+ const values = filter.values.map((v) => v.toString());
4110
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4111
+ import_salt_lab3.ToolbarField,
4112
+ {
4113
+ className: "vuuFilterDropdown",
4114
+ label: filter.column,
4115
+ labelPlacement: "top",
4116
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4117
+ FilterDropdownMultiSelect,
4118
+ {
4119
+ column: filter.column,
4120
+ selected: values,
4121
+ source: values,
4122
+ suggestionProvider,
4123
+ style: { width: 100 }
4124
+ }
4125
+ )
4126
+ },
4127
+ filter.column
4128
+ );
4129
+ }
4130
+ return filter.filters.map(
4131
+ (filter2) => filterToControl(filter2, suggestionProvider)
4132
+ );
4133
+ };
4134
+ var useFilterToolbar = ({
4135
+ filter,
4136
+ suggestionProvider
4137
+ }) => {
4138
+ if (filter) {
4139
+ return filterToControl(filter, suggestionProvider);
4140
+ }
4141
+ return [];
4142
+ };
4143
+
4144
+ // src/filter-toolbar/FilterToolbar.tsx
4145
+ var import_jsx_runtime5 = require("react/jsx-runtime");
4146
+ var FilterToolbar = ({
4147
+ className,
4148
+ filter,
4149
+ suggestionProvider,
4150
+ ...props
4151
+ }) => {
4152
+ console.log(`FilterToolbar ${JSON.stringify(filter, null, 2)}`);
4153
+ const toolbarItems = useFilterToolbar({ filter, suggestionProvider });
4154
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_salt_lab4.Toolbar, { className: (0, import_classnames2.default)("vuuFilterToolbar", className), ...props, children: toolbarItems });
4155
+ };
4156
+
4157
+ // src/filter-utils.ts
4158
+ var import_vuu_utils4 = require("@vuu-ui/vuu-utils");
4159
+ var AND = "and";
4160
+ var EQUALS = "=";
4161
+ var GREATER_THAN = ">";
4162
+ var LESS_THAN = "<";
4163
+ var OR = "or";
4164
+ var STARTS_WITH = "starts";
4165
+ var ENDS_WITH = "ends";
4166
+ var IN = "in";
4167
+ var filterClauses = (filter, clauses = []) => {
4168
+ if (filter) {
4169
+ if ((0, import_vuu_utils4.isMultiClauseFilter)(filter)) {
4170
+ filter.filters.forEach((f) => clauses.push(...filterClauses(f)));
4171
+ } else {
4172
+ clauses.push(filter);
4173
+ }
4174
+ }
4175
+ return clauses;
4176
+ };
4177
+ var DEFAULT_ADD_FILTER_OPTS = {
4178
+ combineWith: "and"
4179
+ };
4180
+ var addFilter = (existingFilter, filter, { combineWith = AND } = DEFAULT_ADD_FILTER_OPTS) => {
4181
+ var _a;
4182
+ if (includesNoValues(filter)) {
4183
+ if ((0, import_vuu_utils4.isMultiClauseFilter)(filter)) {
4184
+ } else {
4185
+ existingFilter = removeFilterForColumn(existingFilter, {
4186
+ name: filter.column
4187
+ });
4188
+ }
4189
+ } else if (includesAllValues(filter)) {
4190
+ if ((0, import_vuu_utils4.isMultiClauseFilter)(filter)) {
4191
+ }
4192
+ return removeFilterForColumn(existingFilter, { name: (_a = filter.column) != null ? _a : "" });
4193
+ }
4194
+ if (!existingFilter) {
4195
+ return filter;
4196
+ }
4197
+ if (!filter) {
4198
+ return existingFilter;
4199
+ }
4200
+ if (existingFilter.op === AND && filter.op === AND) {
4201
+ return {
4202
+ op: AND,
4203
+ filters: combine(existingFilter.filters, filter.filters)
4204
+ };
4205
+ }
4206
+ if (existingFilter.op === AND) {
4207
+ const filters = replaceOrInsert(existingFilter.filters, filter);
4208
+ return filters.length > 1 ? { op: AND, filters } : filters[0];
4209
+ }
4210
+ if (filter.op === AND) {
4211
+ return { op: AND, filters: filter.filters.concat(existingFilter) };
4212
+ }
4213
+ if (filterEquals(existingFilter, filter, true)) {
4214
+ return filter;
4215
+ }
4216
+ if (canMerge(existingFilter, filter)) {
4217
+ return merge(existingFilter, filter);
4218
+ }
4219
+ return { op: combineWith, filters: [existingFilter, filter] };
4220
+ };
4221
+ var includesNoValues = (filter) => {
4222
+ if (!filter) {
4223
+ return false;
4224
+ }
4225
+ if ((0, import_vuu_utils4.isInFilter)(filter) && filter.values.length === 0) {
4226
+ return true;
4227
+ }
4228
+ return (0, import_vuu_utils4.isAndFilter)(filter) && filter.filters.some((f) => includesNoValues(f));
4229
+ };
4230
+ var includesAllValues = (filter) => {
4231
+ if (!filter) {
4232
+ return false;
4233
+ }
4234
+ if (filter.op === STARTS_WITH && filter.value === "") {
4235
+ return true;
4236
+ }
4237
+ return filter.op === STARTS_WITH && filter.value === "";
4238
+ };
4239
+ var replaceOrInsert = (filters, filter) => {
4240
+ return filters.concat(filter);
4241
+ };
4242
+ var merge = (f1, f2) => {
4243
+ if (includesNoValues(f2)) {
4244
+ return f2;
4245
+ }
4246
+ if ((0, import_vuu_utils4.isInFilter)(f1) && (0, import_vuu_utils4.isInFilter)(f2)) {
4247
+ return {
4248
+ ...f1,
4249
+ values: [
4250
+ ...f1.values,
4251
+ ...f2.values.filter(
4252
+ (v) => !f1.values.includes(v)
4253
+ )
4254
+ ]
4255
+ };
4256
+ } else if ((0, import_vuu_utils4.isInFilter)(f1) && f2.op === EQUALS) {
4257
+ return {
4258
+ ...f1,
4259
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4260
+ // @ts-ignore
4261
+ values: f1.values.concat([f2.value])
4262
+ };
4263
+ } else if (f1.op === EQUALS && f2.op === EQUALS) {
4264
+ return {
4265
+ column: f1.column,
4266
+ op: IN,
4267
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4268
+ // @ts-ignore
4269
+ values: [f1.value, f2.value]
4270
+ };
4271
+ }
4272
+ return f2;
4273
+ };
4274
+ var combine = (existingFilters, replacementFilters) => {
4275
+ const equivalentType = ({ op: t1 }, { op: t2 }) => {
4276
+ return t1 === t2 || t1[0] === t2[0];
4277
+ };
4278
+ const replaces = (existingFilter, replacementFilter) => {
4279
+ return existingFilter.column === replacementFilter.column && equivalentType(existingFilter, replacementFilter);
4280
+ };
4281
+ const stillApplicable = (existingFilter) => replacementFilters.some(
4282
+ (replacementFilter) => replaces(existingFilter, replacementFilter)
4283
+ ) === false;
4284
+ return existingFilters.filter(stillApplicable).concat(replacementFilters);
4285
+ };
4286
+ var removeFilter = (sourceFilter, filterToRemove) => {
4287
+ if (filterEquals(sourceFilter, filterToRemove, true)) {
4288
+ return null;
4289
+ }
4290
+ if (sourceFilter.op !== AND) {
4291
+ throw Error(
4292
+ `removeFilter cannot remove ${JSON.stringify(
4293
+ filterToRemove
4294
+ )} from ${JSON.stringify(sourceFilter)}`
4295
+ );
4296
+ }
4297
+ const filters = sourceFilter.filters.filter(
4298
+ (f) => !filterEquals(f, filterToRemove)
4299
+ );
4300
+ return filters.length > 0 ? { type: AND, filters } : null;
4301
+ };
4302
+ var splitFilterOnColumn = (columnName, filter) => {
4303
+ if (!filter) {
4304
+ return [void 0, void 0];
4305
+ }
4306
+ if (filter.column === columnName) {
4307
+ return [filter, void 0];
4308
+ }
4309
+ if (filter.op !== AND) {
4310
+ return [void 0, filter];
4311
+ }
4312
+ const [[columnFilter = void 0], filters] = (0, import_vuu_utils4.partition)(
4313
+ filter.filters,
4314
+ (f) => f.column === columnName
4315
+ );
4316
+ return filters.length === 1 ? [columnFilter, filters[0]] : [columnFilter, { op: AND, filters }];
4317
+ };
4318
+ var overrideColName = (filter, column) => {
4319
+ if ((0, import_vuu_utils4.isMultiClauseFilter)(filter)) {
4320
+ return {
4321
+ op: filter.op,
4322
+ filters: filter.filters.map((f) => overrideColName(f, column))
4323
+ };
4324
+ }
4325
+ return { ...filter, column };
4326
+ };
4327
+ var filterIncludesColumn = (filter, column) => {
4328
+ if (!filter) {
4329
+ return false;
4330
+ }
4331
+ const { op, column: filterColName } = filter;
4332
+ switch (op) {
4333
+ case AND:
4334
+ case OR:
4335
+ return filter.filters != null && filter.filters.some((f) => filterIncludesColumn(f, column));
4336
+ default:
4337
+ return filterColName === column.name;
4338
+ }
4339
+ };
4340
+ var removeFilterForColumn = (sourceFilter, column) => {
4341
+ const colName = column.name;
4342
+ if (!sourceFilter) {
4343
+ return void 0;
4344
+ }
4345
+ if (sourceFilter.column === colName) {
4346
+ return void 0;
4347
+ }
4348
+ if ((0, import_vuu_utils4.isAndFilter)(sourceFilter) || (0, import_vuu_utils4.isOrFilter)(sourceFilter)) {
4349
+ const { op } = sourceFilter;
4350
+ const filters = sourceFilter.filters;
4351
+ const otherColFilters = filters.filter((f) => f.column !== colName);
4352
+ switch (otherColFilters.length) {
4353
+ case 0:
4354
+ return void 0;
4355
+ case 1:
4356
+ return otherColFilters[0];
4357
+ default:
4358
+ return { op, filters: otherColFilters };
4359
+ }
4360
+ }
4361
+ return sourceFilter;
4362
+ };
4363
+ var canMerge = (f1, f2) => f1.column === f2.column && (f1.op === "=" || f1.op === "in") && (f2.op === "=" || f2.op === "in");
4364
+ var sameValues = (arr1, arr2) => {
4365
+ if (arr1 === arr2) {
4366
+ return true;
4367
+ }
4368
+ if (arr1.length === arr2.length) {
4369
+ const a = arr1.slice().sort();
4370
+ const b = arr2.slice().sort();
4371
+ return a.join("|") === b.join("|");
4372
+ }
4373
+ return false;
4374
+ };
4375
+ var filterEquals = (f1, f2, strict = false) => {
4376
+ if (!strict) {
4377
+ return true;
4378
+ }
4379
+ if (f1 && f2 && canMerge(f1, f2)) {
4380
+ return f1.op === f2.op && ((0, import_vuu_utils4.isSingleValueFilter)(f1) && (0, import_vuu_utils4.isSingleValueFilter)(f2) && f1.value === f2.value || (0, import_vuu_utils4.isMultiValueFilter)(f1) && (0, import_vuu_utils4.isMultiValueFilter)(f2) && sameValues(f1.values, f2.values));
4381
+ }
4382
+ return false;
4383
+ };
4384
+ var updateFilter = (filter, newFilter, mode) => {
4385
+ if (filter && newFilter) {
4386
+ if (mode === "replace") {
4387
+ return newFilter;
4388
+ }
4389
+ if (filter.op === "and") {
4390
+ return {
4391
+ ...filter,
4392
+ filters: filter.filters.concat(newFilter)
4393
+ };
4394
+ }
4395
+ const { column: columnName } = newFilter;
4396
+ if (columnName) {
4397
+ const existingClause = newFilter.column ? (0, import_vuu_utils4.extractFilterForColumn)(filter, columnName) : void 0;
4398
+ if (existingClause && columnName) {
4399
+ const result = removeFilterForColumn(filter, { name: columnName });
4400
+ return updateFilter(result, newFilter, "add");
4401
+ }
4402
+ }
4403
+ return {
4404
+ op: "and",
4405
+ filters: [filter, newFilter]
4406
+ };
4407
+ }
4408
+ if (newFilter) {
4409
+ return newFilter;
4410
+ }
4411
+ return filter;
4412
+ };
4413
+ var getTypeaheadFilter = (column, filterValues, isStartsWithFilter) => {
4414
+ if (filterValues.length === 0) {
4415
+ return void 0;
4416
+ }
4417
+ if (isStartsWithFilter) {
4418
+ const startsWith = filterValues[0].substring(0, filterValues[0].length - 3);
4419
+ return {
4420
+ column,
4421
+ op: "starts",
4422
+ value: `"${startsWith}"`
4423
+ };
4424
+ }
4425
+ return {
4426
+ column,
4427
+ op: "in",
4428
+ values: filterValues.map((value) => `"${value}"`)
4429
+ };
4430
+ };
4431
+ var getNumericFilter = (column, operator, value) => {
4432
+ if (operator === void 0)
4433
+ return void 0;
4434
+ if (value === void 0 || isNaN(value))
4435
+ return void 0;
4436
+ return { column, op: operator, value };
4437
+ };
32
4438
  /*! Bundled license information:
33
4439
 
34
4440
  classnames/index.js: