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