postgres-query-box 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2555 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/index.js
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ LATENCY: () => LATENCY,
33
+ LAT_FIELD: () => LAT_FIELD,
34
+ METHODS: () => METHODS,
35
+ OP_INFO: () => OP_INFO,
36
+ PostgresQueryBox: () => PostgresQueryBox_default,
37
+ STATUS_CODES: () => STATUS_CODES,
38
+ TYPE_LABEL: () => TYPE_LABEL,
39
+ buildSchema: () => buildSchema,
40
+ context: () => context,
41
+ evaluate: () => evaluate,
42
+ format: () => format,
43
+ fromTree: () => fromTree,
44
+ ipToBig: () => ipToBig,
45
+ opsFor: () => opsFor,
46
+ parse: () => parse,
47
+ parseRange: () => parseRange,
48
+ schemaFromFields: () => schemaFromFields,
49
+ toSql: () => toSql,
50
+ toTree: () => toTree,
51
+ tokenize: () => tokenize,
52
+ validate: () => validate
53
+ });
54
+ module.exports = __toCommonJS(src_exports);
55
+
56
+ // src/react/PostgresQueryBox.jsx
57
+ var import_react6 = require("react");
58
+ var import_react7 = require("@phosphor-icons/react");
59
+
60
+ // src/core/engine.js
61
+ var LAT_A = "metadata.responseTimestamp";
62
+ var LAT_B = "metadata.requestTimestamp";
63
+ var LATENCY = `(${LAT_A} - ${LAT_B})`;
64
+ var VALUE_FIELDS = ["data.request.verb", "data.response.statusCode"];
65
+ var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE", "CONNECT", "QUERY"];
66
+ var STATUS_CODES = [100, 101, 102, 103, 200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 307, 308, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511].map(String);
67
+ var CATALOG = { "data.request.verb": METHODS, "data.response.statusCode": STATUS_CODES };
68
+ var COMMON = ["data.request.verb", "data.response.statusCode", "data.request.path", "data.request.hostname"];
69
+ var KW = /* @__PURE__ */ new Set(["AND", "OR", "NOT", "CONTAINS", "PRESENT", "ABSENT", "BETWEEN", "ANYONE", "NONEOF", "IP", "IN_RANGE", "NOT_IN_RANGE", "COUNT", "WITHIN", "GROUP", "BY", "LATENCY"]);
70
+ var OPS = ["!~*", "!~", "~*", "==", "!=", "<=", ">=", "~", "<", ">", "="];
71
+ var CMP = /* @__PURE__ */ new Set(["<", "<=", ">", ">="]);
72
+ var REGEX = /* @__PURE__ */ new Set(["~", "~*", "!~", "!~*"]);
73
+ var TEXT_OPS = /* @__PURE__ */ new Set(["~", "~*", "!~", "!~*", "CONTAINS", "NOT CONTAINS"]);
74
+ var UNIT = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
75
+ var pgRegex = (p) => {
76
+ const hex = (k, n) => [...Array(n)].every((_, j) => /[0-9a-fA-F]/.test(p[k + j] || "")) && !/[0-9a-fA-F]/.test(p[k + n] || "");
77
+ const open = [];
78
+ const closed = /* @__PURE__ */ new Set();
79
+ let groups = 0;
80
+ let cls2 = -1;
81
+ let first = 0;
82
+ let fixed = "";
83
+ let wb = false;
84
+ let bare = false;
85
+ let last = 0;
86
+ const size = [0];
87
+ const add = (w) => {
88
+ size[size.length - 1] += w;
89
+ last = w;
90
+ };
91
+ for (let i = 0; i < p.length; ) {
92
+ const c = p[i];
93
+ const d = p[i + 1];
94
+ if (cls2 < 0 && bare && (c === "*" || c === "+" || c === "?" || c === "{" && /\d/.test(d || ""))) return { msg: "Postgres cannot repeat \\y, \\m, \\A, \\Z or a lookaround" };
95
+ bare = false;
96
+ if (c === "\\") {
97
+ if (/[1-9]/.test(d) && !/\d/.test(p[i + 2] || "") && cls2 < 0 && !closed.has(+d)) return { msg: `\\${d} needs group ${d} to be closed before it` };
98
+ if (cls2 >= 0 && /\d/.test(d)) return { msg: `Inside brackets, write the character itself instead of \\${d}` };
99
+ if (d === "x" && !hex(i + 2, 2)) return { msg: "Write \\x with exactly two hex digits, like \\x41" };
100
+ if (d === "u" && !hex(i + 2, 4)) return { msg: "Write \\u with exactly four hex digits, like \\u0041" };
101
+ if (d === "c" && !/[A-Za-z]/.test(p[i + 2] || "")) return { msg: "Write \\c with a letter, like \\cA" };
102
+ if (cls2 >= 0 && /[dDwWsS]/.test(d) && (p[i + 2] === "-" && p[i + 3] && p[i + 3] !== "]" || p[i - 1] === "-" && i - 1 !== first)) return { msg: `A range like a-z cannot start or end with \\${d}` };
103
+ if ((d === "b" || d === "B") && cls2 < 0) {
104
+ wb = bare = true;
105
+ add(1);
106
+ fixed += "\\" + (d === "b" ? "y" : "Y");
107
+ i += 2;
108
+ continue;
109
+ }
110
+ if (/[A-Za-z]/.test(d) && !"dDwWsStnrfvxuc".includes(d) && !(cls2 < 0 ? "yYmMAZ" : "b").includes(d)) return { msg: `Postgres does not understand \\${d}. To match the letter ${d}, write ${d} without the backslash.` };
111
+ bare = cls2 < 0 && "yYmMAZ".includes(d);
112
+ if (cls2 < 0) add(1);
113
+ fixed += c + d;
114
+ i += 2;
115
+ continue;
116
+ }
117
+ if (cls2 >= 0) {
118
+ if (c === "[" && ":.=".includes(d || "-")) {
119
+ const m = p.slice(i).match(/^\[:(alnum|alpha|blank|cntrl|digit|graph|lower|print|punct|space|upper|xdigit|word):\]/);
120
+ if (!m) return { msg: "Inside brackets, write \\[ for a literal [" };
121
+ fixed += m[0];
122
+ i += m[0].length;
123
+ continue;
124
+ }
125
+ if (c === "]" && i > first) {
126
+ cls2 = -1;
127
+ add(1);
128
+ }
129
+ } else if (c === "[") {
130
+ if (d === "]" || d === "^" && p[i + 2] === "]") return { msg: "Postgres does not allow empty brackets [] or [^]" };
131
+ cls2 = i;
132
+ first = i + (d === "^" ? 2 : 1);
133
+ } else if (c === "(") {
134
+ size.push(0);
135
+ if (d !== "?") open.push(++groups);
136
+ else if (p[i + 2] === "<" && p[i + 3] !== "=" && p[i + 3] !== "!") return { msg: "Postgres does not support named groups like (?<name>...). Use ( ) instead." };
137
+ else {
138
+ open.push(p[i + 2] === ":" ? 0 : -1);
139
+ const pre = p.slice(i).match(/^\(\?(?:<[=!]|[:=!])/)[0];
140
+ fixed += pre;
141
+ i += pre.length;
142
+ continue;
143
+ }
144
+ } else if (c === ")") {
145
+ if (!open.length) return { msg: "Postgres reads this ) as having no matching (. Check where the brackets [ ] close." };
146
+ const g = open.pop();
147
+ if (g > 0) closed.add(g);
148
+ add(Math.max(size.pop(), 1));
149
+ bare = g === -1;
150
+ } else if (c === "{" && /\d/.test(d || "")) {
151
+ const m = p.slice(i).match(/^\{(\d+)(?:,(\d*))?\}/);
152
+ if (!m) return { msg: "Finish the repeat count, like {2} or {1,3}, or write \\{ for a literal {" };
153
+ if (+m[1] > 255 || +(m[2] || 0) > 255) return { msg: "Postgres allows at most 255 repeats, like {255}" };
154
+ const k = Math.max(+m[1], +(m[2] || 0));
155
+ size[size.length - 1] += last * (k - 1);
156
+ last *= k;
157
+ fixed += m[0];
158
+ i += m[0].length;
159
+ continue;
160
+ } else if (!"*+?".includes(c)) add(1);
161
+ fixed += c;
162
+ i++;
163
+ }
164
+ if (cls2 >= 0) return { msg: "Close the brackets with ]" };
165
+ if (size[0] > 1e4) return { msg: "This regex is too large for Postgres. Use smaller repeat counts." };
166
+ if (wb) return { msg: "Postgres reads \\b as a backspace. Use \\y for a word boundary and \\Y for the opposite.", fix: fixed };
167
+ return null;
168
+ };
169
+ var OP_INFO = {
170
+ "==": "equals",
171
+ "!=": "not equal",
172
+ "~": "matches regex",
173
+ "~*": "matches regex, any case",
174
+ "!~": "does not match regex",
175
+ "!~*": "does not match regex, any case",
176
+ "<": "less than",
177
+ "<=": "at most",
178
+ ">": "greater than",
179
+ ">=": "at least",
180
+ CONTAINS: "contains text",
181
+ "NOT CONTAINS": "does not contain text",
182
+ PRESENT: "has this field",
183
+ ABSENT: "missing this field",
184
+ BETWEEN: "between, both ends included",
185
+ ANYONE: "any one of",
186
+ NONEOF: "none of",
187
+ "IP IN_RANGE": "IP in range",
188
+ "IP NOT_IN_RANGE": "IP not in range"
189
+ };
190
+ var TYPE_LABEL = { string: "text", number: "number", boolean: "boolean", ip: "ip", numtext: "text", latency: "ms" };
191
+ function opsFor(f) {
192
+ if (!f) return [];
193
+ if (f.type === "latency") return [">", "<", ">=", "<=", "BETWEEN"];
194
+ if (f.type === "number") return ["==", "!=", "<", "<=", ">", ">=", "BETWEEN", "ANYONE", "NONEOF", "PRESENT", "ABSENT"];
195
+ if (f.type === "boolean") return ["==", "!=", "PRESENT", "ABSENT"];
196
+ if (f.type === "ip") return ["IP IN_RANGE", "IP NOT_IN_RANGE", "==", "!=", "CONTAINS", "NOT CONTAINS", "~", "~*", "!~", "!~*", "ANYONE", "NONEOF", "PRESENT", "ABSENT"];
197
+ if (f.type === "numtext") return ["==", "!=", ">=", ">", "<", "<=", "BETWEEN", "ANYONE", "NONEOF", "~", "!~", "CONTAINS", "NOT CONTAINS", "PRESENT", "ABSENT"];
198
+ return ["==", "!=", "CONTAINS", "NOT CONTAINS", "~", "~*", "!~", "!~*", "ANYONE", "NONEOF", "PRESENT", "ABSENT"];
199
+ }
200
+ var GROUPS = [
201
+ ["data.request.headerParams.", "Request headers"],
202
+ ["data.request.queryParams.", "Query params"],
203
+ ["data.request.", "Request"],
204
+ ["data.response.headerParams.", "Response headers"],
205
+ ["data.response.", "Response"],
206
+ ["metadata.additionalMetadata.", "Additional metadata"],
207
+ ["metadata.", "Metadata"]
208
+ ];
209
+ function buildSchema(rows) {
210
+ const map = /* @__PURE__ */ new Map();
211
+ const visit = (o, segs) => {
212
+ for (const k of Object.keys(o)) {
213
+ const v = o[k];
214
+ const ks = [...segs, k];
215
+ const p = ks.join(".");
216
+ if (v && typeof v === "object" && !Array.isArray(v)) visit(v, ks);
217
+ else {
218
+ let f = map.get(p);
219
+ if (!f) map.set(p, f = { path: p, segs: ks, count: 0, kinds: /* @__PURE__ */ new Set(), numeric: true, ip: true, values: /* @__PURE__ */ new Map() });
220
+ f.count++;
221
+ f.kinds.add(typeof v);
222
+ if (typeof v === "string") {
223
+ if (!/^-?\d+(\.\d+)?$/.test(v)) f.numeric = false;
224
+ if (!ipToBig(v)) f.ip = false;
225
+ }
226
+ if (VALUE_FIELDS.includes(p)) f.values.set(v, (f.values.get(v) || 0) + 1);
227
+ }
228
+ }
229
+ };
230
+ for (const r of rows) visit({ data: r.data, metadata: r.metadata }, []);
231
+ return schemaFromFields(
232
+ [...map.values()].map((f) => {
233
+ const kind = f.kinds.size === 1 ? [...f.kinds][0] : "string";
234
+ const type = kind === "number" ? "number" : kind === "boolean" ? "boolean" : f.ip ? "ip" : f.numeric ? "numtext" : "string";
235
+ const values = [...f.values.entries()].sort((a, b) => b[1] - a[1]).map(([v, n]) => ({ v, n }));
236
+ return { path: f.path, segs: f.segs, count: f.count, type, values };
237
+ }),
238
+ rows.length
239
+ );
240
+ }
241
+ function schemaFromFields(list, total = 0) {
242
+ const fields = list.map((f) => ({
243
+ ...f,
244
+ segs: f.segs || f.path.split("."),
245
+ type: f.type || "string",
246
+ count: f.count ?? total,
247
+ group: f.group || (COMMON.includes(f.path) ? "Common" : (GROUPS.find(([p]) => f.path.startsWith(p)) || [, "Other"])[1]),
248
+ values: f.values || []
249
+ }));
250
+ const order = ["Common", ...GROUPS.map((g) => g[1]), "Other"];
251
+ fields.sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group) || (a.group === "Common" ? COMMON.indexOf(a.path) - COMMON.indexOf(b.path) : a.path.localeCompare(b.path)));
252
+ const byPath = Object.fromEntries(fields.map((f) => [f.path, f]));
253
+ const short = {};
254
+ for (const f of fields) {
255
+ for (let n = 1; n <= f.segs.length; n++) {
256
+ const tail = f.segs.slice(-n).join(".");
257
+ if (fields.filter((g) => g.segs.length >= n && g.segs.slice(-n).join(".") === tail).length === 1) {
258
+ short[f.path] = tail;
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ return { fields, byPath, short, total };
264
+ }
265
+ function ipToBig(s) {
266
+ if (typeof s !== "string") return null;
267
+ const v4 = (x2) => {
268
+ const p = x2.split(".");
269
+ if (p.length !== 4 || p.some((n2) => !/^\d{1,3}$/.test(n2) || +n2 > 255)) return null;
270
+ return p.reduce((a2, n2) => a2 * 256n + BigInt(n2), 0n);
271
+ };
272
+ if (s.includes(".") && !s.includes(":")) {
273
+ const n2 = v4(s);
274
+ return n2 === null ? null : { v: 4, n: n2 };
275
+ }
276
+ if (!/^[0-9a-fA-F:.]+$/.test(s) || !s.includes(":")) return null;
277
+ let tail = null;
278
+ let x = s;
279
+ const m = s.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
280
+ if (m) {
281
+ tail = /(^|\.)0\d/.test(m[2]) ? null : v4(m[2]);
282
+ if (tail === null) return null;
283
+ x = m[1] + "0:0";
284
+ }
285
+ const halves = x.split("::");
286
+ if (halves.length > 2) return null;
287
+ const a = halves[0] ? halves[0].split(":") : [];
288
+ const b = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
289
+ const fill = halves.length === 2 ? 8 - a.length - b.length : 0;
290
+ if (halves.length === 2 && fill < 1) return null;
291
+ const parts = [...a, ...Array(fill).fill("0"), ...b];
292
+ if (parts.length !== 8 || parts.some((p) => !/^[0-9a-fA-F]{1,4}$/.test(p))) return null;
293
+ let n = parts.reduce((acc, p) => acc * 65536n + BigInt(parseInt(p, 16)), 0n);
294
+ if (tail !== null) n = (n >> 32n << 32n) + tail;
295
+ if (n >> 32n === 0xffffn) return { v: 4, n: n & 0xffffffffn };
296
+ return { v: 6, n };
297
+ }
298
+ function parseRange(s) {
299
+ if (typeof s !== "string") return null;
300
+ if (s.includes("/")) {
301
+ const [base, bits, extra2] = s.split("/");
302
+ const ip = ipToBig(base);
303
+ const max = ip && ip.v === 4 ? 32 : 128;
304
+ if (!ip || extra2 !== void 0 || !/^(0|[1-9]\d*)$/.test(bits) || +bits > max) return null;
305
+ const host = BigInt(max - +bits);
306
+ const lo = ip.n >> host << host;
307
+ return { v: ip.v, lo, hi: lo + (1n << host) - 1n };
308
+ }
309
+ const [a, b, extra] = s.split("-");
310
+ const x = ipToBig(a);
311
+ const y = ipToBig(b);
312
+ if (!x || !y || extra !== void 0 || x.v !== y.v || x.n > y.n) return null;
313
+ return { v: x.v, lo: x.n, hi: y.n };
314
+ }
315
+ var LAT_FIELD = { path: "@latency", type: "latency" };
316
+ function tokenize(src) {
317
+ const out = [];
318
+ let i = 0;
319
+ while (i < src.length) {
320
+ const c = src[i];
321
+ if (/\s/.test(c)) {
322
+ i++;
323
+ continue;
324
+ }
325
+ const s = i;
326
+ if (c === '"') {
327
+ i++;
328
+ let v = "";
329
+ let closed = false;
330
+ while (i < src.length) {
331
+ if (src[i] === "\\" && (src[i + 1] === '"' || src[i + 1] === "\\")) {
332
+ v += src[i + 1];
333
+ i += 2;
334
+ continue;
335
+ }
336
+ if (src[i] === '"') {
337
+ closed = true;
338
+ i++;
339
+ break;
340
+ }
341
+ v += src[i++];
342
+ }
343
+ out.push({ t: "str", v, s, e: i, closed, raw: src.slice(s, i) });
344
+ continue;
345
+ }
346
+ const prev = out[out.length - 1];
347
+ const neg = c === "-" && /\d/.test(src[i + 1] || "") && prev && (prev.t === "op" || prev.t === "punct" && prev.v !== ")" || prev.t === "kw" && prev.v !== "COUNT");
348
+ if (/\d/.test(c) || neg) {
349
+ const m = src.slice(i).match(/^-?\d+(?:\.\d+)?/)[0];
350
+ i += m.length;
351
+ if (/[smhd]/.test(src[i] || "") && !/[A-Za-z0-9_]/.test(src[i + 1] || "")) {
352
+ i++;
353
+ out.push({ t: "dur", v: m + src[i - 1], ms: Number(m) * UNIT[src[i - 1]], s, e: i, raw: src.slice(s, i) });
354
+ } else out.push({ t: "num", v: Number(m), s, e: i, raw: m });
355
+ continue;
356
+ }
357
+ if (/[A-Za-z_]/.test(c)) {
358
+ const m = src.slice(i).match(/^[A-Za-z_](?:[A-Za-z0-9_.-]|\\\.)*/)[0];
359
+ i += m.length;
360
+ const up = m.toUpperCase();
361
+ if (KW.has(up)) out.push({ t: "kw", v: up, s, e: i, raw: m });
362
+ else if (up === "TRUE" || up === "FALSE") out.push({ t: "bool", v: up === "TRUE", s, e: i, raw: m });
363
+ else out.push({ t: "word", v: m, s, e: i, raw: m });
364
+ continue;
365
+ }
366
+ const op = OPS.find((o) => src.startsWith(o, i));
367
+ if (op) {
368
+ i += op.length;
369
+ out.push({ t: "op", v: op, s, e: i, raw: op });
370
+ continue;
371
+ }
372
+ i++;
373
+ if (c === "-") out.push({ t: "minus", v: "-", s, e: i, raw: "-" });
374
+ else if ("()[],".includes(c)) out.push({ t: "punct", v: c, s, e: i, raw: c });
375
+ else out.push({ t: "bad", v: c, s, e: i, raw: c });
376
+ }
377
+ return out;
378
+ }
379
+ var near = (word, schema) => {
380
+ const w = word.toLowerCase();
381
+ const leaf = w.split(".").pop();
382
+ const hits = schema.fields.filter((f) => f.path.toLowerCase().includes(leaf) || leaf.includes(f.path.split(".").pop().toLowerCase()));
383
+ return hits.slice(0, 4).map((f) => f.path);
384
+ };
385
+ var lit = (v) => typeof v === "string" ? '"' + v.replace(/\\(?=[\\"]|$)/g, "\\\\").replace(/"/g, '\\"') + '"' : String(v);
386
+ function parse(src, schema) {
387
+ const toks = tokenize(src);
388
+ const errors = [];
389
+ let p = 0;
390
+ const peek = (o = 0) => toks[p + o];
391
+ const isKw = (t, k) => t && t.t === "kw" && t.v === k;
392
+ const isP = (t, v) => t && t.t === "punct" && t.v === v;
393
+ const role = (t, r) => t && (t.role = r);
394
+ const fail = (t, msg, extra) => {
395
+ throw { s: t ? t.s : src.length, e: t ? t.e : src.length, msg, eof: !t, ...extra };
396
+ };
397
+ const word = (t) => t ? t.raw : "";
398
+ const latencyAhead = () => {
399
+ var _a, _b, _c;
400
+ return isP(peek(), "(") && ((_a = peek(1)) == null ? void 0 : _a.t) === "word" && ((_b = peek(2)) == null ? void 0 : _b.t) === "minus" && ((_c = peek(3)) == null ? void 0 : _c.t) === "word" && isP(peek(4), ")");
401
+ };
402
+ const value = (allowBool = true, type) => {
403
+ const t = peek();
404
+ if (!t) fail(null, "Add a value");
405
+ if (t.t === "str") {
406
+ if (!t.closed) fail(t, "Close the quote", { at: t.e, fix: { s: t.e, e: t.e, text: '"', verb: "Add", label: '"' } });
407
+ if (t.v.includes("\0")) errors.push({ s: t.s, e: t.e, msg: "Remove the hidden NUL character from this text" });
408
+ role(t, "str");
409
+ } else if (t.t === "num") role(t, "num");
410
+ else if (t.t === "bool" && allowBool) role(t, "bool");
411
+ else if (t.t !== "word" || type === "number" || type === "latency") fail(t, `Expected a ${type === "number" || type === "latency" ? "number" : "value"}, found ${word(t)}`);
412
+ else fail(t, `Expected a value, found ${word(t)}`, { fix: (type === "boolean" ? ["true", "false"] : [lit(t.raw)]).map((x) => ({ s: t.s, e: t.e, text: x, verb: "Use", label: x })) });
413
+ p++;
414
+ return { v: t.v, raw: t.t === "str" ? t.raw : t.t === "bool" ? String(t.v) : t.raw, tok: t };
415
+ };
416
+ const list = (allowBool = true, type) => {
417
+ const o = peek();
418
+ if (!isP(o, "[")) fail(o, `Expected a list like ${type === "number" ? "[1, 2]" : type === "boolean" ? "[true, false]" : '["a", "b"]'}`, o && ["str", "num", "bool"].includes(o.t) ? { fix: { s: o.s, e: o.s, text: "[", verb: "Add", label: "[" } } : void 0);
419
+ p++;
420
+ const vals = [];
421
+ if (isP(peek(), "]")) fail(peek(), "Add at least one value to the list");
422
+ for (; ; ) {
423
+ vals.push(value(allowBool, type));
424
+ if (isP(peek(), ",")) {
425
+ p++;
426
+ continue;
427
+ }
428
+ if (isP(peek(), "]")) {
429
+ const c2 = peek();
430
+ p++;
431
+ return { vals, e: c2.e };
432
+ }
433
+ const c = peek();
434
+ const prev = peek(-1);
435
+ const ins = (text, verb, label) => ({ s: prev.e, e: prev.e, text, verb, label });
436
+ if (c && ["str", "num", "bool"].includes(c.t)) fail(c, `Separate list values with a comma, between ${prev.raw} and ${c.raw}`, { s: prev.s, at: prev.e, fix: ins(",", "Add", ",") });
437
+ fail(c, `Close the list with ] after ${prev.raw}`, { s: o.s, e: o.e, at: prev.e, fix: ins("]", "Add", "]") });
438
+ }
439
+ };
440
+ const typeFix = (f, val, display) => {
441
+ if (!f) return;
442
+ const t = val.tok;
443
+ const isNumText = typeof val.v === "string" && /^-?\d+(\.\d+)?$/.test(val.v);
444
+ if ((f.type === "string" || f.type === "numtext" || f.type === "ip") && t.t !== "str") {
445
+ errors.push({ s: t.s, e: t.e, msg: `${display} is stored as text, so ${t.raw} never matches. Use "${t.raw}".`, fix: { s: t.s, e: t.e, text: `"${t.raw}"`, label: `"${t.raw}"` } });
446
+ } else if (f.type === "number" && t.t !== "num") {
447
+ if (isNumText) errors.push({ s: t.s, e: t.e, msg: `${display} is stored as a number, so ${t.raw} never matches. Use ${val.v}.`, fix: { s: t.s, e: t.e, text: val.v, label: val.v } });
448
+ else errors.push({ s: t.s, e: t.e, msg: `${display} holds numbers, ${t.raw} is not one` });
449
+ } else if (f.type === "boolean" && t.t !== "bool") {
450
+ if (t.t === "str" && /^(true|false)$/i.test(val.v)) errors.push({ s: t.s, e: t.e, msg: `${display} is a boolean, write ${val.v.toLowerCase()} without quotes`, fix: { s: t.s, e: t.e, text: val.v.toLowerCase(), label: val.v.toLowerCase() } });
451
+ else errors.push({ s: t.s, e: t.e, msg: `${display} is a boolean, use true or false` });
452
+ }
453
+ };
454
+ const numFix = (val, display) => {
455
+ const t = val.tok;
456
+ if (t.t === "num") return;
457
+ if (t.t === "str" && /^-?\d+(\.\d+)?$/.test(val.v)) errors.push({ s: t.s, e: t.e, msg: `Numeric operators take a bare number. Use ${val.v}.`, fix: { s: t.s, e: t.e, text: val.v, label: val.v } });
458
+ else errors.push({ s: t.s, e: t.e, msg: `${display} needs a number here, found ${t.raw}` });
459
+ };
460
+ const condition = () => {
461
+ const t = peek();
462
+ let field;
463
+ let fs = t.s;
464
+ let fe;
465
+ if (isP(t, "(")) {
466
+ const a = peek(1);
467
+ const b = peek(3);
468
+ [t, a, peek(2), b, peek(4)].forEach((x) => role(x, "field"));
469
+ if (a.v !== LAT_A || b.v !== LAT_B) errors.push({ s: t.s, e: peek(4).e, msg: `Latency is written ${LATENCY}`, fix: { s: t.s, e: peek(4).e, text: LATENCY, label: LATENCY } });
470
+ field = "@latency";
471
+ fe = peek(4).e;
472
+ p += 5;
473
+ } else if (isKw(t, "LATENCY")) {
474
+ role(t, "field");
475
+ field = "@latency";
476
+ fe = t.e;
477
+ p++;
478
+ } else if (t.t === "word") {
479
+ role(t, "field");
480
+ field = t.v.replace(/\\\./g, ".");
481
+ fe = t.e;
482
+ p++;
483
+ if (!schema.byPath[field]) {
484
+ const n = near(field, schema);
485
+ errors.push({ s: t.s, e: t.e, msg: `${field} is not a field in this index`, near: n });
486
+ }
487
+ } else fail(t, t.t === "kw" ? `${t.raw} needs a condition before it` : `Expected a field, found ${word(t)}`);
488
+ const f = field === "@latency" ? LAT_FIELD : schema.byPath[field];
489
+ const display = field === "@latency" ? "Latency" : field;
490
+ const o = peek();
491
+ if (!o && !f) throw errors.pop();
492
+ if (!o) fail(null, `Add an operator after ${display}`);
493
+ let op;
494
+ if (o.t === "op") {
495
+ op = o.v === "=" ? "==" : o.v;
496
+ role(o, "op");
497
+ p++;
498
+ } else if (o.t === "kw" && ["CONTAINS", "PRESENT", "ABSENT", "BETWEEN", "ANYONE", "NONEOF"].includes(o.v)) {
499
+ op = o.v;
500
+ role(o, "op");
501
+ p++;
502
+ } else if (isKw(o, "NOT") && isKw(peek(1), "CONTAINS")) {
503
+ op = "NOT CONTAINS";
504
+ role(o, "op");
505
+ role(peek(1), "op");
506
+ p += 2;
507
+ } else if (isKw(o, "IP") && (isKw(peek(1), "IN_RANGE") || isKw(peek(1), "NOT_IN_RANGE"))) {
508
+ op = "IP " + peek(1).v;
509
+ role(o, "op");
510
+ role(peek(1), "op");
511
+ p += 2;
512
+ } else if (isKw(o, "IP")) fail(peek(1) || o, "After IP write IN_RANGE or NOT_IN_RANGE");
513
+ else if (o.t === "minus") {
514
+ const b = peek(1);
515
+ const open = peek(-2);
516
+ if ((b == null ? void 0 : b.t) === "word" && isP(open, "(")) fail(o, `Missing ) after ${b.raw}`, { s: open.s, e: open.e, at: b.e, fix: { s: b.e, e: b.e, text: ")", verb: "Add", label: ")" } });
517
+ if ((b == null ? void 0 : b.t) === "word") fail(o, `Latency is written ${LATENCY}`, { s: t.s, e: b.e, at: b.e, fix: { s: t.s, e: b.e, text: LATENCY, verb: "Wrap in", label: "( )" } });
518
+ fail(o, `Latency is written ${LATENCY}`);
519
+ } else fail(o, `Expected an operator after ${display}, found ${word(o)}`);
520
+ const node = { k: "cond", field, op, s: fs };
521
+ if (f && !opsFor(f).includes(op)) {
522
+ const why = f.type === "latency" ? "Latency takes >, <, >=, <= or BETWEEN" : op.startsWith("IP") ? "IP operators work only on fields that hold IP addresses" : CMP.has(op) || op === "BETWEEN" ? `${op} needs a number field, ${display} holds ${TYPE_LABEL[f.type]}` : `${op} does not apply to ${display} (${TYPE_LABEL[f.type]})`;
523
+ const base = op.endsWith("*") && opsFor(f).includes(op.slice(0, -1)) ? op.slice(0, -1) : null;
524
+ errors.push({ s: o.s, e: (peek(-1) || o).e, msg: base ? `${op} does not apply to ${display}, use ${base}` : why, ...base ? { fix: { s: o.s, e: o.e, text: base, verb: "Use", label: base } } : {} });
525
+ }
526
+ if (op === "PRESENT" || op === "ABSENT") {
527
+ node.e = o.e;
528
+ return node;
529
+ }
530
+ if (op === "BETWEEN") {
531
+ const lo = value(false, "number");
532
+ const a = peek();
533
+ if (!isKw(a, "AND")) fail(a, "BETWEEN needs AND, like BETWEEN 200 AND 299", (a == null ? void 0 : a.t) === "num" ? { s: lo.tok.s, e: a.e, at: lo.tok.e, fix: { s: lo.tok.e, e: lo.tok.e, text: " AND", verb: "Add", label: "AND" } } : void 0);
534
+ role(a, "op");
535
+ p++;
536
+ const hi = value(false, "number");
537
+ numFix(lo, display);
538
+ numFix(hi, display);
539
+ if (Number(lo.v) > Number(hi.v)) errors.push({ s: lo.tok.s, e: hi.tok.e, msg: "The first number must be the smaller one", fix: { s: lo.tok.s, e: hi.tok.e, text: `${hi.raw} AND ${lo.raw}`, verb: "Swap to", label: `${hi.raw} AND ${lo.raw}` } });
540
+ Object.assign(node, { lo, hi, e: hi.tok.e });
541
+ return node;
542
+ }
543
+ if (op === "ANYONE" || op === "NONEOF") {
544
+ const l = list(true, f == null ? void 0 : f.type);
545
+ for (const v2 of l.vals) typeFix(f, v2, display);
546
+ Object.assign(node, { vals: l.vals, e: l.e });
547
+ return node;
548
+ }
549
+ if (op.startsWith("IP")) {
550
+ let vals;
551
+ if (isP(peek(), "[")) {
552
+ const l = list(false);
553
+ vals = l.vals;
554
+ node.e = l.e;
555
+ node.list = true;
556
+ } else {
557
+ const v2 = value(false);
558
+ vals = [v2];
559
+ node.e = v2.tok.e;
560
+ }
561
+ for (const v2 of vals) {
562
+ if (v2.tok.t !== "str") errors.push({ s: v2.tok.s, e: v2.tok.e, msg: 'Write the range in quotes, like "10.0.0.0/8"' });
563
+ else if (!v2.v.trim()) errors.push({ s: v2.tok.s, e: v2.tok.e, msg: 'Add a range, like "10.0.0.0/8" or "10.0.0.1-10.0.0.50"' });
564
+ else if (!parseRange(v2.v.includes("/") || v2.v.includes("-") ? v2.v : v2.v + (v2.v.includes(":") ? "/128" : "/32"))) errors.push({ s: v2.tok.s, e: v2.tok.e, msg: `${v2.raw} is not a valid CIDR or range. Use "10.0.0.0/8" or "10.0.0.1-10.0.0.50".` });
565
+ }
566
+ node.vals = vals;
567
+ return node;
568
+ }
569
+ const v = value(!TEXT_OPS.has(op), f == null ? void 0 : f.type);
570
+ node.val = v;
571
+ node.e = v.tok.e;
572
+ if (TEXT_OPS.has(op) && v.tok.t !== "str") errors.push({ s: v.tok.s, e: v.tok.e, msg: `${op} takes text in quotes`, fix: { s: v.tok.s, e: v.tok.e, text: `"${v.tok.raw}"`, label: `"${v.tok.raw}"` } });
573
+ else if (REGEX.has(op)) {
574
+ try {
575
+ new RegExp(v.v);
576
+ const pg = pgRegex(v.v);
577
+ if (pg) errors.push({ s: v.tok.s, e: v.tok.e, msg: pg.msg, ...pg.fix ? { fix: { s: v.tok.s, e: v.tok.e, text: lit(pg.fix), label: lit(pg.fix) } } : {} });
578
+ } catch (err) {
579
+ errors.push({ s: v.tok.s, e: v.tok.e, msg: `Invalid regex: ${String(err.message).replace(/^Invalid regular expression: /, "")}` });
580
+ }
581
+ } else if (CMP.has(op)) numFix(v, display);
582
+ else if (op === "==" || op === "!=") typeFix(f, v, display);
583
+ return node;
584
+ };
585
+ const countClause = () => {
586
+ const t = peek();
587
+ role(t, "fn");
588
+ p++;
589
+ if (!isP(peek(), "(") || !isP(peek(1), ")")) fail(peek(), "Write COUNT()");
590
+ role(peek(), "fn");
591
+ role(peek(1), "fn");
592
+ p += 2;
593
+ const o = peek();
594
+ if (!o || o.t !== "op" || REGEX.has(o.v) || o.v === "!=") fail(o, "COUNT() takes >, <, >=, <= or ==", (o == null ? void 0 : o.t) === "num" ? { fix: { s: o.s, e: o.s, text: "> ", verb: "Add", label: ">" } } : void 0);
595
+ role(o, "op");
596
+ p++;
597
+ const n = peek();
598
+ if (!n || n.t !== "num") fail(n, "COUNT() needs a number, like COUNT() > 50");
599
+ role(n, "num");
600
+ p++;
601
+ const node = { k: "count", op: o.v === "=" ? "==" : o.v, n: n.v, s: t.s, e: n.e };
602
+ if (isKw(peek(), "WITHIN")) {
603
+ role(peek(), "kw");
604
+ p++;
605
+ const d = peek();
606
+ if (d && d.t === "num") fail(d, `Add a unit: ${d.raw}s, ${d.raw}m, ${d.raw}h or ${d.raw}d`, { fix: ["s", "m", "h", "d"].map((u) => ({ s: d.s, e: d.e, text: d.raw + u, verb: "Use", label: d.raw + u })) });
607
+ if (!d || d.t !== "dur") fail(d, "WITHIN takes a window like 5m");
608
+ role(d, "num");
609
+ p++;
610
+ node.within = d.v;
611
+ node.ms = d.ms;
612
+ node.e = d.e;
613
+ }
614
+ if (isKw(peek(), "GROUP")) {
615
+ role(peek(), "kw");
616
+ p++;
617
+ if (!isKw(peek(), "BY")) fail(peek(), "Write GROUP BY");
618
+ role(peek(), "kw");
619
+ p++;
620
+ const g = peek();
621
+ if (!g || g.t !== "word") fail(g, "GROUP BY needs a field");
622
+ role(g, "field");
623
+ p++;
624
+ const by = g.v.replace(/\\\./g, ".");
625
+ if (!schema.byPath[by]) errors.push({ s: g.s, e: g.e, msg: `${g.v} is not a field in this index`, near: near(g.v, schema) });
626
+ node.by = by;
627
+ node.e = g.e;
628
+ }
629
+ return node;
630
+ };
631
+ const primary = () => {
632
+ const t = peek();
633
+ if (!t) fail(null, "Add a condition");
634
+ if (isP(t, "(") && !latencyAhead()) {
635
+ role(t, "punct");
636
+ p++;
637
+ const x = orExpr();
638
+ const c = peek();
639
+ if (!isP(c, ")")) {
640
+ const end = peek(-1).e;
641
+ const ins = (text, label) => ({ s: end, e: end, text, verb: "Add", label });
642
+ if (c) fail(c, `Expected ) or AND/OR before ${word(c)}`, { at: end, fix: [...toks.slice(p).some((x2) => isP(x2, ")")) ? [] : [ins(")", ")")], ins(" AND", "AND"), ins(" OR", "OR")] });
643
+ fail(c, "Close the group with ). The highlighted ( is never closed.", { s: t.s, e: t.e, at: end, fix: [ins(")", ")"), { s: t.s, e: t.e, text: "", verb: "Remove", label: "this (" }] });
644
+ }
645
+ role(c, "punct");
646
+ p++;
647
+ return { k: "group", x, s: t.s, e: c.e };
648
+ }
649
+ if (isKw(t, "COUNT")) return countClause();
650
+ return condition();
651
+ };
652
+ const notExpr = () => {
653
+ const t = peek();
654
+ if (isKw(t, "NOT")) {
655
+ role(t, "kw");
656
+ p++;
657
+ const x = notExpr();
658
+ return { k: "not", x, s: t.s, e: x.e };
659
+ }
660
+ return primary();
661
+ };
662
+ const join = (k, next) => () => {
663
+ const items = [next()];
664
+ while (isKw(peek(), k)) {
665
+ role(peek(), "kw");
666
+ p++;
667
+ items.push(next());
668
+ }
669
+ return items.length === 1 ? items[0] : { k: k.toLowerCase(), items, s: items[0].s, e: items[items.length - 1].e };
670
+ };
671
+ const andExpr = join("AND", notExpr);
672
+ const orExpr = join("OR", andExpr);
673
+ let ast = null;
674
+ let syntax = null;
675
+ if (toks.length) {
676
+ try {
677
+ ast = orExpr();
678
+ if (p < toks.length) {
679
+ const t = peek();
680
+ const end = peek(-1).e;
681
+ if (isP(t, ")")) fail(t, "This ) has no matching (", { fix: { s: t.s, e: t.e, text: "", verb: "Remove", label: "this )" } });
682
+ fail(t, `Join conditions with AND or OR before ${word(t)}`, { at: end, fix: [" AND", " OR"].map((x) => ({ s: end, e: end, text: x, verb: "Add", label: x.trim() })) });
683
+ }
684
+ } catch (err) {
685
+ if (!err || err.msg === void 0) throw err;
686
+ syntax = err;
687
+ ast = null;
688
+ const k = toks.findIndex((t, j) => {
689
+ var _a;
690
+ return t.t === "str" && t.closed && ((_a = toks[j + 1]) == null ? void 0 : _a.t) === "word" && toks[j + 1].s === t.e && /\s(?:AND|OR|ANYONE|NONEOF|CONTAINS|BETWEEN)\s|[=!<>~[]|,\s*$|\b(?:data|metadata)\./.test(t.v);
691
+ });
692
+ if (k >= 0 && toks[k].s <= Math.max(syntax.s, syntax.e, syntax.at ?? 0)) {
693
+ const w = toks[k].raw.slice(1).match(/^[^\s",]*/)[0];
694
+ const at = toks[k].s + 1 + w.length;
695
+ syntax = { s: toks[k].s, e: at, at, msg: `Missing " after ${w}`, fix: { s: at, e: at, text: '"', verb: "Add", label: `" after ${w}` } };
696
+ }
697
+ }
698
+ }
699
+ if (ast) {
700
+ const counts = [];
701
+ const walk = (n, top) => {
702
+ if (n.k === "count") counts.push({ n, top });
703
+ if (n.items) n.items.forEach((x, i) => walk(x, n === ast && n.k === "and" && i === n.items.length - 1));
704
+ if (n.x) walk(n.x, false);
705
+ };
706
+ walk(ast, ast.k === "count");
707
+ if (counts.length > 1) counts.slice(1).forEach(({ n }) => errors.push({ s: n.s, e: n.e, msg: "Only one COUNT() per query" }));
708
+ else if (counts.length === 1 && !counts[0].top) errors.push({ s: counts[0].n.s, e: counts[0].n.e, msg: "COUNT() goes last, joined with AND" });
709
+ }
710
+ const all = syntax ? [syntax, ...errors] : errors;
711
+ all.sort((a, b) => a.s - b.s);
712
+ return { ast, errors: all, toks };
713
+ }
714
+ function format(ast, name, pretty) {
715
+ const f = (x) => x === "@latency" ? name ? name(x) : LATENCY : name ? name(x) : x;
716
+ const one = (n, d = 0) => {
717
+ if (n.k === "cond") {
718
+ const head = `${f(n.field)} ${n.op}`;
719
+ if (n.op === "PRESENT" || n.op === "ABSENT") return head;
720
+ if (n.op === "BETWEEN") return `${head} ${n.lo.raw} AND ${n.hi.raw}`;
721
+ if (n.vals && (n.list || !n.op.startsWith("IP"))) return `${head} [${n.vals.map((v) => v.raw).join(", ")}]`;
722
+ if (n.vals) return `${head} ${n.vals[0].raw}`;
723
+ return `${head} ${n.val.raw}`;
724
+ }
725
+ if (n.k === "count") return `COUNT() ${n.op} ${n.n}${n.within ? " WITHIN " + n.within : ""}${n.by ? " GROUP BY " + f(n.by) : ""}`;
726
+ const ind = (k) => "\n" + " ".repeat(k);
727
+ if (n.k === "group") return pretty && n.x.items ? `(${ind(d + 1)}${one(n.x, d + 1)}${ind(d)})` : `(${one(n.x, d)})`;
728
+ if (n.k === "not") return `NOT ${one(n.x, d)}`;
729
+ if (pretty) return n.items.map((x, i) => (i ? `${ind(d)}${n.k.toUpperCase()} ` : "") + one(x, d)).join("");
730
+ return n.items.map((x) => one(x)).join(` ${n.k.toUpperCase()} `);
731
+ };
732
+ return ast ? one(ast) : "";
733
+ }
734
+ var get = (row, path) => {
735
+ const segs = path.replace(/\\\./g, ".").split(".");
736
+ let o = row;
737
+ let i = 0;
738
+ while (i < segs.length) {
739
+ if (o == null || typeof o !== "object") return void 0;
740
+ let j = segs.length;
741
+ while (j > i && !(segs.slice(i, j).join(".") in o)) j--;
742
+ if (j === i) return void 0;
743
+ o = o[segs.slice(i, j).join(".")];
744
+ i = j;
745
+ }
746
+ return o;
747
+ };
748
+ var asNum = (v) => typeof v === "number" ? v : typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v) ? Number(v) : null;
749
+ var inRanges = (v, vals) => {
750
+ const ip = ipToBig(v);
751
+ if (!ip) return null;
752
+ return vals.some((x) => {
753
+ const r = parseRange(x.v.includes("/") || x.v.includes("-") ? x.v : x.v + (x.v.includes(":") ? "/128" : "/32"));
754
+ return r && r.v === ip.v && ip.n >= r.lo && ip.n <= r.hi;
755
+ });
756
+ };
757
+ function test(n, row) {
758
+ if (n.k === "group") return test(n.x, row);
759
+ if (n.k === "not") {
760
+ const r = test(n.x, row);
761
+ return r === null ? null : !r;
762
+ }
763
+ if (n.k === "and") {
764
+ let unknown = false;
765
+ for (const x2 of n.items) {
766
+ const r = test(x2, row);
767
+ if (r === false) return false;
768
+ if (r === null) unknown = true;
769
+ }
770
+ return unknown ? null : true;
771
+ }
772
+ if (n.k === "or") {
773
+ let unknown = false;
774
+ for (const x2 of n.items) {
775
+ const r = test(x2, row);
776
+ if (r === true) return true;
777
+ if (r === null) unknown = true;
778
+ }
779
+ return unknown ? null : false;
780
+ }
781
+ if (n.k === "count") return true;
782
+ let v;
783
+ if (n.field === "@latency") {
784
+ const a = get(row, LAT_A);
785
+ const b = get(row, LAT_B);
786
+ v = typeof a === "number" && typeof b === "number" ? a - b : void 0;
787
+ } else v = get(row, n.field);
788
+ if (n.op === "PRESENT") return v !== void 0 && v !== null;
789
+ if (n.op === "ABSENT") return v === void 0 || v === null;
790
+ if (v === void 0 || v === null) return null;
791
+ switch (n.op) {
792
+ case "==":
793
+ return v === n.val.v;
794
+ case "!=":
795
+ return v !== n.val.v;
796
+ case "~":
797
+ case "~*":
798
+ case "!~":
799
+ case "!~*": {
800
+ const hit = new RegExp(n.val.v, n.op.endsWith("*") ? "i" : "").test(String(v));
801
+ return n.op.startsWith("!") ? !hit : hit;
802
+ }
803
+ case "CONTAINS":
804
+ return String(v).includes(n.val.v);
805
+ case "NOT CONTAINS":
806
+ return !String(v).includes(n.val.v);
807
+ case "ANYONE":
808
+ return n.vals.some((x2) => x2.v === v);
809
+ case "NONEOF":
810
+ return !n.vals.some((x2) => x2.v === v);
811
+ case "IP IN_RANGE":
812
+ return inRanges(v, n.vals);
813
+ case "IP NOT_IN_RANGE": {
814
+ const r = inRanges(v, n.vals);
815
+ return r === null ? null : !r;
816
+ }
817
+ }
818
+ const x = asNum(v);
819
+ if (x === null) return null;
820
+ if (n.op === "BETWEEN") return x >= Number(n.lo.v) && x <= Number(n.hi.v);
821
+ const y = Number(n.val.v);
822
+ return n.op === "<" ? x < y : n.op === "<=" ? x <= y : n.op === ">" ? x > y : x >= y;
823
+ }
824
+ var cmp = (a, op, b) => op === ">" ? a > b : op === "<" ? a < b : op === ">=" ? a >= b : op === "<=" ? a <= b : a === b;
825
+ function evaluate(ast, rows) {
826
+ if (!ast) return { rows, count: null };
827
+ const count = ast.k === "count" ? ast : ast.k === "and" && ast.items[ast.items.length - 1].k === "count" ? ast.items[ast.items.length - 1] : null;
828
+ const hit = rows.filter((r) => test(ast, r) === true);
829
+ if (!count) return { rows: hit, count: null };
830
+ const buckets = /* @__PURE__ */ new Map();
831
+ for (const r of hit) {
832
+ const key = count.by ? get(r, count.by) : "*";
833
+ if (key === void 0 || key === null) continue;
834
+ const win = count.ms ? Math.floor(r.metadata.requestTimestamp / count.ms) * count.ms : 0;
835
+ const id = key + "\0" + win;
836
+ let b = buckets.get(id);
837
+ if (!b) buckets.set(id, b = { key, win, rows: [] });
838
+ b.rows.push(r);
839
+ }
840
+ const pass = [...buckets.values()].filter((b) => cmp(b.rows.length, count.op, count.n)).sort((a, b) => b.rows.length - a.rows.length);
841
+ return { rows: pass.flatMap((b) => b.rows).sort((a, b) => b.metadata.requestTimestamp - a.metadata.requestTimestamp), count: { node: count, groups: pass, buckets: buckets.size, filtered: hit.length } };
842
+ }
843
+ function context(src, caret, schema) {
844
+ const toks = tokenize(src.slice(0, caret));
845
+ let part = null;
846
+ const last = toks[toks.length - 1];
847
+ if (last && last.e === caret && ["word", "kw", "bool", "op", "num", "dur"].includes(last.t)) part = toks.pop();
848
+ else if (last && last.t === "str" && !last.closed) part = toks.pop();
849
+ let st = "term";
850
+ let depth = 0;
851
+ let field = null;
852
+ let op = null;
853
+ let between = false;
854
+ let hasCount = /\bCOUNT\s*\(/i.test(src.slice(caret));
855
+ let used = [];
856
+ let inList = false;
857
+ let opTok = null;
858
+ let eq = null;
859
+ for (let i = 0; i < toks.length; i++) {
860
+ const t = toks[i];
861
+ const kw = t.t === "kw" ? t.v : null;
862
+ if (kw === "COUNT") hasCount = true;
863
+ if (st === "term") {
864
+ if (kw === "NOT") continue;
865
+ if (t.v === "(" && t.t === "punct") depth++;
866
+ else if (kw === "COUNT") st = "countParen";
867
+ else if (kw === "LATENCY") field = LAT_FIELD, st = "op";
868
+ else if (t.t === "word") field = schema.byPath[t.v.replace(/\\\./g, ".")] || { path: t.v, type: null }, st = "op";
869
+ else st = "bad";
870
+ } else if (st === "op") {
871
+ if (t.t === "minus") st = "lat2";
872
+ else if (t.t === "op") op = t.v === "=" ? "==" : t.v, opTok = t, st = "value";
873
+ else if (kw === "PRESENT" || kw === "ABSENT") st = "joiner";
874
+ else if (kw === "CONTAINS") op = kw, st = "value";
875
+ else if (kw === "NOT") st = "notc";
876
+ else if (kw === "IP") st = "ipop";
877
+ else if (kw === "BETWEEN") op = kw, between = true, st = "value";
878
+ else if (kw === "ANYONE" || kw === "NONEOF") op = kw, opTok = t, st = "listStart";
879
+ else st = "bad";
880
+ } else if (st === "lat2") st = t.t === "word" ? "latClose" : "bad";
881
+ else if (st === "latClose") {
882
+ if (t.v === ")") depth = Math.max(0, depth - 1), field = LAT_FIELD, st = "op";
883
+ else st = "bad";
884
+ } else if (st === "notc") st = kw === "CONTAINS" ? (op = "NOT CONTAINS", "value") : "bad";
885
+ else if (st === "ipop") st = kw === "IN_RANGE" || kw === "NOT_IN_RANGE" ? (op = "IP " + kw, "value") : "bad";
886
+ else if (st === "listStart") st = t.v === "[" ? (used = [], inList = true, "list") : "bad";
887
+ else if (st === "value") {
888
+ if (t.v === "[" && t.t === "punct") used = [], inList = true, st = "list";
889
+ else if (t.t === "str" || t.t === "num" || t.t === "bool") st = between ? "betAnd" : "joiner", eq = (op === "==" || op === "!=") && opTok ? { op, from: opTok.s, to: t.e, vals: [t.v] } : null;
890
+ else st = "bad";
891
+ } else if (st === "list") {
892
+ if (t.t === "str" || t.t === "num" || t.t === "bool") used.push(t.v);
893
+ else if (t.v === "]") inList = false, st = "joiner", eq = (op === "ANYONE" || op === "NONEOF") && opTok ? { op, from: opTok.s, to: t.e, vals: [...used] } : null;
894
+ else if (t.v !== ",") st = "bad";
895
+ } else if (st === "betAnd") st = kw === "AND" ? (between = false, "value") : "bad";
896
+ else if (st === "joiner") {
897
+ if (kw === "AND" || kw === "OR") st = "term", field = null, op = null, eq = null;
898
+ else if (t.v === ")" && t.t === "punct") depth = Math.max(0, depth - 1);
899
+ else st = "bad";
900
+ } else if (st === "countParen") st = t.v === "(" ? "countParen2" : "bad";
901
+ else if (st === "countParen2") st = t.v === ")" ? "countOp" : "bad";
902
+ else if (st === "countOp") st = t.t === "op" ? "countN" : "bad";
903
+ else if (st === "countN") st = t.t === "num" ? "countAfter" : "bad";
904
+ else if (st === "countAfter") st = kw === "WITHIN" ? "dur" : kw === "GROUP" ? "by" : "bad";
905
+ else if (st === "dur") st = t.t === "dur" ? "countAfter2" : "bad";
906
+ else if (st === "countAfter2") st = kw === "GROUP" ? "by" : "bad";
907
+ else if (st === "by") st = kw === "BY" ? "groupField" : "bad";
908
+ else if (st === "groupField") st = t.t === "word" ? "end" : "bad";
909
+ }
910
+ let to = caret;
911
+ const tail = src.slice(caret).match(/^(?:[A-Za-z0-9_.-]|\\\.)+/);
912
+ if (part && part.t !== "str" && tail) to += tail[0].length;
913
+ if (part && part.t === "str") {
914
+ const m = src.slice(caret).match(/^(?:[^"\\\n]|\\.)*"/);
915
+ if (m) to += m[0].length;
916
+ }
917
+ const from = part ? part.s : caret;
918
+ const q = part ? (part.t === "str" ? part.v : part.raw).toLowerCase() : "";
919
+ const before = src.slice(0, from);
920
+ const pad = before && !/[\s([]$/.test(before) ? " " : "";
921
+ const res = (kind, title, items, extra) => ({ kind, title, items, from, to, q, ...extra });
922
+ const kws = (list, title) => res("kw", title, list.filter((x) => !q || x.label.toLowerCase().startsWith(q) || x.label.toLowerCase().includes(" " + q)));
923
+ if (st === "term" || st === "groupField") {
924
+ const items = [];
925
+ const match = (s) => !q || s.toLowerCase().includes(q);
926
+ for (const f of schema.fields) if (match(f.path)) items.push({ kind: "field", label: f.path, insert: f.path + " ", type: f.type, count: f.count, group: f.group, reopen: st === "term" });
927
+ if (st === "term") {
928
+ const at = items.findIndex((x) => x.group !== "Common");
929
+ if (match("latency") || match(LATENCY)) items.splice(at < 0 ? items.length : at, 0, { kind: "field", label: LATENCY, sub: "latency in ms", insert: LATENCY + " ", type: "latency", group: "Common", reopen: true });
930
+ const prev = toks[toks.length - 1];
931
+ if (!hasCount && depth === 0 && (!prev || prev.t === "kw" && prev.v === "AND") && match("count()")) items.push({ kind: "fn", label: "COUNT()", sub: "number of matching calls, e.g. COUNT() > 50 WITHIN 5m", insert: "COUNT() ", group: "Functions", reopen: true, pin: true });
932
+ if (match("not")) items.push({ kind: "kw", label: "NOT", sub: 'exclude matching calls, e.g. NOT data.request.verb == "GET"', insert: "NOT ", group: "Logic", reopen: true, pin: true });
933
+ if (!q) items.push({ kind: "kw", label: "(", sub: "start a group", insert: "(", group: "Logic", reopen: true, pin: true });
934
+ }
935
+ return res("fields", st === "term" ? "Fields" : "Group by", items, { total: schema.fields.length });
936
+ }
937
+ if (st === "op") {
938
+ if (!field || !field.type) return null;
939
+ const allowed = opsFor(field);
940
+ const ops = BUILD_OPS.flatMap(([g, list]) => list.flatMap((o) => o === "~" || o === "!~" ? [o, o + "*"] : [o]).map((o) => [o, g])).filter(([o]) => allowed.includes(o) && (!q || o.toLowerCase().startsWith(q) || OP_INFO[o].includes(q)));
941
+ const hasValues = VALUE_FIELDS.includes(field.path);
942
+ const after = src.slice(to);
943
+ const valued = /^\s*(?:"|\[|-?\d|true\b|false\b)/i.test(after);
944
+ const items = ops.map(([o, group]) => {
945
+ let insert = o + " ";
946
+ let caretAt = null;
947
+ let reopen = false;
948
+ if (o === "PRESENT" || o === "ABSENT" || o === "BETWEEN" || CMP.has(o)) reopen = true;
949
+ else if (o === "ANYONE" || o === "NONEOF") insert = o + " []", caretAt = insert.length - 1, reopen = hasValues || field.type === "boolean";
950
+ else if (o.startsWith("IP")) insert = o + ' ""', caretAt = insert.length - 1, reopen = true;
951
+ else if (o === "==" || o === "!=") {
952
+ if (hasValues || field.type === "boolean") reopen = true;
953
+ else if (field.type !== "number" && field.type !== "latency") insert = o + ' ""', caretAt = insert.length - 1;
954
+ } else if (TEXT_OPS.has(o)) insert = o + ' ""', caretAt = insert.length - 1, reopen = o.includes("~");
955
+ if (valued) insert = o + (/^\s/.test(after) ? "" : " "), caretAt = null, reopen = false;
956
+ return { kind: "op", label: o, sub: OP_INFO[o], insert, caretAt, reopen, group };
957
+ });
958
+ return res("ops", "Operators", items, { field });
959
+ }
960
+ if (st === "notc") return kws([{ kind: "op", label: "CONTAINS", sub: OP_INFO["NOT CONTAINS"], insert: 'CONTAINS ""', caretAt: 10 }], "Operators");
961
+ if (st === "ipop") return kws(["IN_RANGE", "NOT_IN_RANGE"].map((x) => ({ kind: "op", label: x, sub: OP_INFO["IP " + x], insert: x + ' ""', caretAt: x.length + 2, reopen: true })), "Operators");
962
+ const catalog = field && CATALOG[field.path];
963
+ const another = (e) => catalog.filter((v) => !e.vals.includes(v)).map((v) => ({ kind: "value", label: lit(v), insert: `${e.op === "!=" || e.op === "NONEOF" ? "NONEOF" : "ANYONE"} [${[...e.vals, v].map(lit).join(", ")}] `, from: e.from, to: e.to, reopen: true, group: "Add another value" }));
964
+ if (st === "value" && catalog && opTok && (op === "==" || op === "!=") && (part == null ? void 0 : part.t) === "str" && catalog.includes(part.v)) return res("values", "Add another value", another({ op, from: opTok.s, to, vals: [part.v] }));
965
+ const ranges = {
966
+ "data.response.statusCode": ["Informational", "Success", "Redirect", "Client error", "Server error"].map((n, i) => [`${i + 1}00 AND ${i + 1}99`, `${i + 1}XX \xB7 ${n}`]),
967
+ "data.request.port": [["0 AND 1023", "Well-known ports"], ["1024 AND 49151", "Registered ports"], ["49152 AND 65535", "Dynamic ports"], ["8000 AND 8999", "8xxx app ports"]]
968
+ };
969
+ const nums = (list, title) => res("ops", title, list.map(([label, sub]) => ({ kind: "op", label: String(label), sub, insert: label + " ", num: true, reopen: true })).filter((x) => !q || x.label.startsWith(q)));
970
+ if (st === "value" && between && (field == null ? void 0 : field.type) === "latency" && !q) return nums([["0 AND 100", "under 100 ms"], ["100 AND 500", "100 to 500 ms"], ["500 AND 1000", "500 ms to 1 s"], ["1000 AND 5000", "1 to 5 s"], ["5000 AND 10000", "5 to 10 s"]], "Example ranges \xB7 latency in ms");
971
+ if (st === "value" && between && ranges[field == null ? void 0 : field.path]) return nums(ranges[field.path], `Example ranges \xB7 ${field.path}`);
972
+ if ((st === "value" || st === "list") && (op == null ? void 0 : op.startsWith("IP"))) {
973
+ const lastTok = toks[toks.length - 1];
974
+ const lead = inList && !part && used.length && !(lastTok && lastTok.v === ",") ? ", " : "";
975
+ return res("ops", `Example ranges \xB7 ${field == null ? void 0 : field.path}`, [["10.0.0.0/8", "Private network, 10.x.x.x"], ["172.16.0.0/12", "Private network, 172.16 to 172.31"], ["192.168.0.0/16", "Private network, 192.168.x.x"], ["127.0.0.0/8", "Loopback"], ["169.254.0.0/16", "Link-local"], ["10.0.0.1-10.0.0.50", "First to last address"]].filter(([v]) => !used.includes(v)).map(([v, sub]) => ({ kind: "op", label: `"${v}"`, sub, insert: lead + `"${v}"` + (inList ? "" : " "), str: true, reopen: true })).filter((x) => !q || x.label.includes(q)), { list: inList });
976
+ }
977
+ if (st === "value" && (op == null ? void 0 : op.includes("~")) && field) {
978
+ const patterns = {
979
+ "data.response.statusCode": [["^5\\d\\d$", "any 5XX code"], ["^4\\d\\d$", "any 4XX code"], ["^(401|403)$", "401 or 403"], ["^2", "starts with 2"]],
980
+ "data.request.verb": [["^(GET|HEAD)$", "GET or HEAD"], ["^P", "POST, PUT or PATCH"], ["^(POST|PUT|PATCH|DELETE)$", "any write method"]]
981
+ }[field.path];
982
+ if (patterns) return res("ops", `Example patterns \xB7 ${field.path}`, patterns.map(([v, sub]) => ({ kind: "op", label: lit(v), sub, insert: lit(v) + " ", str: true, reopen: true })).filter((x) => !q || x.label.toLowerCase().includes(q)));
983
+ if ((part == null ? void 0 : part.t) === "str") {
984
+ const syntax = [["^", "start of text"], ["$", "end of text"], [".", "any one character"], ["\\d", "a digit"], ["\\w", "a letter, digit or _"], ["\\s", "a space"], ["[abc]", "one of a, b or c", "[]", 1], ["[^abc]", "anything except a, b or c", "[^]", 2], ["a|b", "a or b", "|"], ["(ab)", "a group", "()", 1], ["*", "zero or more of the previous"], ["+", "one or more of the previous"], ["?", "previous is optional"], ["{3}", "exactly 3 of the previous", "{}", 1], ["\\.", "a literal dot"]];
985
+ return res("ops", `Regex syntax \xB7 ${field.path}`, syntax.map(([label, sub, ins = label, at]) => ({ kind: "op", label, sub, insert: ins, caretAt: at, from: caret, to: caret, str: true, reopen: true })));
986
+ }
987
+ }
988
+ const bands = {
989
+ "data.response.statusCode": [[100, 199, "1XX"], [200, 299, "2XX"], [300, 399, "3XX"], [400, 499, "4XX"], [500, 599, "5XX"], ""],
990
+ "data.request.port": [[0, 1023, "well-known"], [1024, 49151, "registered"], [49152, 65535, "dynamic"], " ports"]
991
+ }[field == null ? void 0 : field.path];
992
+ if (st === "value" && CMP.has(op) && bands && !q) {
993
+ const cls2 = bands.slice(0, -1);
994
+ const suf = bands[bands.length - 1];
995
+ const test2 = (x, t) => op === "<" ? x < t : op === "<=" ? x <= t : op === ">" ? x > t : x >= t;
996
+ const label = (t) => {
997
+ const cs = cls2.filter(([lo, hi]) => test2(lo, t) && test2(hi, t)).map(([, , n]) => n);
998
+ return cs.length === 1 ? `${cs[0]}${suf} only` : `${cs[0]} ${cs.length === 2 ? "and" : "to"} ${cs[cs.length - 1]}${suf}`;
999
+ };
1000
+ const edges = op === "<" || op === ">=" ? cls2.slice(1).map(([lo]) => lo) : cls2.slice(0, -1).map(([, hi]) => hi);
1001
+ return nums(edges.map((t) => [t, label(t)]), `Example thresholds \xB7 ${field.path}`);
1002
+ }
1003
+ if (st === "value" && CMP.has(op) && (field == null ? void 0 : field.type) === "latency" && !q) return nums([[100, "100 ms"], [250, "250 ms"], [500, "500 ms"], [1e3, "1 s"], [2e3, "2 s"], [5e3, "5 s"], [1e4, "10 s"]], "Example thresholds \xB7 latency in ms");
1004
+ if (st === "value" && !between && !(op == null ? void 0 : op.startsWith("IP")) && !CMP.has(op) || st === "list") {
1005
+ if (!field) return null;
1006
+ const fresh = (v) => !used.includes(v);
1007
+ let vals = [];
1008
+ if (catalog && (op === "==" || op === "!=" || inList)) vals = catalog.filter(fresh).map((v) => ({ v }));
1009
+ else if (field.type === "boolean" && (op === "==" || op === "!=" || inList)) vals = [true, false].filter(fresh).map((v) => ({ v }));
1010
+ if (!vals.length) return null;
1011
+ const lastTok = toks[toks.length - 1];
1012
+ const comma = inList && used.length && !(lastTok && lastTok.v === ",") ? ", " : "";
1013
+ const items = vals.filter((x) => !q || String(x.v).toLowerCase().startsWith(q.replace(/^"/, ""))).map((x) => ({ kind: "value", label: lit(x.v), insert: (part ? "" : comma) + lit(x.v) + (inList ? "" : " "), reopen: true }));
1014
+ return res("values", inList && used.length ? `Add another \xB7 ${field.path}` : `Values \xB7 ${field.path}`, items, { list: inList });
1015
+ }
1016
+ if (st === "betAnd") return kws([{ kind: "kw", label: "AND", sub: "then the upper bound", insert: pad + "AND " }], "Between");
1017
+ if (st === "joiner" || st === "end") {
1018
+ const items = [];
1019
+ if (st === "joiner") {
1020
+ items.push({ kind: "kw", label: "AND", sub: "both must match, e.g. AND data.response.statusCode >= 500", insert: pad + "AND ", reopen: true });
1021
+ items.push({ kind: "kw", label: "OR", sub: 'either can match, e.g. OR data.request.verb == "PUT"', insert: pad + "OR ", reopen: true });
1022
+ items.push({ kind: "kw", label: "AND NOT", sub: 'exclude matching calls, e.g. AND NOT data.request.path CONTAINS "/health"', insert: pad + "AND NOT ", reopen: true });
1023
+ if (depth > 0) items.push({ kind: "kw", label: ")", sub: "close the group, e.g. (A OR B) AND C", insert: ") ", trim: true, reopen: true });
1024
+ if (!hasCount && depth === 0) items.push({ kind: "fn", label: "AND COUNT()", sub: "number of matching calls, e.g. AND COUNT() > 50 WITHIN 5m", insert: pad + "AND COUNT() ", reopen: true });
1025
+ }
1026
+ if (st === "joiner" && eq && catalog && !q) return res("kw", "Combine", [...another(eq), ...items.map((x) => ({ ...x, group: "Join conditions", pin: true }))]);
1027
+ return kws(items, "Combine");
1028
+ }
1029
+ if (st === "countOp") return kws([">", ">=", "<", "<=", "=="].map((o) => ({ kind: "op", label: o, sub: OP_INFO[o], insert: o + " " })), "COUNT()");
1030
+ if (st === "countAfter" || st === "countAfter2") {
1031
+ const items = [];
1032
+ if (st === "countAfter") items.push({ kind: "kw", label: "WITHIN", sub: "window, defaults to the time range", insert: pad + "WITHIN ", reopen: true });
1033
+ items.push({ kind: "kw", label: "GROUP BY", sub: "count each value on its own", insert: pad + "GROUP BY ", reopen: true });
1034
+ return kws(items, "COUNT()");
1035
+ }
1036
+ if (st === "dur") return kws(["1m", "5m", "10m", "15m", "1h", "1d"].map((d) => ({ kind: "value", label: d, insert: d + " ", reopen: true })), "Window");
1037
+ if (st === "by") return kws([{ kind: "kw", label: "BY", insert: "BY ", reopen: true }], "COUNT()");
1038
+ return null;
1039
+ }
1040
+ var uid = 0;
1041
+ var nid = () => "b" + ++uid;
1042
+ var RE_META = /[.*+?^${}()|[\]\\]/;
1043
+ var escRe = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1044
+ var unescRe = (p) => {
1045
+ let out = "";
1046
+ for (let i = 0; i < p.length; i++) {
1047
+ if (p[i] === "\\" && i + 1 < p.length && RE_META.test(p[i + 1])) out += p[++i];
1048
+ else if (RE_META.test(p[i])) return null;
1049
+ else out += p[i];
1050
+ }
1051
+ return out;
1052
+ };
1053
+ var BUILD_OPS = [
1054
+ ["Equality", ["==", "!=", "ANYONE", "NONEOF"]],
1055
+ ["Compare", ["<", "<=", ">", ">=", "BETWEEN"]],
1056
+ ["Text", ["CONTAINS", "NOT CONTAINS", "~", "!~"]],
1057
+ ["Existence", ["PRESENT", "ABSENT"]],
1058
+ ["Network", ["IP IN_RANGE", "IP NOT_IN_RANGE"]]
1059
+ ];
1060
+ var arity = (op) => op === "PRESENT" || op === "ABSENT" ? "none" : op === "BETWEEN" ? "two" : op === "ANYONE" || op === "NONEOF" ? "list" : op.startsWith("IP") ? "ip" : "one";
1061
+ var isComplete = (c) => {
1062
+ if (!c.field) return false;
1063
+ const a = arity(c.op);
1064
+ const vals = c.values.filter((v) => String(v).trim());
1065
+ return a === "none" || (a === "two" ? vals.length === 2 : vals.length > 0);
1066
+ };
1067
+ var newCond = () => ({ kind: "cond", id: nid(), field: "", op: "==", values: [], ci: false, not: false });
1068
+ function toTree(ast) {
1069
+ const root = { kind: "group", id: nid(), join: "AND", not: false, items: [], count: null };
1070
+ if (!ast) return root;
1071
+ const node = (n, not = false) => {
1072
+ if (n.k === "not") return node(n.x, !not);
1073
+ if (n.k === "group") return node(n.x, not);
1074
+ if (n.k === "and" || n.k === "or") return { kind: "group", id: nid(), join: n.k.toUpperCase(), not, items: n.items.map((x) => node(x)) };
1075
+ let op = n.op;
1076
+ let ci = false;
1077
+ if (op === "~*" || op === "!~*") ci = true, op = op.slice(0, -1);
1078
+ let values = n.op === "BETWEEN" ? [String(n.lo.v), String(n.hi.v)] : n.vals ? n.vals.map((v) => String(v.v)) : n.val ? [String(n.val.v)] : [];
1079
+ if (ci) {
1080
+ const plain = unescRe(values[0]);
1081
+ if (plain !== null) op = op === "~" ? "CONTAINS" : "NOT CONTAINS", values = [plain];
1082
+ }
1083
+ return { kind: "cond", id: nid(), field: n.field, op, values, ci, not };
1084
+ };
1085
+ const top = ast.k === "and" ? ast.items : [ast];
1086
+ const rest = [];
1087
+ for (const n of top) {
1088
+ if (n.k === "count") root.count = { op: n.op, n: String(n.n), within: n.within || "", by: n.by || "" };
1089
+ else rest.push(n);
1090
+ }
1091
+ if (ast.k === "and") root.items = rest.map((x) => node(x));
1092
+ else if (rest.length) {
1093
+ const one = node(rest[0]);
1094
+ if (one.kind === "group" && !one.not) root.join = one.join, root.items = one.items;
1095
+ else root.items = [one];
1096
+ }
1097
+ return root;
1098
+ }
1099
+ function fromTree(root, schema) {
1100
+ const quoted = (field) => {
1101
+ const f = field === "@latency" ? LAT_FIELD : schema.byPath[field];
1102
+ return !f || f.type !== "number" && f.type !== "boolean" && f.type !== "latency";
1103
+ };
1104
+ const cond = (c2) => {
1105
+ const head = c2.field === "@latency" ? LATENCY : c2.field;
1106
+ const vals = c2.values.map((v) => String(v).trim()).filter(Boolean);
1107
+ const val = (v) => quoted(c2.field) ? lit(v) : v;
1108
+ const a = arity(c2.op);
1109
+ let s;
1110
+ if (a === "none") s = `${head} ${c2.op}`;
1111
+ else if (a === "two") s = `${head} BETWEEN ${vals[0]} AND ${vals[1]}`;
1112
+ else if (a === "list") s = `${head} ${c2.op} [${vals.map(val).join(", ")}]`;
1113
+ else if (a === "ip") s = `${head} ${c2.op} ${vals.length > 1 ? `[${vals.map(lit).join(", ")}]` : lit(vals[0])}`;
1114
+ else if (CMP.has(c2.op)) s = `${head} ${c2.op} ${vals[0]}`;
1115
+ else if (c2.op === "CONTAINS" || c2.op === "NOT CONTAINS") s = c2.ci ? `${head} ${c2.op === "CONTAINS" ? "~*" : "!~*"} ${lit(escRe(vals[0]))}` : `${head} ${c2.op} ${lit(vals[0])}`;
1116
+ else if (c2.op === "~" || c2.op === "!~") s = `${head} ${c2.op}${c2.ci ? "*" : ""} ${lit(vals[0])}`;
1117
+ else s = `${head} ${c2.op} ${val(vals[0])}`;
1118
+ return c2.not ? `NOT ${s}` : s;
1119
+ };
1120
+ const group = (g, top) => {
1121
+ const parts = g.items.map((x) => [x.j || g.join, x.kind === "group" ? group(x, false) : isComplete(x) ? cond(x) : ""]).filter((x) => x[1]);
1122
+ if (!parts.length) return "";
1123
+ const body = parts.map(([j, x], i) => i ? ` ${j} ${x}` : x).join("");
1124
+ if (top) return body;
1125
+ if (parts.length === 1) return g.not ? `NOT ${body.startsWith("NOT ") ? `(${body})` : body}` : body;
1126
+ return `${g.not ? "NOT " : ""}(${body})`;
1127
+ };
1128
+ let t = group(root, true);
1129
+ const c = root.count;
1130
+ if (c && String(c.n).trim()) {
1131
+ const cnt = `COUNT() ${c.op} ${String(c.n).trim()}${c.within.trim() ? ` WITHIN ${c.within.trim()}` : ""}${c.by ? ` GROUP BY ${c.by}` : ""}`;
1132
+ t = t ? `${root.items.some((x, i) => i && (x.j || root.join) === "OR") && root.items.filter((x) => x.kind === "group" || isComplete(x)).length > 1 ? `(${t})` : t} AND ${cnt}` : cnt;
1133
+ }
1134
+ return t;
1135
+ }
1136
+
1137
+ // src/react/QueryBox.jsx
1138
+ var import_react2 = require("react");
1139
+ var import_react3 = require("@phosphor-icons/react");
1140
+
1141
+ // src/react/Builder.jsx
1142
+ var import_react = require("react");
1143
+ var P = __toESM(require("@phosphor-icons/react"), 1);
1144
+
1145
+ // src/react/colors.js
1146
+ var VERB = { GET: "#147af3", POST: "#2fb880", PUT: "#b07500", PATCH: "#9d57f4", DELETE: "#ea3829", OPTIONS: "#626978", HEAD: "#626978", TRACE: "#626978", CONNECT: "#626978", QUERY: "#626978" };
1147
+ var TONE = { 1: ["#147af3", "#e0f2ff"], 2: ["#00653e", "#cef8e0"], 3: ["#4046ca", "#d3d5ff"], 4: ["#b40000", "#ffcdc3"], 5: ["#cb5d00", "#ffeccc"] };
1148
+ var valueStyle = (v, field) => {
1149
+ const s = String(v);
1150
+ if ((!field || field === "data.request.verb") && VERB[s]) return { color: VERB[s], fontWeight: 600 };
1151
+ const t = (!field || field === "data.response.statusCode") && /^\d{3}$/.test(s) && TONE[s[0]];
1152
+ return t ? { color: t[0], background: t[1], boxShadow: "inset 0 0 0 1px #cdd2dd", borderRadius: 2 } : null;
1153
+ };
1154
+
1155
+ // src/react/Builder.jsx
1156
+ var import_jsx_runtime = require("react/jsx-runtime");
1157
+ var TYPE_ICON = { string: P.TextT, numtext: P.TextT, ip: P.Globe, number: P.Hash, boolean: P.ToggleLeft, latency: P.Timer };
1158
+ var EXAMPLE = {
1159
+ "==": '"GET"',
1160
+ "!=": '"200"',
1161
+ ANYONE: '["POST", "PUT"]',
1162
+ NONEOF: '["GET", "HEAD"]',
1163
+ "<": "1024",
1164
+ "<=": "5000",
1165
+ ">": "399",
1166
+ ">=": "500",
1167
+ BETWEEN: "200 AND 299",
1168
+ CONTAINS: '"agent-registry"',
1169
+ "NOT CONTAINS": '"node"',
1170
+ "~": '"^/api/v1/"',
1171
+ "!~": '"/health$"',
1172
+ PRESENT: "no value",
1173
+ ABSENT: "no value",
1174
+ "IP IN_RANGE": '"10.0.0.0/8"',
1175
+ "IP NOT_IN_RANGE": '["10.0.0.0/8"]'
1176
+ };
1177
+ var HINT = { "data.request.verb": "Method", "data.response.statusCode": "Status code", "data.request.path": "Path", "data.request.hostname": "Host" };
1178
+ var CATALOG2 = { "data.request.verb": METHODS, "data.response.statusCode": STATUS_CODES };
1179
+ var INPUT = "h-7 min-w-0 rounded-md border border-stroke-subsection bg-transparent px-1.5 hover:border-stroke-section font-mono text-code-editor-small text-text-default-regular outline-none placeholder:font-sans placeholder:text-text-default-disabled focus:border-stroke-active";
1180
+ var ACT = "grid h-7 w-7 place-items-center rounded text-icon-default hover:bg-surface-hover-l1-hover";
1181
+ var typeOf = (field, schema) => {
1182
+ var _a;
1183
+ return field === "@latency" ? "latency" : ((_a = schema.byPath[field]) == null ? void 0 : _a.type) || "string";
1184
+ };
1185
+ var update = (g, id, fn) => ({ ...g, items: g.items.map((x) => x.id === id ? fn(x) : x.kind === "group" ? update(x, id, fn) : x) });
1186
+ var remove = (g, id) => ({ ...g, items: g.items.filter((x) => x.id !== id).map((x) => x.kind === "group" ? remove(x, id) : x) });
1187
+ var tidy = (g, top) => {
1188
+ const items = g.items.map((x) => x.kind === "group" ? tidy(x, false) : x).filter((x) => x && (x.kind !== "group" || x.items.length));
1189
+ if (!top && items.length === 1 && !g.not) return items[0];
1190
+ return { ...g, items };
1191
+ };
1192
+ var insertAfter = (g, id, item) => {
1193
+ const i = g.items.findIndex((x) => x.id === id);
1194
+ if (i >= 0) return { ...g, items: [...g.items.slice(0, i + 1), item, ...g.items.slice(i + 1)] };
1195
+ return { ...g, items: g.items.map((x) => x.kind === "group" ? insertAfter(x, id, item) : x) };
1196
+ };
1197
+ var clone = (x) => x.kind === "group" ? { ...x, id: newCond().id, items: x.items.map(clone) } : { ...x, id: newCond().id, values: [...x.values] };
1198
+ function Menu({ anchor, width, onClose, children }) {
1199
+ const ref = (0, import_react.useRef)(null);
1200
+ const close = (0, import_react.useRef)(onClose);
1201
+ close.current = onClose;
1202
+ const [pos, setPos] = (0, import_react.useState)(null);
1203
+ (0, import_react.useEffect)(() => {
1204
+ const onClose2 = () => close.current();
1205
+ const r = anchor.current.getBoundingClientRect();
1206
+ const below = r.bottom + 360 < window.innerHeight;
1207
+ setPos({ left: Math.min(r.left, window.innerWidth - width - 8), top: below ? r.bottom + 4 : void 0, bottom: below ? void 0 : window.innerHeight - r.top + 4 });
1208
+ const out = (e) => {
1209
+ var _a, _b;
1210
+ return !((_a = ref.current) == null ? void 0 : _a.contains(e.target)) && !((_b = anchor.current) == null ? void 0 : _b.contains(e.target)) && onClose2();
1211
+ };
1212
+ const key = (e) => e.key === "Escape" && onClose2();
1213
+ const scroll = (e) => {
1214
+ var _a;
1215
+ return !((_a = ref.current) == null ? void 0 : _a.contains(e.target)) && onClose2();
1216
+ };
1217
+ document.addEventListener("mousedown", out, true);
1218
+ document.addEventListener("keydown", key);
1219
+ document.addEventListener("scroll", scroll, true);
1220
+ return () => {
1221
+ document.removeEventListener("mousedown", out, true);
1222
+ document.removeEventListener("keydown", key);
1223
+ document.removeEventListener("scroll", scroll, true);
1224
+ };
1225
+ }, []);
1226
+ if (!pos) return null;
1227
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ref, style: { position: "fixed", zIndex: 70, width, ...pos }, className: "rounded-md border border-stroke-subsection bg-surface-default-l1 shadow-e300", children });
1228
+ }
1229
+ function FieldPicker({ value, schema, onPick, autoOpen, placeholder = "Add field" }) {
1230
+ const btn = (0, import_react.useRef)(null);
1231
+ const [open, setOpen] = (0, import_react.useState)(autoOpen);
1232
+ const [q, setQ] = (0, import_react.useState)("");
1233
+ const x = q.trim().toLowerCase();
1234
+ const common = [...schema.fields.filter((f) => f.group === "Common").map((f) => ({ path: f.path, hint: HINT[f.path] || "" })), { path: "@latency", hint: "Latency in ms" }].filter((c) => !x || (c.path === "@latency" ? LATENCY : c.path).toLowerCase().includes(x) || c.hint.toLowerCase().includes(x));
1235
+ const all = schema.fields.filter((f) => f.group !== "Common" && (!x || f.path.toLowerCase().includes(x))).slice(0, 80);
1236
+ const pick = (p) => {
1237
+ onPick(p);
1238
+ setOpen(false);
1239
+ setQ("");
1240
+ };
1241
+ const label = value === "@latency" ? LATENCY : value;
1242
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative min-w-0 shrink", children: [
1243
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { ref: btn, onClick: () => setOpen(!open), "aria-expanded": open, "data-pqb-tip": value ? void 0 : "Pick a field", className: `flex h-7 max-w-[440px] items-center rounded-md border text-left ${value ? `px-1 ${open ? "border-stroke-active bg-surface-default-ground" : "border-transparent hover:bg-surface-hover-l1-hover"}` : `border-dashed bg-surface-default-ground px-2 ${open ? "border-stroke-active" : "border-stroke-section hover:border-stroke-active"}`}`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: `min-w-0 truncate text-interface-body-s-normal ${value ? "font-mono text-base-blue-1100" : "text-text-default-disabled"}`, children: value ? label : placeholder }) }),
1244
+ open && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Menu, { anchor: btn, width: 420, onClose: () => setOpen(false), children: [
1245
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-9 items-center gap-1.5 border-b border-stroke-subsection px-2.5", children: [
1246
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.MagnifyingGlass, { size: 14, className: "text-icon-default" }),
1247
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1248
+ "input",
1249
+ {
1250
+ autoFocus: true,
1251
+ value: q,
1252
+ onChange: (e) => setQ(e.target.value),
1253
+ placeholder: `Search ${schema.fields.length} fields`,
1254
+ onKeyDown: (e) => {
1255
+ var _a, _b;
1256
+ if (e.key === "Enter") {
1257
+ const p = ((_a = common[0]) == null ? void 0 : _a.path) ?? ((_b = all[0]) == null ? void 0 : _b.path);
1258
+ if (p) pick(p);
1259
+ }
1260
+ },
1261
+ className: "min-w-0 flex-1 bg-transparent text-interface-body-s-normal text-text-default-regular outline-none placeholder:text-text-default-disabled"
1262
+ }
1263
+ )
1264
+ ] }),
1265
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "max-h-[280px] overflow-y-auto no-scrollbar pb-1", children: [
1266
+ [["Common", common], ...Object.entries(all.reduce((g, f) => ((g[f.group] ||= []).push(f), g), {}))].filter(([, list]) => list.length).map(([g, list]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
1267
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { style: { position: "sticky", top: 0, zIndex: 1 }, className: "flex items-center justify-between gap-3 bg-surface-default-l1 px-2.5 pb-0.5 pt-1.5 text-interface-titles-caption text-text-default-subdued", children: [
1268
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "min-w-0 truncate", children: `FIELDS / ${g}`.toUpperCase() }),
1269
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "shrink-0 text-interface-labels-xs-normal text-text-default-subtle", children: list.length })
1270
+ ] }),
1271
+ g === "Common" ? list.map((c) => {
1272
+ var _a;
1273
+ const Icon = TYPE_ICON[c.path === "@latency" ? "latency" : (_a = schema.byPath[c.path]) == null ? void 0 : _a.type] || P.TextT;
1274
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { onClick: () => pick(c.path), className: "flex w-full items-center gap-2 px-2.5 py-1 text-left hover:bg-surface-hover-l1-hover", children: [
1275
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { size: 12, className: "shrink-0 text-icon-subtle" }),
1276
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "min-w-0 flex-1 truncate font-mono text-code-editor-small text-text-default-regular", children: c.path === "@latency" ? LATENCY : c.path }),
1277
+ value === c.path && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Check, { size: 12, className: "shrink-0 text-icon-default" })
1278
+ ] }, c.path);
1279
+ }) : list.map((f) => {
1280
+ const Icon = TYPE_ICON[f.type] || P.TextT;
1281
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { onClick: () => pick(f.path), className: "flex w-full items-center gap-2 px-2.5 py-1 text-left hover:bg-surface-hover-l1-hover", children: [
1282
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { size: 12, className: "shrink-0 text-icon-subtle" }),
1283
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "min-w-0 flex-1 truncate font-mono text-code-editor-small text-text-default-regular", children: f.path }),
1284
+ value === f.path && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Check, { size: 12, className: "shrink-0 text-icon-default" })
1285
+ ] }, f.path);
1286
+ })
1287
+ ] }, g)),
1288
+ !common.length && !all.length && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "px-2.5 py-2 text-interface-body-s-light text-text-default-subdued", children: [
1289
+ "No field matches \u201C",
1290
+ q,
1291
+ "\u201D"
1292
+ ] })
1293
+ ] })
1294
+ ] })
1295
+ ] });
1296
+ }
1297
+ function OpPicker({ value, type, onPick }) {
1298
+ const btn = (0, import_react.useRef)(null);
1299
+ const [open, setOpen] = (0, import_react.useState)(false);
1300
+ const [q, setQ] = (0, import_react.useState)("");
1301
+ const allowed = opsFor({ type });
1302
+ const x = q.trim().toLowerCase();
1303
+ const groups = BUILD_OPS.map(([name, ops]) => [name, ops.filter((o) => allowed.includes(o) && (!x || `${o} ${OP_INFO[o]}`.toLowerCase().includes(x)))]).filter(([, ops]) => ops.length);
1304
+ const pick = (o) => {
1305
+ onPick(o);
1306
+ setOpen(false);
1307
+ setQ("");
1308
+ };
1309
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative shrink-0", children: [
1310
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { ref: btn, onClick: () => setOpen(!open), "aria-expanded": open, "data-pqb-tip": OP_INFO[value], className: `mt-[3px] flex h-[22px] min-w-[22px] items-center justify-center rounded px-1.5 bg-surface-color-blue-default-subtle hover:bg-surface-color-blue-hover-subtle ${open ? "ring-1 ring-stroke-active" : ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "whitespace-nowrap font-mono text-code-editor-small font-semibold text-text-color-blue", children: value }) }),
1311
+ open && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Menu, { anchor: btn, width: 320, onClose: () => setOpen(false), children: [
1312
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-9 items-center gap-1.5 border-b border-stroke-subsection px-2.5", children: [
1313
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.MagnifyingGlass, { size: 14, className: "text-icon-default" }),
1314
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1315
+ "input",
1316
+ {
1317
+ autoFocus: true,
1318
+ value: q,
1319
+ onChange: (e) => setQ(e.target.value),
1320
+ placeholder: "Search operators",
1321
+ onKeyDown: (e) => e.key === "Enter" && groups[0] && pick(groups[0][1][0]),
1322
+ className: "min-w-0 flex-1 bg-transparent text-interface-body-s-normal text-text-default-regular outline-none placeholder:text-text-default-disabled"
1323
+ }
1324
+ )
1325
+ ] }),
1326
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "max-h-[320px] overflow-y-auto no-scrollbar py-1", children: [
1327
+ groups.map(([name, ops]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
1328
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "px-2.5 pb-0.5 pt-1.5 text-interface-titles-caption text-text-default-subdued", children: name.toUpperCase() }),
1329
+ ops.map((o) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { onClick: () => pick(o), className: `flex w-full items-center gap-2 px-2.5 py-1.5 text-left hover:bg-surface-hover-l1-hover ${o === value ? "bg-surface-color-blue-default-subtle" : ""}`, children: [
1330
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "w-[72px] shrink-0 truncate rounded bg-surface-default-underground px-1 py-0.5 text-center font-mono text-code-editor-small text-text-default-subtle", children: o.replace("IP ", "") }),
1331
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex min-w-0 flex-1 flex-col", children: [
1332
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "text-interface-body-s-normal text-text-default-regular", children: OP_INFO[o] }),
1333
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "truncate font-mono text-interface-labels-xs-light text-text-default-subdued", children: EXAMPLE[o] })
1334
+ ] }),
1335
+ o === value && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Check, { size: 12, className: "shrink-0 text-icon-default" })
1336
+ ] }, o))
1337
+ ] }, name)),
1338
+ !groups.length && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "px-2.5 py-2 text-interface-body-s-light text-text-default-subdued", children: [
1339
+ "No operator matches \u201C",
1340
+ q,
1341
+ "\u201D"
1342
+ ] })
1343
+ ] }),
1344
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "border-t border-stroke-subsection px-2.5 py-1.5 text-interface-labels-xs-light text-text-default-subdued", children: [
1345
+ "Showing operators for ",
1346
+ TYPE_LABEL[type],
1347
+ " fields"
1348
+ ] })
1349
+ ] })
1350
+ ] });
1351
+ }
1352
+ function Options({ list, value, field, quoted, onPick, children }) {
1353
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex max-h-[280px] flex-col gap-1 overflow-y-auto no-scrollbar p-2", children: [
1354
+ Object.entries(list.reduce((g, v) => ((g[/^\d{3}$/.test(v) ? v[0] + "XX" : ""] ||= []).push(v), g), {})).map(([k, vs]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-1", children: [
1355
+ k && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "w-8 shrink-0 text-interface-labels-xs-normal text-text-default-subdued", children: k }),
1356
+ vs.map((v) => {
1357
+ const st = valueStyle(v, field);
1358
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onMouseDown: (e) => e.preventDefault(), onClick: () => onPick(v), style: { ...st, outline: v === value ? "2px solid var(--color-stroke-active)" : "none", outlineOffset: 1 }, className: `h-6 rounded px-1.5 font-mono text-code-editor-small hover:opacity-80 ${(st == null ? void 0 : st.background) ? "" : "bg-surface-default-underground"} ${st ? "" : "text-text-default-regular"}`, children: quoted && !st ? `"${v}"` : v }, v);
1359
+ })
1360
+ ] }, k)),
1361
+ children
1362
+ ] });
1363
+ }
1364
+ function ValuePick({ value, options, quoted, onPick, add, field }) {
1365
+ const btn = (0, import_react.useRef)(null);
1366
+ const [open, setOpen] = (0, import_react.useState)(false);
1367
+ const [q, setQ] = (0, import_react.useState)("");
1368
+ const x = q.trim().toLowerCase();
1369
+ const list = options.filter((o) => !x || o.toLowerCase().includes(x));
1370
+ const show = (v) => {
1371
+ const st = valueStyle(v, field);
1372
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: st ? { ...st, padding: st.background ? "0 4px" : 0 } : void 0, children: quoted && !st ? `"${v}"` : v });
1373
+ };
1374
+ const pick = (v) => {
1375
+ onPick(v);
1376
+ setOpen(false);
1377
+ setQ("");
1378
+ };
1379
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "relative shrink-0", children: [
1380
+ add ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { ref: btn, onClick: () => setOpen(!open), "aria-expanded": open, "data-pqb-tip": "Add a value", "aria-label": "Add a value", className: ACT, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Plus, { size: 14 }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { ref: btn, onClick: () => setOpen(!open), className: `flex h-7 min-w-[90px] items-center gap-1.5 rounded-md border px-1.5 text-left ${open ? "border-stroke-active" : "border-stroke-subsection hover:border-stroke-active"}`, children: [
1381
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: `min-w-0 flex-1 truncate ${value ? "font-mono text-code-editor-small text-text-default-regular" : "text-interface-body-s-normal text-text-default-disabled"}`, children: value ? show(value) : "Pick a value" }),
1382
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.CaretDown, { size: 12, className: "shrink-0 text-text-default-subtle" })
1383
+ ] }),
1384
+ open && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Menu, { anchor: btn, width: field === "data.response.statusCode" ? 420 : 300, onClose: () => setOpen(false), children: [
1385
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-9 items-center gap-1.5 border-b border-stroke-subsection px-2.5", children: [
1386
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.MagnifyingGlass, { size: 14, className: "text-icon-default" }),
1387
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1388
+ "input",
1389
+ {
1390
+ autoFocus: true,
1391
+ value: q,
1392
+ onChange: (e) => setQ(e.target.value),
1393
+ placeholder: "Search values",
1394
+ onKeyDown: (e) => {
1395
+ if (e.key === "Enter" && (list[0] || q.trim())) pick(list[0] ?? q.trim());
1396
+ },
1397
+ className: "min-w-0 flex-1 bg-transparent text-interface-body-s-normal text-text-default-regular outline-none placeholder:text-text-default-disabled"
1398
+ }
1399
+ )
1400
+ ] }),
1401
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Options, { list, value, field, quoted, onPick: pick, children: !list.length && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "px-0.5 py-1 text-interface-body-s-light text-text-default-subdued", children: [
1402
+ "Enter adds \u201C",
1403
+ q,
1404
+ "\u201D"
1405
+ ] }) })
1406
+ ] })
1407
+ ] });
1408
+ }
1409
+ function Chips({ values, onValues, placeholder, quoted, field, options }) {
1410
+ const [draft, setDraft] = (0, import_react.useState)("");
1411
+ const [open, setOpen] = (0, import_react.useState)(false);
1412
+ const ref = (0, import_react.useRef)(null);
1413
+ const box = (0, import_react.useRef)(null);
1414
+ const x = draft.trim().toLowerCase();
1415
+ const list = (options || []).filter((o) => !values.includes(o) && (!x || o.toLowerCase().includes(x)));
1416
+ const add = (raw) => {
1417
+ const vals = raw.split(/[,\n]/).map((v) => v.trim().replace(/^"(.*)"$/s, "$1")).filter(Boolean);
1418
+ if (vals.length) onValues([...values, ...vals.filter((v) => !values.includes(v))]);
1419
+ setDraft("");
1420
+ setOpen(false);
1421
+ };
1422
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { ref: box, onClick: () => {
1423
+ var _a;
1424
+ return (_a = ref.current) == null ? void 0 : _a.focus(), setOpen(true);
1425
+ }, className: "flex min-h-7 min-w-0 max-w-[420px] flex-1 cursor-text flex-wrap items-center gap-1 rounded-md border border-stroke-subsection bg-surface-default-ground px-1 py-0.5 focus-within:border-stroke-active", children: [
1426
+ values.map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { style: valueStyle(v, field) || void 0, className: "flex h-5 items-center gap-1 rounded bg-surface-default-underground pl-1.5 pr-0.5 font-mono text-code-editor-small text-text-default-regular", children: [
1427
+ quoted && !valueStyle(v, field) ? `"${v}"` : v,
1428
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1429
+ "button",
1430
+ {
1431
+ onClick: (e) => {
1432
+ e.stopPropagation();
1433
+ onValues(values.filter((x2) => x2 !== v));
1434
+ },
1435
+ "aria-label": `Remove ${v}`,
1436
+ className: "grid h-4 w-4 place-items-center rounded text-icon-subtle hover:bg-surface-hover-l1-hover",
1437
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.X, { size: 9 })
1438
+ }
1439
+ )
1440
+ ] }, v)),
1441
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1442
+ "input",
1443
+ {
1444
+ ref,
1445
+ value: draft,
1446
+ placeholder: values.length ? "" : `${placeholder}, then Enter`,
1447
+ onFocus: () => setOpen(true),
1448
+ onChange: (e) => (setOpen(true), e.target.value.includes(",") ? add(e.target.value) : setDraft(e.target.value)),
1449
+ onKeyDown: (e) => {
1450
+ if (e.key === "Enter") {
1451
+ e.preventDefault();
1452
+ add(x && list[0] ? list[0] : draft);
1453
+ }
1454
+ if (e.key === "Backspace" && !draft && values.length) onValues(values.slice(0, -1));
1455
+ },
1456
+ onBlur: () => draft && add(draft),
1457
+ className: "h-5 min-w-[90px] flex-1 bg-transparent px-1 font-mono text-code-editor-small text-text-default-regular outline-none placeholder:font-sans placeholder:text-text-default-disabled"
1458
+ }
1459
+ ),
1460
+ open && list.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Menu, { anchor: box, width: field === "data.response.statusCode" ? 420 : 300, onClose: () => setOpen(false), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Options, { list, field, quoted, onPick: add }) })
1461
+ ] });
1462
+ }
1463
+ function Values({ cond, type, onChange }) {
1464
+ const a = arity(cond.op);
1465
+ const [one = "", two = ""] = cond.values;
1466
+ const set = (values) => onChange({ values });
1467
+ const catalog = CATALOG2[cond.field] || (type === "boolean" ? ["true", "false"] : null);
1468
+ const quoted = type !== "number" && type !== "boolean" && type !== "latency" && !["<", "<=", ">", ">="].includes(cond.op);
1469
+ const placeholder = cond.field === "data.response.statusCode" ? "404" : type === "number" || type === "latency" ? "Number" : type === "ip" ? "10.0.4.12" : type === "boolean" ? "true or false" : "Value";
1470
+ const hint = (t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pl-0.5 text-interface-labels-xs-light text-text-default-subdued", children: t });
1471
+ const textOp = ["CONTAINS", "NOT CONTAINS", "~", "!~"].includes(cond.op);
1472
+ if (a === "none") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "flex h-7 items-center px-1 text-interface-labels-xs-light text-text-default-subdued", children: "no value needed" });
1473
+ if (a === "two")
1474
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex min-w-0 flex-1 items-center gap-1.5", children: [
1475
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: one, onChange: (e) => set([e.target.value, two]), inputMode: "decimal", placeholder: "From", className: `${INPUT} w-24` }),
1476
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "text-interface-body-s-normal text-text-default-subtle", children: "and" }),
1477
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: two, onChange: (e) => set([one, e.target.value]), inputMode: "decimal", placeholder: "To", className: `${INPUT} w-24` }),
1478
+ hint(type === "latency" ? "ms \xB7 both ends included" : "both ends included")
1479
+ ] });
1480
+ if (a === "list")
1481
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1482
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Chips, { values: cond.values, onValues: set, placeholder, quoted, field: cond.field, options: catalog }),
1483
+ catalog && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ValuePick, { add: true, options: catalog.filter((v) => !cond.values.includes(v)), quoted, field: cond.field, onPick: (v) => set([...cond.values, v]) })
1484
+ ] });
1485
+ if (a === "ip")
1486
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: cond.values.join(", "), onChange: (e) => set(e.target.value.split(",").map((v) => v.trim())), placeholder: "10.0.0.0/24 or 10.0.0.1-10.0.0.50, comma for several", className: `${INPUT} w-full max-w-[340px]` }) });
1487
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex min-w-0 flex-1 items-center gap-1.5", children: [
1488
+ catalog && (cond.op === "==" || cond.op === "!=") ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ValuePick, { value: one, options: catalog, quoted, field: cond.field, onPick: (v) => set([v]) }) : quoted ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex h-7 w-[220px] min-w-0 items-center rounded-md border border-stroke-subsection font-mono text-code-editor-small hover:border-stroke-section focus-within:border-stroke-active", children: [
1489
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pl-1.5 text-text-default-subdued", children: cond.op === "~" || cond.op === "!~" ? "/" : '"' }),
1490
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: one, onChange: (e) => set([e.target.value.replace(/^"(.*)"$/s, "$1")]), placeholder, spellCheck: false, className: "h-full min-w-0 flex-1 bg-transparent px-0.5 text-text-default-regular outline-none placeholder:font-sans placeholder:text-text-default-disabled" }),
1491
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pr-1.5 text-text-default-subdued", children: cond.op === "~" || cond.op === "!~" ? "/" : '"' })
1492
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: one, onChange: (e) => set([e.target.value]), inputMode: type === "boolean" ? void 0 : "decimal", placeholder, className: `${INPUT} w-[180px]` }),
1493
+ type === "latency" && hint("ms"),
1494
+ textOp && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => onChange({ ci: !cond.ci }), "aria-pressed": cond.ci, "data-pqb-tip": cond.ci ? "Any case (click for exact case)" : "Exact case (click for any case)", className: `h-6 shrink-0 rounded px-1.5 font-mono text-interface-labels-xs-normal font-semibold ${cond.ci ? "bg-surface-color-blue-default-subtle text-text-color-blue" : "text-text-default-subtle hover:bg-surface-hover-l1-hover"}`, children: "Aa" })
1495
+ ] });
1496
+ }
1497
+ function RowActions({ item, depth, parentJoin, onRoot }) {
1498
+ const btn = (0, import_react.useRef)(null);
1499
+ const [open, setOpen] = (0, import_react.useState)(false);
1500
+ const row = "flex h-8 w-full items-center gap-2 px-2.5 text-left text-interface-body-s-normal text-text-default-regular hover:bg-surface-hover-l1-hover";
1501
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex shrink-0 items-center", children: [
1502
+ depth < 2 && item.kind === "cond" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => onRoot((r) => update(r, item.id, (c) => ({ kind: "group", id: newCond().id, join: parentJoin === "AND" ? "OR" : "AND", not: false, items: [c, newCond()] }))), "data-pqb-tip": "Branch", "aria-label": "Branch from this condition", className: ACT, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.TreeView, { size: 14 }) }),
1503
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => onRoot((r) => tidy(remove(r, item.id), true)), "data-pqb-tip": item.kind === "group" ? "Remove group" : "Remove condition", "aria-label": "Remove", className: `${ACT} hover:text-text-color-red`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Trash, { size: 14 }) }),
1504
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "relative", children: [
1505
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { ref: btn, onClick: () => setOpen(!open), "aria-expanded": open, "aria-label": "More", "data-pqb-tip": "More", className: ACT, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.DotsThreeVertical, { size: 16, weight: "bold" }) }),
1506
+ open && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Menu, { anchor: btn, width: 200, onClose: () => setOpen(false), children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "py-1", children: [
1507
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
1508
+ "button",
1509
+ {
1510
+ onClick: () => {
1511
+ onRoot((r) => insertAfter(r, item.id, clone(item)));
1512
+ setOpen(false);
1513
+ },
1514
+ className: row,
1515
+ children: [
1516
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Copy, { size: 14, className: "text-icon-default" }),
1517
+ "Duplicate"
1518
+ ]
1519
+ }
1520
+ ),
1521
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
1522
+ "button",
1523
+ {
1524
+ onClick: () => {
1525
+ onRoot((r) => update(r, item.id, (x) => ({ ...x, not: !x.not })));
1526
+ setOpen(false);
1527
+ },
1528
+ className: row,
1529
+ children: [
1530
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Prohibit, { size: 14, className: "text-icon-default" }),
1531
+ item.not ? "Remove NOT" : "Negate with NOT"
1532
+ ]
1533
+ }
1534
+ )
1535
+ ] }) })
1536
+ ] })
1537
+ ] });
1538
+ }
1539
+ var NotChip = ({ onClick }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick, "data-pqb-tip": "Negated, click to remove NOT", className: "mt-[3px] h-[22px] shrink-0 rounded bg-surface-color-red-default-subtle px-1.5 font-mono text-code-editor-small font-semibold text-text-color-red", children: "NOT" });
1540
+ function Row({ cond, depth, parentJoin, schema, errors, onRoot }) {
1541
+ const type = cond.field ? typeOf(cond.field, schema) : "string";
1542
+ const set = (patch) => onRoot((r) => update(r, cond.id, (c) => ({ ...c, ...patch })));
1543
+ const err = errors.get(cond.id);
1544
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "group/row", children: [
1545
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "inline-flex max-w-full items-start gap-1.5", children: [
1546
+ cond.not && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(NotChip, { onClick: () => set({ not: false }) }),
1547
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1548
+ FieldPicker,
1549
+ {
1550
+ value: cond.field,
1551
+ schema,
1552
+ autoOpen: !cond.field,
1553
+ onPick: (f) => {
1554
+ const t = typeOf(f, schema);
1555
+ const ops = opsFor({ type: t });
1556
+ const keep = ops.includes(cond.op) && t === type;
1557
+ set({ field: f, op: keep ? cond.op : t === "latency" ? ">" : "==", values: keep ? cond.values : [] });
1558
+ }
1559
+ }
1560
+ ),
1561
+ cond.field && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1562
+ OpPicker,
1563
+ {
1564
+ value: cond.op,
1565
+ type,
1566
+ onPick: (o) => {
1567
+ const from = arity(cond.op);
1568
+ const to = arity(o);
1569
+ set({ op: o, values: from === to ? cond.values : to === "none" ? [] : to === "two" ? [cond.values[0] ?? "", ""] : cond.values.slice(0, to === "list" || to === "ip" ? 99 : 1) });
1570
+ }
1571
+ }
1572
+ ),
1573
+ cond.field && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Values, { cond, type, onChange: set }),
1574
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RowActions, { item: cond, depth, parentJoin, onRoot })
1575
+ ] }),
1576
+ err && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "flex items-center gap-1.5 pt-0.5 text-interface-labels-xs-normal text-text-color-red", children: [
1577
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Warning, { size: 12, weight: "fill", className: "shrink-0" }),
1578
+ err
1579
+ ] })
1580
+ ] });
1581
+ }
1582
+ function Group({ group, depth, schema, errors, onRoot, parentJoin }) {
1583
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative pl-6", children: [
1584
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { "aria-hidden": "true", className: `absolute left-2 ${depth > 0 ? "top-[14px]" : "top-0"} bottom-[9px] w-px bg-stroke-section` }),
1585
+ depth > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "group/row -ml-6 mb-1 flex items-center gap-1.5 pl-6", children: [
1586
+ group.not && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(NotChip, { onClick: () => onRoot((r) => update(r, group.id, (g) => ({ ...g, not: false }))) }),
1587
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "text-interface-labels-xs-light text-text-default-subdued", children: "Group" }),
1588
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RowActions, { item: group, depth, parentJoin, onRoot })
1589
+ ] }),
1590
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "flex flex-col", children: group.items.map((item, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
1591
+ i > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => onRoot((r) => update(r, item.id, (x) => ({ ...x, j: (item.j || group.join) === "AND" ? "OR" : "AND" }))), "data-pqb-tip": `Switch to ${(item.j || group.join) === "AND" ? "OR" : "AND"}`, className: "relative -ml-6 my-1 block h-5 rounded bg-surface-color-blue-default-subtle px-1.5 text-interface-labels-xs-normal font-semibold text-text-color-blue hover:bg-surface-color-blue-hover-subtle", children: item.j || group.join }),
1592
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative", children: [
1593
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { "aria-hidden": "true", className: "absolute -left-4 top-[14px] h-px w-4 bg-stroke-section" }),
1594
+ item.kind === "cond" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Row, { cond: item, depth, parentJoin: item.j || group.join, schema, errors, onRoot }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "-ml-2", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Group, { group: item, depth: depth + 1, schema, errors, onRoot, parentJoin: item.j || group.join }) })
1595
+ ] })
1596
+ ] }, item.id)) }),
1597
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "relative -ml-6 mt-1 block h-[18px]", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => onRoot((r) => {
1598
+ var _a;
1599
+ return r.id === group.id ? { ...r, items: [...r.items, { ...newCond(), j: (_a = group.items[group.items.length - 1]) == null ? void 0 : _a.j }] } : update(r, group.id, (g) => {
1600
+ var _a2;
1601
+ return { ...g, items: [...g.items, { ...newCond(), j: (_a2 = group.items[group.items.length - 1]) == null ? void 0 : _a2.j }] };
1602
+ });
1603
+ }), "aria-label": "Add a condition", "data-pqb-tip": "Add a condition", className: "ml-[1px] grid h-[15px] w-[15px] place-items-center rounded-full border border-stroke-section bg-surface-default-l1 text-icon-subtle hover:border-stroke-active hover:text-text-color-blue", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Plus, { size: 9, weight: "bold" }) }) })
1604
+ ] });
1605
+ }
1606
+ function CountRow({ count, schema, onChange, onRemove }) {
1607
+ const set = (patch) => onChange({ ...count, ...patch });
1608
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "group/row mt-2 flex flex-wrap items-start gap-1.5 border-t border-stroke-subsection pl-6 pt-2", children: [
1609
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "mt-[3px] flex h-[22px] items-center rounded bg-surface-color-blue-default-subtle px-1.5 font-mono text-code-editor-small font-semibold text-text-color-purple", children: "COUNT()" }),
1610
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", { value: count.op, onChange: (e) => set({ op: e.target.value }), className: `${INPUT} w-16`, children: [">", ">=", "<", "<=", "=="].map((o) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: o, children: o }, o)) }),
1611
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: count.n, onChange: (e) => set({ n: e.target.value }), inputMode: "numeric", placeholder: "Number", className: `${INPUT} w-24` }),
1612
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "flex h-7 items-center text-interface-body-s-normal text-text-default-subtle", children: "within" }),
1613
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { value: count.within, onChange: (e) => set({ within: e.target.value }), placeholder: "time range", className: `${INPUT} w-24` }),
1614
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "flex h-7 items-center text-interface-body-s-normal text-text-default-subtle", children: "group by" }),
1615
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FieldPicker, { value: count.by, schema, placeholder: "Whole result", onPick: (f) => set({ by: f === "@latency" ? "" : f }) }),
1616
+ count.by && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => set({ by: "" }), "data-pqb-tip": "Count the whole result", "aria-label": "Remove group by", className: ACT, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.X, { size: 12 }) }),
1617
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: onRemove, "data-pqb-tip": "Remove COUNT()", "aria-label": "Remove COUNT()", className: `${ACT} hover:text-text-color-red`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Trash, { size: 14 }) })
1618
+ ] });
1619
+ }
1620
+ function Builder({ text, schema, onApply, onCancel }) {
1621
+ var _a;
1622
+ const start = (0, import_react.useMemo)(() => {
1623
+ const p = parse(text, schema);
1624
+ const ok = text.trim() && !p.errors.length;
1625
+ const tree = toTree(ok ? p.ast : null);
1626
+ if (!tree.items.length && !tree.count) tree.items = [newCond()];
1627
+ return { tree, replaced: !!text.trim() && !ok };
1628
+ }, []);
1629
+ const [root, setRoot] = (0, import_react.useState)(start.tree);
1630
+ const [show, setShow] = (0, import_react.useState)(false);
1631
+ const onRoot = (fn) => setRoot((r) => fn(r));
1632
+ const out = (0, import_react.useMemo)(() => fromTree(root, schema), [root, schema]);
1633
+ const parsed = (0, import_react.useMemo)(() => out ? parse(out, schema) : null, [out, schema]);
1634
+ const clean = parsed && !parsed.errors.length ? format(parsed.ast) : out;
1635
+ const incomplete = (0, import_react.useMemo)(() => {
1636
+ let n = 0;
1637
+ const walk = (g) => g.items.forEach((x) => x.kind === "group" ? walk(x) : x.field && !isComplete(x) && n++);
1638
+ walk(root);
1639
+ if (root.count && !String(root.count.n).trim()) n++;
1640
+ return n;
1641
+ }, [root]);
1642
+ const error = (_a = parsed == null ? void 0 : parsed.errors[0]) == null ? void 0 : _a.msg;
1643
+ const blocked = incomplete > 0 || !!error;
1644
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "border-t border-stroke-subsection", onMouseDown: (e) => e.stopPropagation(), children: [
1645
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "max-h-[380px] min-h-[96px] overflow-auto scroll-thin bg-surface-default-l1 px-3 pb-2 pt-3", children: [
1646
+ start.replaced && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "mb-2 text-interface-labels-xs-light text-text-default-subdued", children: "The query in the bar has an error, so the builder starts empty. Apply replaces it." }),
1647
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Group, { group: root, depth: 0, schema, errors: /* @__PURE__ */ new Map(), onRoot }),
1648
+ root.count ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CountRow, { count: root.count, schema, onChange: (c) => setRoot({ ...root, count: c }), onRemove: () => setRoot({ ...root, count: null }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => setRoot({ ...root, count: { op: ">", n: "", within: "", by: "" } }), className: "mt-1 h-6 rounded px-1.5 text-interface-labels-xs-normal text-text-color-blue hover:bg-surface-hover-l1-hover", children: "Add COUNT() threshold" })
1649
+ ] }),
1650
+ show && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "border-t border-stroke-subsection px-3 py-2", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { style: { maxHeight: 200 }, className: "overflow-auto scroll-thin whitespace-pre-wrap break-all font-mono text-code-editor-small leading-5 text-text-default-subdued", children: clean ? paint(parsed && !parsed.errors.length ? format(parsed.ast, null, true) : clean, schema) : "No filter" }) }),
1651
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-center gap-2 border-t border-stroke-subsection px-3 py-2", children: [
1652
+ incomplete > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex min-w-0 items-center gap-1.5 text-interface-labels-xs-normal text-text-color-red", children: [
1653
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Warning, { size: 12, weight: "fill", className: "shrink-0" }),
1654
+ incomplete === 1 ? "Finish 1 condition to run" : `Finish ${incomplete} conditions to run`
1655
+ ] }) : error ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "flex min-w-0 items-center gap-1.5 truncate text-interface-labels-xs-normal text-text-color-red", children: [
1656
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(P.Warning, { size: 12, weight: "fill", className: "shrink-0" }),
1657
+ error
1658
+ ] }) : null,
1659
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ml-auto" }),
1660
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => setShow(!show), "aria-pressed": show, className: "h-6 shrink-0 rounded-[5px] border border-stroke-subsection bg-surface-default-ground px-2.5 text-interface-labels-xs-normal font-semibold text-text-default-regular hover:bg-surface-hover-l1-hover", children: show ? "Hide query" : "Show query" }),
1661
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: onCancel, className: "h-6 shrink-0 rounded-[5px] border border-stroke-subsection bg-surface-default-ground px-2.5 text-interface-labels-xs-normal font-semibold text-text-default-regular hover:bg-surface-hover-l1-hover", children: "Cancel" }),
1662
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { disabled: blocked, onClick: () => onApply(clean || ""), className: "h-6 shrink-0 rounded-[5px] border border-stroke-active bg-surface-default-action px-2.5 text-interface-labels-xs-normal font-semibold text-text-default-static hover:bg-surface-default-action-hover disabled:cursor-not-allowed disabled:opacity-50", children: "Apply & run" })
1663
+ ] })
1664
+ ] });
1665
+ }
1666
+
1667
+ // src/react/QueryBox.jsx
1668
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1669
+ var ROLE = { field: "text-base-blue-1100", op: "text-text-color-purple", kw: "font-semibold text-text-color-purple", str: "text-text-color-success", num: "text-text-color-cyan", bool: "text-text-color-orange", fn: "font-semibold text-text-color-purple", punct: "text-text-default-subtle" };
1670
+ var DEFAULT = { kw: ROLE.kw, str: ROLE.str, num: ROLE.num, dur: ROLE.num, bool: ROLE.bool, op: ROLE.op, word: ROLE.field };
1671
+ var cls = (t) => t.role === "op" && t.t === "op" ? "text-text-default-subdued" : ROLE[t.role] || DEFAULT[t.t] || "";
1672
+ var TYPE_ICON2 = { string: import_react3.TextT, numtext: import_react3.TextT, number: import_react3.Hash, boolean: import_react3.ToggleLeft, ip: import_react3.Globe, latency: import_react3.Timer };
1673
+ var PAIRS = { '"': '"', "]": "]", ")": ")" };
1674
+ var MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
1675
+ function paint(text, schema, tipFor) {
1676
+ const { toks } = parse(text, schema);
1677
+ const out = [];
1678
+ let at = 0;
1679
+ for (const t of toks) {
1680
+ if (t.s > at) out.push(text.slice(at, t.s));
1681
+ const tip = tipFor && t.role === "field" ? tipFor(t.raw) : null;
1682
+ out.push(
1683
+ tip ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { "data-pqb-tip": tip, "data-mono": "", className: `${cls(t)} underline decoration-dotted`, children: t.raw }, t.s) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: cls(t), children: t.raw }, t.s)
1684
+ );
1685
+ at = t.e;
1686
+ }
1687
+ out.push(text.slice(at));
1688
+ return out;
1689
+ }
1690
+ function Tips({ root }) {
1691
+ const [tip, setTip] = (0, import_react2.useState)(null);
1692
+ (0, import_react2.useEffect)(() => {
1693
+ let timer;
1694
+ const over = (e) => {
1695
+ var _a, _b, _c;
1696
+ const el = (_b = (_a = e.target).closest) == null ? void 0 : _b.call(_a, "[data-pqb-tip]");
1697
+ clearTimeout(timer);
1698
+ if (!el || !el.dataset.pqbTip || !((_c = root.current) == null ? void 0 : _c.contains(el)) || el.getAttribute("aria-expanded") === "true") return setTip(null);
1699
+ if (el.dataset.trunc !== void 0 && el.scrollWidth <= el.clientWidth) return setTip(null);
1700
+ const r = el.getBoundingClientRect();
1701
+ timer = setTimeout(() => setTip({ text: el.dataset.pqbTip, mono: el.dataset.mono !== void 0, side: el.dataset.side, r }), 200);
1702
+ };
1703
+ const hide = () => {
1704
+ clearTimeout(timer);
1705
+ setTip(null);
1706
+ };
1707
+ document.addEventListener("mouseover", over);
1708
+ document.addEventListener("mousedown", hide, true);
1709
+ document.addEventListener("scroll", hide, true);
1710
+ return () => {
1711
+ clearTimeout(timer);
1712
+ document.removeEventListener("mouseover", over);
1713
+ document.removeEventListener("mousedown", hide, true);
1714
+ document.removeEventListener("scroll", hide, true);
1715
+ };
1716
+ }, []);
1717
+ if (!tip) return null;
1718
+ const place = (el) => {
1719
+ if (!el) return;
1720
+ const { r } = tip;
1721
+ const w = el.offsetWidth;
1722
+ const h = el.offsetHeight;
1723
+ const a = el.firstChild.style;
1724
+ if (tip.side === "right") {
1725
+ const top = Math.max(8, r.top + r.height / 2 - h / 2);
1726
+ el.style.left = r.right + 8 + "px";
1727
+ el.style.top = top + "px";
1728
+ Object.assign(a, { left: "-4px", top: Math.min(h - 12, Math.max(4, r.top + r.height / 2 - top - 4)) + "px" });
1729
+ return;
1730
+ }
1731
+ const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.left + r.width / 2 - w / 2));
1732
+ const below = r.bottom + 8 + h < window.innerHeight;
1733
+ el.style.left = left + "px";
1734
+ el.style.top = (below ? r.bottom + 8 : r.top - h - 8) + "px";
1735
+ Object.assign(a, { left: Math.min(w - 12, Math.max(4, r.left + r.width / 2 - left - 4)) + "px", top: below ? "-4px" : h - 4 + "px" });
1736
+ };
1737
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { ref: place, role: "tooltip", style: { position: "fixed", zIndex: 100, left: -9999, top: -9999, background: "#000", fontSize: tip.mono ? 11 : 13, lineHeight: tip.mono ? "16px" : "18px" }, className: `pointer-events-none w-max max-w-[520px] whitespace-pre-wrap break-words rounded-md px-2.5 py-1.5 font-medium text-text-default-static shadow-e300 ${tip.mono ? "font-mono" : ""}`, children: [
1738
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { "aria-hidden": "true", style: { position: "absolute", width: 8, height: 8, background: "#000", transform: "rotate(45deg)" } }),
1739
+ tip.text
1740
+ ] });
1741
+ }
1742
+ var closes = (text, pos) => {
1743
+ let n = 0;
1744
+ for (let i = 0; i < pos; i++) {
1745
+ if (text[i] === "\\") i++;
1746
+ else if (text[i] === '"') n++;
1747
+ }
1748
+ return n % 2 === 1;
1749
+ };
1750
+ function QueryBox({ text, setText, schema, onRun, tools, actions, runErrors, setRunErrors, runRef, adv, setAdv, placeholder }) {
1751
+ var _a, _b, _c, _d;
1752
+ const ta = (0, import_react2.useRef)(null);
1753
+ const pre = (0, import_react2.useRef)(null);
1754
+ const list = (0, import_react2.useRef)(null);
1755
+ const nextCaret = (0, import_react2.useRef)(null);
1756
+ const stepped = (0, import_react2.useRef)(null);
1757
+ const last = (0, import_react2.useRef)(text);
1758
+ last.current = text;
1759
+ const [caret, setCaret] = (0, import_react2.useState)(0);
1760
+ const [focus, setFocus] = (0, import_react2.useState)(false);
1761
+ const [open, setOpen] = (0, import_react2.useState)(false);
1762
+ const [hl, setHl] = (0, import_react2.useState)(0);
1763
+ const sugg = (0, import_react2.useMemo)(() => focus && open ? context(text, caret, schema) : null, [focus, open, text, caret, schema]);
1764
+ const items = (sugg == null ? void 0 : sugg.items) || [];
1765
+ const parsed = (0, import_react2.useMemo)(() => parse(text, schema), [text, schema]);
1766
+ const [ranged, setRanged] = (0, import_react2.useState)(false);
1767
+ const startHl = (sugg == null ? void 0 : sugg.title) === "Combine" || (sugg == null ? void 0 : sugg.title) === "Add another value" || ((_a = sugg == null ? void 0 : sugg.title) == null ? void 0 : _a.startsWith("Regex syntax")) ? -1 : 0;
1768
+ (0, import_react2.useLayoutEffect)(() => {
1769
+ setHl(startHl);
1770
+ if (list.current) list.current.scrollTop = 0;
1771
+ }, [sugg == null ? void 0 : sugg.kind, sugg == null ? void 0 : sugg.title, sugg == null ? void 0 : sugg.from, startHl]);
1772
+ (0, import_react2.useLayoutEffect)(() => {
1773
+ if (nextCaret.current !== null && ta.current) {
1774
+ ta.current.setSelectionRange(nextCaret.current, nextCaret.current);
1775
+ setCaret(nextCaret.current);
1776
+ nextCaret.current = null;
1777
+ }
1778
+ }, [text]);
1779
+ (0, import_react2.useEffect)(() => {
1780
+ var _a2, _b2;
1781
+ (_b2 = (_a2 = list.current) == null ? void 0 : _a2.querySelector("[data-hl]")) == null ? void 0 : _b2.scrollIntoView({ block: "nearest" });
1782
+ }, [hl]);
1783
+ const visible = (0, import_react2.useMemo)(() => parsed.errors.filter((e) => runErrors || !e.eof && (e.e < caret || caret < e.s || !focus)), [parsed, runErrors, caret, focus]);
1784
+ const highlighted = (0, import_react2.useMemo)(() => {
1785
+ const out = [];
1786
+ let at = 0;
1787
+ const marked = visible.find((e) => e.at !== void 0);
1788
+ const mark = marked == null ? void 0 : marked.at;
1789
+ const lo = marked && Math.min(marked.s, mark);
1790
+ const hi = marked && Math.max(marked.e, mark);
1791
+ const tint = (a, b) => marked && a >= lo && b <= hi ? " bg-base-red-100" : "";
1792
+ const pin = (k) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "relative", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { position: "absolute", left: 0, top: -1, height: 20, width: 2, borderRadius: 1, background: "var(--color-text-color-red)" } }) }, "at" + k);
1793
+ for (const t of parsed.toks) {
1794
+ if (t.s > at) out.push(/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: tint(at, t.s), children: text.slice(at, t.s) }, "g" + at));
1795
+ const bad = visible.some((e) => t.s < e.e && t.e > e.s);
1796
+ out.push(/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: (bad ? "text-text-color-red underline decoration-dotted" : cls(t)) + tint(t.s, t.e), children: text.slice(t.s, t.e) }, t.s));
1797
+ at = t.e;
1798
+ if (mark === t.e) out.push(pin(t.e));
1799
+ }
1800
+ out.push(text.slice(at));
1801
+ return out;
1802
+ }, [parsed, text, visible]);
1803
+ const edit = (value, pos, keep) => {
1804
+ nextCaret.current = pos;
1805
+ setText(value);
1806
+ setRunErrors(false);
1807
+ setOpen(keep);
1808
+ };
1809
+ const accept = (item) => {
1810
+ let from = item.from ?? sugg.from;
1811
+ if (item.trim) while (from > 0 && /\s/.test(text[from - 1])) from--;
1812
+ const ins = item.insert;
1813
+ edit(text.slice(0, from) + ins + text.slice(item.to ?? sugg.to), from + (item.caretAt ?? ins.length), !!item.reopen);
1814
+ };
1815
+ const run = (src = text) => {
1816
+ setOpen(false);
1817
+ const p = parse(src, schema);
1818
+ if (p.errors.length) {
1819
+ setRunErrors(true);
1820
+ return;
1821
+ }
1822
+ const clean = format(p.ast);
1823
+ const shown = focus ? format(p.ast, null, true) : clean;
1824
+ if (shown !== text) edit(shown, shown.length, false);
1825
+ onRun == null ? void 0 : onRun(clean, p.ast);
1826
+ };
1827
+ if (runRef) runRef.current = run;
1828
+ const skip = (pos) => {
1829
+ nextCaret.current = pos;
1830
+ ta.current.setSelectionRange(pos, pos);
1831
+ setCaret(pos);
1832
+ setOpen(true);
1833
+ };
1834
+ const onKeyDown = (e) => {
1835
+ const el = ta.current;
1836
+ stepped.current = null;
1837
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
1838
+ e.preventDefault();
1839
+ run();
1840
+ return;
1841
+ }
1842
+ if (e.ctrlKey && e.key === " ") {
1843
+ e.preventDefault();
1844
+ setOpen(true);
1845
+ return;
1846
+ }
1847
+ if (open && items.length) {
1848
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1849
+ e.preventDefault();
1850
+ const d = e.key === "ArrowDown" ? 1 : -1;
1851
+ setHl((h) => h < 0 ? d > 0 ? 0 : items.length - 1 : (h + d + items.length) % items.length);
1852
+ return;
1853
+ }
1854
+ if (e.key === "Enter" && !e.shiftKey && hl >= 0) {
1855
+ e.preventDefault();
1856
+ accept(items[hl]);
1857
+ return;
1858
+ }
1859
+ }
1860
+ if (e.key === "Escape") {
1861
+ e.preventDefault();
1862
+ if (open && items.length) setOpen(false);
1863
+ else el.blur();
1864
+ return;
1865
+ }
1866
+ if (e.key === "Enter" && !e.shiftKey) {
1867
+ e.preventDefault();
1868
+ run();
1869
+ return;
1870
+ }
1871
+ const at = el.selectionStart;
1872
+ const live = el.value;
1873
+ last.current = live;
1874
+ if (e.key === " " && at === el.selectionEnd && live[at - 1] === " " && !((live.slice(0, at).match(/(?<!\\)"/g) || []).length % 2)) {
1875
+ e.preventDefault();
1876
+ return;
1877
+ }
1878
+ if (PAIRS[e.key] && at === el.selectionEnd && live[at] === e.key && (e.key !== '"' || closes(live, at))) {
1879
+ e.preventDefault();
1880
+ stepped.current = { pos: at + 1, c: e.key };
1881
+ skip(at + 1);
1882
+ }
1883
+ };
1884
+ const onChange = (e) => {
1885
+ const value = e.target.value;
1886
+ const pos = e.target.selectionStart;
1887
+ const prev = last.current;
1888
+ const st = stepped.current;
1889
+ stepped.current = null;
1890
+ if (st && value === prev.slice(0, st.pos) + st.c + prev.slice(st.pos)) {
1891
+ e.target.value = prev;
1892
+ setText(prev);
1893
+ skip(st.pos);
1894
+ return;
1895
+ }
1896
+ if (value.length === prev.length + 1 && value.slice(pos - 2, pos) === ". " && value.slice(0, pos - 2) + " " + value.slice(pos) === prev) {
1897
+ e.target.value = prev;
1898
+ setText(prev);
1899
+ skip(pos - 1);
1900
+ return;
1901
+ }
1902
+ const n = value.length - prev.length;
1903
+ const c = value[pos - 1];
1904
+ if (n >= 1 && PAIRS[c] && value.slice(0, pos - n) + value.slice(pos) === prev && prev[pos - n] === c && (c !== '"' || closes(value, pos - 1))) {
1905
+ const v = value.slice(0, pos - 1) + value.slice(pos);
1906
+ e.target.value = v;
1907
+ last.current = v;
1908
+ setText(v);
1909
+ setRunErrors(false);
1910
+ skip(pos);
1911
+ return;
1912
+ }
1913
+ last.current = value;
1914
+ setText(value);
1915
+ setCaret(pos);
1916
+ setRunErrors(false);
1917
+ setOpen(true);
1918
+ };
1919
+ const sync = () => setCaret(ta.current.selectionStart);
1920
+ const showCard = !adv && focus && open && !ranged && items.length > 0;
1921
+ const err = visible[0];
1922
+ const showNotice = !adv && !showCard && err && (focus || runErrors);
1923
+ const fix = (s, e, t) => {
1924
+ edit(text.slice(0, s) + t + text.slice(e), s + t.length, true);
1925
+ ta.current.focus();
1926
+ };
1927
+ const lifted = focus || showNotice || adv;
1928
+ const kfmt = (n) => n >= 1e3 ? (n / 1e3).toFixed(2).replace(/\.?0+$/, "") + "k" : n;
1929
+ let lastGroup = sugg == null ? void 0 : sugg.title;
1930
+ const row = "relative flex h-7 cursor-pointer items-center gap-2 rounded px-2";
1931
+ const chips = showCard && items.some((it) => !it.pin) && items.every((it) => it.pin || it.kind === "value");
1932
+ const rowsOf = [];
1933
+ if (chips)
1934
+ items.forEach((it, i) => {
1935
+ if (it.pin) return;
1936
+ const raw = it.label.replace(/^"(.*)"$/, "$1");
1937
+ const cls2 = /^\d{3}$/.test(raw) ? raw[0] + "XX" : "";
1938
+ const last2 = rowsOf[rowsOf.length - 1];
1939
+ if (last2 && last2.group === it.group && last2.cls === cls2) last2.items.push([it, i]);
1940
+ else rowsOf.push({ group: it.group, cls: cls2, head: (!last2 || last2.group !== it.group) && it.group, items: [[it, i]] });
1941
+ });
1942
+ const grouped = showCard && !chips && items.some((it) => !it.pin && it.group);
1943
+ const groupsOf = [];
1944
+ if (grouped)
1945
+ items.forEach((it, i) => {
1946
+ if (it.pin) return;
1947
+ const last2 = groupsOf[groupsOf.length - 1];
1948
+ if (last2 && last2.group === (it.group || "")) last2.items.push([it, i]);
1949
+ else groupsOf.push({ group: it.group || "", items: [[it, i]] });
1950
+ });
1951
+ const renderRow = (it, i, bare) => {
1952
+ var _a2;
1953
+ const head = !bare && it.group && it.group !== lastGroup ? it.group : null;
1954
+ lastGroup = it.group;
1955
+ const segs = (_a2 = schema.byPath[it.label]) == null ? void 0 : _a2.segs;
1956
+ const dot = segs ? it.label.length - segs[segs.length - 1].length : it.label.search(/[^.]*$/);
1957
+ const Icon = TYPE_ICON2[it.type];
1958
+ const raw = it.label.replace(/^"(.*)"$/, "$1");
1959
+ const vs = it.kind === "value" && valueStyle(raw);
1960
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
1961
+ head && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: `px-2 pb-1 text-interface-titles-caption text-text-default-subdued ${i > 0 ? "pt-2" : ""}`, children: head.toUpperCase() }),
1962
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { "data-hl": i === hl || void 0, style: { scrollMarginTop: 28 }, onMouseMove: () => i !== hl && setHl(i), onClick: () => accept(it), className: `${row} ${i === hl ? "bg-surface-color-blue-default-subtle" : ""}`, children: [
1963
+ it.kind === "field" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1964
+ Icon && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, { size: 13, className: "shrink-0 text-icon-subtle" }),
1965
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "min-w-0 truncate font-mono text-code-editor-small", children: it.sub ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1966
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "font-semibold text-base-blue-1100", children: it.label }),
1967
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "text-text-default-subtle", children: [
1968
+ " ",
1969
+ it.sub
1970
+ ] })
1971
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1972
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "text-text-default-subtle", children: it.label.slice(0, dot) }),
1973
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "font-semibold text-base-blue-1100", children: it.label.slice(dot) })
1974
+ ] }) }),
1975
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "flex-1" }),
1976
+ it.count !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "w-9 shrink-0 text-right text-interface-labels-xs-normal text-text-default-subtle", children: kfmt(it.count) })
1977
+ ] }),
1978
+ (it.kind === "op" || it.kind === "kw" || it.kind === "fn") && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1979
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `shrink-0 font-mono text-code-editor-small font-semibold ${it.num ? ROLE.num : it.str ? ROLE.str : "text-text-color-purple"}`, children: it.label }),
1980
+ it.sub && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "ml-auto min-w-0 truncate text-interface-body-s-normal text-text-default-subdued", children: it.sub })
1981
+ ] }),
1982
+ it.kind === "value" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1983
+ vs ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { ...vs, padding: vs.background ? "0 4px" : 0 }, className: "min-w-0 truncate font-mono text-code-editor-small", children: raw }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `min-w-0 truncate font-mono text-code-editor-small ${it.label.startsWith('"') ? ROLE.str : it.label === "true" || it.label === "false" ? ROLE.bool : ROLE.num}`, children: it.label }),
1984
+ it.total ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "ml-auto h-1 w-14 shrink-0 overflow-hidden rounded-full bg-surface-hover-l1-hover", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "block h-full rounded-full bg-base-blue-500", style: { width: Math.max(4, it.count / it.total * 100) + "%" } }) }) : null,
1985
+ it.count !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "w-9 shrink-0 text-right text-interface-labels-xs-normal text-text-default-subtle", children: kfmt(it.count) })
1986
+ ] }),
1987
+ i === hl && (it.kind === "field" || it.kind === "value") && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("kbd", { className: `${it.kind === "field" || it.total ? "" : "ml-auto"} shrink-0 rounded border border-stroke-subsection bg-surface-default-ground px-1 font-sans text-[10px] leading-4 text-text-default-subtle`, children: "Enter" })
1988
+ ] })
1989
+ ] }, i);
1990
+ };
1991
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { "data-qbox": "", className: "relative h-8 min-w-0 flex-1", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `absolute inset-x-0 top-0 rounded-md border ${lifted ? `z-40 bg-surface-default-l1 shadow-e300 ${showNotice && runErrors ? "border-stroke-red-regular" : "border-stroke-active"}` : `${runErrors && parsed.errors.length ? "border-stroke-red-regular" : "border-stroke-subsection"} bg-surface-default-underground`}`, children: [
1992
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-start", children: [
1993
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: `flex h-[30px] shrink-0 items-center pl-2 ${adv ? "invisible" : ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.Funnel, { size: 14, className: "text-icon-default" }) }),
1994
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `group/filter relative min-w-0 flex-1 ${adv ? "invisible" : ""}`, children: [
1995
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { ref: pre, "aria-hidden": "true", style: focus ? { maxHeight: 210 } : void 0, className: `pointer-events-none px-2 py-[5px] font-mono text-code-editor-small leading-5 ${focus ? "overflow-hidden whitespace-pre-wrap break-words" : "h-[30px] overflow-hidden whitespace-pre"}`, children: [
1996
+ highlighted,
1997
+ "\u200B"
1998
+ ] }),
1999
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2000
+ "textarea",
2001
+ {
2002
+ ref: ta,
2003
+ rows: 1,
2004
+ wrap: focus ? "soft" : "off",
2005
+ value: text,
2006
+ spellCheck: false,
2007
+ "aria-label": "Filter",
2008
+ placeholder,
2009
+ onSelect: (e) => setRanged(e.target.selectionStart !== e.target.selectionEnd),
2010
+ onChange,
2011
+ onKeyDown,
2012
+ onKeyUp: (e) => {
2013
+ if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key) || !open && ["ArrowUp", "ArrowDown"].includes(e.key)) sync();
2014
+ },
2015
+ onClick: () => {
2016
+ sync();
2017
+ setOpen(true);
2018
+ },
2019
+ onFocus: () => {
2020
+ setFocus(true);
2021
+ setOpen(true);
2022
+ const pretty = parsed.ast && !parsed.errors.length ? format(parsed.ast, null, true) : text;
2023
+ if (pretty === text) return sync();
2024
+ const n = text.slice(0, ta.current.selectionStart).replace(/\s/g, "").length;
2025
+ let i = 0;
2026
+ for (let k = 0; i < pretty.length && k < n; i++) if (!/\s/.test(pretty[i])) k++;
2027
+ nextCaret.current = i;
2028
+ setText(pretty);
2029
+ },
2030
+ onBlur: () => {
2031
+ setFocus(false);
2032
+ setOpen(false);
2033
+ if (text.includes("\n")) setText(parsed.ast && !parsed.errors.length ? format(parsed.ast) : text.replace(/\s*\n\s*/g, " "));
2034
+ ta.current.scrollTop = 0;
2035
+ if (pre.current) pre.current.scrollTop = 0;
2036
+ },
2037
+ onScroll: (e) => {
2038
+ if (pre.current) pre.current.scrollTop = e.target.scrollTop;
2039
+ },
2040
+ className: `absolute inset-0 h-full w-full resize-none ${focus ? "no-scrollbar overflow-y-auto" : "overflow-hidden"} bg-transparent px-2 py-[5px] font-mono text-code-editor-small leading-5 text-transparent caret-[var(--color-text-default-regular)] outline-none placeholder:text-text-default-disabled`
2041
+ }
2042
+ )
2043
+ ] }),
2044
+ text && !adv && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "flex h-[30px] shrink-0 items-center", children: [
2045
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { onMouseDown: (e) => e.preventDefault(), onClick: () => edit("", 0, true), "data-pqb-tip": "Clear filter", "aria-label": "Clear filter", className: "grid h-6 w-6 place-items-center rounded text-icon-default hover:bg-surface-hover-l1-hover", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.X, { size: 13 }) }),
2046
+ focus && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { onMouseDown: (e) => e.preventDefault(), onClick: () => {
2047
+ var _a2;
2048
+ return (_a2 = navigator.clipboard) == null ? void 0 : _a2.writeText(text);
2049
+ }, "data-pqb-tip": "Copy query", "aria-label": "Copy query", className: "grid h-6 w-6 place-items-center rounded text-icon-default hover:bg-surface-hover-l1-hover", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.Copy, { size: 13 }) }),
2050
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "w-1" })
2051
+ ] }),
2052
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "flex h-[30px] shrink-0 items-center gap-0.5 px-1", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { onMouseDown: (e) => e.preventDefault(), onClick: () => {
2053
+ if (!adv) ta.current.blur();
2054
+ setAdv(!adv);
2055
+ }, "aria-pressed": adv, "data-pqb-tip": "Build the filter with AND / OR groups", className: `flex h-6 items-center gap-1 rounded px-1.5 ${adv ? "bg-surface-color-blue-default-subtle text-text-color-blue" : "text-text-default-regular hover:bg-surface-hover-l1-hover"}`, children: [
2056
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.TreeStructure, { size: 14, className: adv ? "" : "text-icon-default" }),
2057
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "whitespace-nowrap text-interface-body-s-heavy", children: "Advanced filter" })
2058
+ ] }) }),
2059
+ (tools || actions) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex shrink-0 self-stretch border-l border-stroke-subsection pl-1 pr-1", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "flex min-h-[30px] flex-col items-stretch", children: [
2060
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "flex min-h-[30px] items-center", children: tools }),
2061
+ focus && !adv && actions
2062
+ ] }) })
2063
+ ] }),
2064
+ adv && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2065
+ Builder,
2066
+ {
2067
+ text,
2068
+ schema,
2069
+ onCancel: () => setAdv(false),
2070
+ onApply: (t) => {
2071
+ setAdv(false);
2072
+ edit(t, t.length, false);
2073
+ run(t);
2074
+ }
2075
+ }
2076
+ ),
2077
+ showCard && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "border-t border-stroke-subsection", onMouseDown: (e) => e.preventDefault(), children: [
2078
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `${grouped || chips && ((_b = rowsOf[0]) == null ? void 0 : _b.head) ? "hidden" : "flex"} items-center justify-between gap-3 px-3 pb-1 pt-2`, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "min-w-0 truncate text-interface-titles-caption text-text-default-subdued", children: sugg.title.toUpperCase() }) }),
2079
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { ref: list, style: { maxHeight: 180 }, className: "no-scrollbar overflow-y-auto px-1 pb-1", children: chips ? rowsOf.map((r) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
2080
+ r.head && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "px-2 pb-1 pt-2 text-interface-titles-caption text-text-default-subdued", children: (r === rowsOf[0] && r.head !== sugg.title ? `${sugg.title} / ${r.head}` : r.head).toUpperCase() }),
2081
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex flex-wrap items-center gap-1 px-2 py-1", children: [
2082
+ r.cls && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "w-8 shrink-0 text-interface-labels-xs-normal text-text-default-subdued", children: r.cls }),
2083
+ r.items.map(([it, i]) => {
2084
+ const raw = it.label.replace(/^"(.*)"$/, "$1");
2085
+ const vs = valueStyle(raw);
2086
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { "data-hl": i === hl || void 0, onMouseMove: () => i !== hl && setHl(i), onClick: () => accept(it), style: { ...vs, outline: i === hl ? "2px solid var(--color-stroke-active)" : "none", outlineOffset: 1 }, className: `h-6 rounded px-1.5 font-mono text-code-editor-small ${(vs == null ? void 0 : vs.background) ? "" : "bg-surface-default-underground"} ${vs ? "" : raw === "true" || raw === "false" ? ROLE.bool : ROLE.str}`, children: vs ? raw : it.label }, i);
2087
+ })
2088
+ ] })
2089
+ ] }, r.items[0][1])) : grouped ? groupsOf.map((g) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
2090
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: { position: "sticky", top: 0, zIndex: 1 }, className: "flex items-center justify-between gap-3 bg-surface-default-l1 px-2 pb-1 pt-2 text-interface-titles-caption text-text-default-subdued", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "min-w-0 truncate", children: (g.group ? `${sugg.title} / ${g.group}` : sugg.title).toUpperCase() }) }),
2091
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { children: g.items.map(([it, i]) => renderRow(it, i, true)) })
2092
+ ] }, g.items[0][1])) : items.map((it, i) => !it.pin && renderRow(it, i)) }),
2093
+ items.some((it) => it.pin) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { className: "border-t border-stroke-subsection px-1 pb-1", children: items.map((it, i) => it.pin && renderRow(it, i)) }),
2094
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex items-center gap-3 border-t border-stroke-subsection px-3 py-1.5 text-interface-labels-xs-light text-text-default-subdued", children: [
2095
+ ["\u2191\u2193", "move"],
2096
+ ["Enter", hl < 0 ? "run" : "add"],
2097
+ ["Esc", "close"],
2098
+ [MAC ? "\u2318 Enter" : "Ctrl Enter", "run"],
2099
+ [MAC ? "\u21E7 Enter" : "Shift Enter", "new line"]
2100
+ ].map(([k, l]) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "flex items-center gap-1", children: [
2101
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("kbd", { className: "rounded border border-stroke-subsection bg-surface-default-ground px-1 font-sans text-[10px] leading-4 text-text-default-subtle", children: k }),
2102
+ l
2103
+ ] }, k)) })
2104
+ ] }),
2105
+ showNotice && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-start gap-1.5 border-t border-stroke-subsection px-2.5 py-1.5", onMouseDown: (e) => e.preventDefault(), children: [
2106
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.Warning, { size: 14, weight: "fill", className: "mt-[3px] shrink-0 text-text-color-red" }),
2107
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "min-w-0 flex-1", children: [
2108
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "text-interface-labels-xs-normal leading-5 text-text-color-red", children: err.msg }),
2109
+ (err.fix || ((_c = err.near) == null ? void 0 : _c.length) > 0) && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mt-1 flex flex-wrap items-center gap-1", children: [
2110
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-1 text-interface-labels-xs-light text-text-default-subdued", children: "Suggestions" }),
2111
+ [].concat(err.fix || []).map((f) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { onClick: () => fix(f.s, f.e, f.text), style: { minHeight: 24 }, className: "max-w-full break-words rounded border border-stroke-subsection px-2 py-0.5 text-left font-mono text-interface-labels-xs-normal text-base-blue-1100 hover:bg-surface-hover-l1-hover", children: [
2112
+ f.verb || "Use",
2113
+ " ",
2114
+ f.label
2115
+ ] }, f.verb + f.label)),
2116
+ (_d = err.near) == null ? void 0 : _d.map((n) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { onClick: () => fix(err.s, err.e, n), style: { minHeight: 24 }, className: "max-w-full break-words rounded border border-stroke-subsection px-2 py-0.5 text-left font-mono text-interface-labels-xs-normal text-base-blue-1100 hover:bg-surface-hover-l1-hover", children: n }, n))
2117
+ ] }),
2118
+ visible.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "mt-1 text-interface-labels-xs-light text-text-default-subdued", children: [
2119
+ "and ",
2120
+ visible.length - 1,
2121
+ " more ",
2122
+ visible.length === 2 ? "problem" : "problems"
2123
+ ] })
2124
+ ] })
2125
+ ] })
2126
+ ] }) });
2127
+ }
2128
+
2129
+ // src/react/Saved.jsx
2130
+ var import_react4 = require("react");
2131
+ var import_react5 = require("@phosphor-icons/react");
2132
+ var import_jsx_runtime3 = require("react/jsx-runtime");
2133
+ var ICON = { width: 13, height: 13, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true };
2134
+ var PIN = "M9 3h6l-1 6 4 4H6l4-4zM12 13v8";
2135
+ var FUNNEL = "M3 5h18l-7 8v6l-4 2v-8z";
2136
+ var BELL = "M6 16v-5a6 6 0 0 1 12 0v5l2 2H4zM10 21h4";
2137
+ var BOOKMARK = "M6 3h12v18l-6-4-6 4z";
2138
+ function QueryChip({ query, schema }) {
2139
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("code", { style: { fontSize: 11, lineHeight: "16px", paddingTop: 1, paddingBottom: 1 }, className: "flex w-fit max-w-full items-center gap-1 rounded border border-stroke-subsection bg-surface-default-underground px-1.5 font-mono text-text-default-regular", children: [
2140
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, width: 12, height: 12, className: "shrink-0 text-icon-default", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: FUNNEL }) }),
2141
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { "data-pqb-tip": query, "data-mono": "", "data-trunc": "", className: "min-w-0 truncate", children: paint(query.replace(/\s+/g, " ").trim(), schema) })
2142
+ ] });
2143
+ }
2144
+ function Saved({ saved, loading, schema, onPick, onPin, onDelete, onUpdate, onAlert, onSearch, onClose }) {
2145
+ const [q, setQ] = (0, import_react4.useState)("");
2146
+ const [editing, setEditing] = (0, import_react4.useState)(null);
2147
+ const [removing, setRemoving] = (0, import_react4.useState)(null);
2148
+ const ref = (0, import_react4.useRef)(null);
2149
+ const close = (0, import_react4.useRef)(onClose);
2150
+ close.current = onClose;
2151
+ (0, import_react4.useEffect)(() => {
2152
+ const out = (e) => {
2153
+ var _a;
2154
+ return !((_a = ref.current) == null ? void 0 : _a.contains(e.target)) && !e.target.closest("[data-pqb-saved]") && close.current();
2155
+ };
2156
+ document.addEventListener("mousedown", out, true);
2157
+ return () => document.removeEventListener("mousedown", out, true);
2158
+ }, []);
2159
+ const x = q.trim().toLowerCase();
2160
+ const hit = saved.filter((s) => !x || s.name.toLowerCase().includes(x) || s.query.toLowerCase().includes(x));
2161
+ const err = editing && editing.query.trim() ? parse(editing.query, schema).errors[0] : null;
2162
+ const nameTaken = editing && saved.some((s) => s.id !== editing.id && s.name === editing.name.trim());
2163
+ const submit = () => {
2164
+ if (!editing.name.trim() || !editing.query.trim() || err || nameTaken) return;
2165
+ onUpdate(saved.find((s) => s.id === editing.id), { name: editing.name.trim(), query: format(parse(editing.query, schema).ast) });
2166
+ setEditing(null);
2167
+ };
2168
+ const act = "grid h-6 w-6 place-items-center rounded text-text-default-subtle hover:bg-surface-default-l1 hover:text-text-default-regular";
2169
+ const item = (s) => removing === s.id ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { onKeyDown: (e) => e.key === "Escape" && (e.stopPropagation(), setRemoving(null)), className: "flex items-center gap-1 bg-surface-hover-l1-hover px-2.5 py-1.5", children: [
2170
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "min-w-0 flex-1 truncate text-interface-body-s-heavy text-text-default-regular", children: [
2171
+ "Delete \u201C",
2172
+ s.name,
2173
+ "\u201D?"
2174
+ ] }),
2175
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { onClick: () => (onDelete(s), setRemoving(null)), className: "h-6 rounded px-2 text-interface-labels-xs-normal font-semibold text-text-color-red hover:bg-surface-default-l1", children: "Delete" }),
2176
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { autoFocus: true, onClick: () => setRemoving(null), className: "h-6 rounded border border-stroke-subsection bg-surface-default-l1 px-2 text-interface-labels-xs-normal font-semibold text-text-default-regular", children: "Cancel" })
2177
+ ] }, s.id) : (editing == null ? void 0 : editing.id) === s.id ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
2178
+ "div",
2179
+ {
2180
+ onKeyDown: (e) => {
2181
+ if (e.key === "Escape") e.stopPropagation(), setEditing(null);
2182
+ else if (e.key === "Enter" && !e.shiftKey && e.target.tagName !== "BUTTON") e.preventDefault(), submit();
2183
+ },
2184
+ className: "flex flex-col gap-1.5 bg-surface-hover-l1-hover px-2.5 py-1.5",
2185
+ children: [
2186
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("input", { autoFocus: true, "aria-label": "Name", value: editing.name, onFocus: (e) => e.target.select(), onChange: (e) => setEditing({ ...editing, name: e.target.value }), className: "rounded border border-stroke-subsection bg-surface-default-l1 px-1.5 py-1 text-interface-body-s-heavy text-text-default-regular outline-none focus:border-stroke-active" }),
2187
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("textarea", { "aria-label": "Query", rows: 3, spellCheck: false, value: editing.query, onChange: (e) => setEditing({ ...editing, query: e.target.value }), style: { fontSize: 11, lineHeight: "16px" }, className: "resize-none rounded border border-stroke-subsection bg-surface-default-l1 px-1.5 py-1 font-mono text-text-default-regular outline-none focus:border-stroke-active" }),
2188
+ err && (() => {
2189
+ const t = editing.query.replace(/\n/g, " ");
2190
+ const from = Math.min(err.s, err.at ?? err.s);
2191
+ const to = Math.max(err.e, err.at ?? err.e);
2192
+ const lo = Math.max(0, from - 30);
2193
+ const hi = Math.min(t.length, to + 30);
2194
+ const fixes = [...[].concat(err.fix || []), ...(err.near || []).map((n) => ({ s: err.s, e: err.e, text: n, label: n, plain: true }))];
2195
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex flex-col gap-1", children: [
2196
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "text-interface-labels-xs-normal text-text-color-red", children: err.msg }),
2197
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("code", { style: { fontSize: 11, lineHeight: "16px" }, className: "whitespace-pre-wrap break-all rounded border border-stroke-subsection bg-surface-default-l1 px-1.5 py-0.5 font-mono text-text-default-subdued", children: [
2198
+ lo > 0 && "\u2026",
2199
+ t.slice(lo, from),
2200
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "rounded-sm bg-base-red-100 text-text-color-red", children: [
2201
+ t.slice(from, err.s),
2202
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("b", { className: "font-semibold", children: t.slice(err.s, err.e) }),
2203
+ t.slice(err.e, to) || (from === to ? " " : "")
2204
+ ] }),
2205
+ t.slice(to, hi),
2206
+ hi < t.length && "\u2026"
2207
+ ] }),
2208
+ fixes.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex flex-wrap items-center gap-1", children: [
2209
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "mr-1 text-interface-labels-xs-light text-text-default-subdued", children: "Suggestions" }),
2210
+ fixes.map((f) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { onClick: () => setEditing({ ...editing, query: editing.query.slice(0, f.s) + f.text + editing.query.slice(f.e) }), style: { minHeight: 24 }, className: "max-w-full break-words rounded border border-stroke-subsection bg-surface-default-l1 px-2 py-0.5 text-left font-mono text-interface-labels-xs-normal text-base-blue-1100 hover:bg-surface-default-underground", children: f.plain ? f.label : `${f.verb || "Use"} ${f.label}` }, (f.verb || "") + f.label))
2211
+ ] })
2212
+ ] });
2213
+ })(),
2214
+ !err && nameTaken && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "text-interface-labels-xs-normal text-text-color-red", children: [
2215
+ "A saved query is already called ",
2216
+ editing.name.trim()
2217
+ ] }),
2218
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex justify-end gap-2", children: [
2219
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { onClick: () => setEditing(null), className: "h-6 rounded bg-surface-default-l1 px-2 text-interface-labels-xs-normal font-semibold text-text-default-regular hover:bg-surface-default-underground", children: "Cancel" }),
2220
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { disabled: !editing.name.trim() || !editing.query.trim() || !!err || nameTaken, onClick: submit, className: "h-6 rounded-md border border-stroke-active bg-surface-default-action px-2.5 text-interface-labels-xs-normal font-semibold text-text-default-static hover:bg-surface-default-action-hover disabled:cursor-not-allowed disabled:opacity-50", children: "Save" })
2221
+ ] })
2222
+ ]
2223
+ },
2224
+ s.id
2225
+ ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "group flex items-start gap-2 px-2.5 py-1.5 hover:bg-surface-hover-l1-hover", children: [
2226
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("button", { onClick: () => onPick(s), style: { gap: 3 }, className: "flex min-w-0 flex-1 flex-col text-left", children: [
2227
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { "data-pqb-tip": s.name, "data-trunc": "", className: "max-w-full truncate text-interface-body-s-heavy text-text-default-regular", children: s.name }),
2228
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(QueryChip, { query: s.query, schema })
2229
+ ] }),
2230
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "grid shrink-0 self-center", children: [
2231
+ s.pinned && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, width: 14, height: 14, role: "img", "aria-label": "Pinned", style: { gridArea: "1 / 1", justifySelf: "end", marginRight: 5 }, className: "text-text-color-blue group-hover:hidden", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: PIN, fill: "currentColor" }) }),
2232
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { style: { gridArea: "1 / 1" }, className: "hidden gap-0.5 group-hover:flex", children: [
2233
+ onPin && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { "aria-label": s.pinned ? `Unpin ${s.name}` : `Pin ${s.name}`, "data-pqb-tip": s.pinned ? "Unpin" : "Pin", onClick: () => onPin(s, !s.pinned), className: act, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: s.pinned ? PIN + "M4 4l16 16" : PIN }) }) }),
2234
+ onAlert && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { "aria-label": `Create an alert from ${s.name}`, "data-pqb-tip": "Create alert", onClick: () => onAlert(s.query), className: act, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: BELL }) }) }),
2235
+ onUpdate && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { "aria-label": `Edit ${s.name}`, "data-pqb-tip": "Edit", onClick: () => (setRemoving(null), setEditing({ id: s.id, name: s.name, query: s.query })), className: act, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: "M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4" }) }) }),
2236
+ onDelete && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { "aria-label": `Delete ${s.name}`, "data-pqb-tip": "Delete", onClick: () => (setEditing(null), setRemoving(s.id)), className: `${act} hover:text-text-color-red`, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("svg", { ...ICON, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: "M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3" }) }) })
2237
+ ] })
2238
+ ] })
2239
+ ] }, s.id);
2240
+ const pinned = hit.filter((s) => s.pinned);
2241
+ const rest = hit.filter((s) => !s.pinned);
2242
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { ref, className: "absolute right-0 top-9 z-50 flex w-[380px] flex-col rounded-md border border-stroke-subsection bg-surface-default-l1 shadow-e300", children: [
2243
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex h-9 items-center gap-1.5 border-b border-stroke-subsection px-3", children: [
2244
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react5.MagnifyingGlass, { size: 14, className: "shrink-0 text-icon-default" }),
2245
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2246
+ "input",
2247
+ {
2248
+ autoFocus: true,
2249
+ value: q,
2250
+ onChange: (e) => {
2251
+ setQ(e.target.value);
2252
+ onSearch == null ? void 0 : onSearch(e.target.value);
2253
+ },
2254
+ onKeyDown: (e) => {
2255
+ if (e.key === "Escape") onClose();
2256
+ else if (e.key === "Enter" && hit[0]) onPick(hit[0]);
2257
+ },
2258
+ placeholder: "Search saved queries",
2259
+ className: "min-w-0 flex-1 bg-transparent text-interface-body-s-normal text-text-default-regular outline-none placeholder:text-text-default-disabled"
2260
+ }
2261
+ )
2262
+ ] }),
2263
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: { maxHeight: "min(520px, 70vh)" }, className: "overflow-y-auto no-scrollbar py-1", children: [
2264
+ loading && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "px-3 py-3 text-interface-body-s-light text-text-default-subdued", children: "Loading saved queries" }),
2265
+ pinned.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
2266
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "px-2.5 pb-0.5 pt-1 text-interface-titles-caption text-text-default-subdued", children: "PINNED" }),
2267
+ pinned.map(item)
2268
+ ] }),
2269
+ rest.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: pinned.length ? "mt-1 border-t border-stroke-subsection pt-1" : "", children: [
2270
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "px-2.5 pb-0.5 pt-1 text-interface-titles-caption text-text-default-subdued", children: "ALL SAVED" }),
2271
+ rest.map(item)
2272
+ ] }),
2273
+ !loading && !hit.length && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "px-3 py-5 text-center text-interface-body-s-light text-text-default-subdued", children: q ? "No saved queries match." : "No saved queries yet. Type a filter and press Save." })
2274
+ ] })
2275
+ ] });
2276
+ }
2277
+
2278
+ // src/react/PostgresQueryBox.jsx
2279
+ var import_jsx_runtime4 = require("react/jsx-runtime");
2280
+ var PostgresQueryBox = (0, import_react6.forwardRef)(function PostgresQueryBox2({
2281
+ schema,
2282
+ value,
2283
+ defaultValue = "",
2284
+ onChange,
2285
+ onRun,
2286
+ placeholder = 'Filter calls, e.g. data.request.verb == "GET" AND data.response.statusCode >= 500',
2287
+ runLabel = "Run query",
2288
+ tools,
2289
+ saved,
2290
+ savedCount,
2291
+ savedLoading,
2292
+ onSelectSaved,
2293
+ onPinSaved,
2294
+ onSaveQuery,
2295
+ onDeleteSaved,
2296
+ onUpdateSaved,
2297
+ onSavedSearch,
2298
+ onCreateAlert,
2299
+ className = ""
2300
+ }, ref) {
2301
+ const root = (0, import_react6.useRef)(null);
2302
+ const runRef = (0, import_react6.useRef)(null);
2303
+ const [own, setOwn] = (0, import_react6.useState)(defaultValue);
2304
+ const text = value ?? own;
2305
+ const setText = (t) => {
2306
+ if (value === void 0) setOwn(t);
2307
+ onChange == null ? void 0 : onChange(t);
2308
+ };
2309
+ const [runErrors, setRunErrors] = (0, import_react6.useState)(false);
2310
+ const [adv, setAdvState] = (0, import_react6.useState)(false);
2311
+ const [panel, setPanelState] = (0, import_react6.useState)(false);
2312
+ const setAdv = (v) => {
2313
+ setAdvState(v);
2314
+ if (v) setPanelState(false);
2315
+ };
2316
+ const setPanel = (v) => {
2317
+ setPanelState(v);
2318
+ if (v) setAdvState(false);
2319
+ };
2320
+ const parsed = text.trim() ? parse(text, schema) : null;
2321
+ const valid = !!parsed && !parsed.errors.length;
2322
+ const clean = valid ? format(parsed.ast) : "";
2323
+ const match = onUpdateSaved && (saved == null ? void 0 : saved.find((s) => s.query === clean));
2324
+ const [draft, setDraft] = (0, import_react6.useState)(null);
2325
+ const popRef = (0, import_react6.useRef)(null);
2326
+ const taken = draft && (saved == null ? void 0 : saved.some((s) => s.id !== (match == null ? void 0 : match.id) && s.name === draft.name.trim()));
2327
+ (0, import_react6.useEffect)(() => {
2328
+ if (!draft) return;
2329
+ const out = (e) => {
2330
+ var _a;
2331
+ return !((_a = popRef.current) == null ? void 0 : _a.contains(e.target)) && setDraft(null);
2332
+ };
2333
+ document.addEventListener("mousedown", out);
2334
+ return () => document.removeEventListener("mousedown", out);
2335
+ }, [!draft]);
2336
+ const submitDraft = () => {
2337
+ if (!draft.name.trim() || taken) return;
2338
+ if (match) onUpdateSaved(match, { name: draft.name.trim(), pinned: draft.pinned });
2339
+ else onSaveQuery({ name: draft.name.trim(), query: clean, pinned: draft.pinned });
2340
+ setDraft(null);
2341
+ };
2342
+ const openAlert = (q) => {
2343
+ var _a, _b;
2344
+ (_b = (_a = root.current) == null ? void 0 : _a.querySelector("textarea")) == null ? void 0 : _b.blur();
2345
+ setPanel(false);
2346
+ const p = parse(q, schema);
2347
+ onCreateAlert(format(p.ast), p.ast);
2348
+ };
2349
+ (0, import_react6.useImperativeHandle)(ref, () => ({
2350
+ focus: () => {
2351
+ var _a, _b;
2352
+ return (_b = (_a = root.current) == null ? void 0 : _a.querySelector("textarea")) == null ? void 0 : _b.focus();
2353
+ },
2354
+ run: () => {
2355
+ var _a;
2356
+ return (_a = runRef.current) == null ? void 0 : _a.call(runRef);
2357
+ },
2358
+ setText,
2359
+ getText: () => text
2360
+ }));
2361
+ const pick = (s) => {
2362
+ var _a;
2363
+ onSelectSaved == null ? void 0 : onSelectSaved(s);
2364
+ setPanel(false);
2365
+ const p = parse(s.query, schema);
2366
+ const clean2 = p.errors.length ? s.query : format(p.ast);
2367
+ setText(clean2);
2368
+ (_a = runRef.current) == null ? void 0 : _a.call(runRef, clean2);
2369
+ };
2370
+ const extra = tools || saved ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
2371
+ tools,
2372
+ saved && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("span", { className: "relative", children: [
2373
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("button", { "data-pqb-saved": "", onMouseDown: (e) => e.preventDefault(), onClick: () => setPanel(!panel), "aria-expanded": panel, "data-pqb-tip": "Saved queries", className: `flex h-6 items-center gap-1.5 rounded px-1.5 hover:bg-surface-hover-l1-hover ${panel ? "bg-surface-hover-l1-hover" : ""}`, children: [
2374
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react7.BookmarksSimple, { size: 14, className: "shrink-0 text-icon-default" }),
2375
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "min-w-0 max-w-[200px] truncate text-interface-body-s-heavy text-text-default-regular", children: "Queries" }),
2376
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "rounded-full bg-surface-hover-l1-hover px-1.5 text-interface-labels-xxs-normal text-text-default-subdued", children: savedCount ?? saved.length }),
2377
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react7.CaretDown, { size: 12, className: "shrink-0 text-text-default-subtle" })
2378
+ ] }),
2379
+ panel && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Saved, { saved, loading: savedLoading, schema, onPick: pick, onPin: onPinSaved, onDelete: onDeleteSaved, onUpdate: onUpdateSaved, onAlert: onCreateAlert && openAlert, onSearch: onSavedSearch, onClose: () => setPanel(false) })
2380
+ ] })
2381
+ ] }) : null;
2382
+ const actions = [
2383
+ onSaveQuery && ["Save", BOOKMARK, (e) => {
2384
+ const r = e.currentTarget.getBoundingClientRect();
2385
+ setPanel(false);
2386
+ setDraft({ name: (match == null ? void 0 : match.name) ?? text.replace(/\b(?:data|metadata)\.[\w.-]+/g, (x) => x.split(".").pop()).replace(/\s+/g, " ").trim().slice(0, 60), pinned: !!(match == null ? void 0 : match.pinned), top: r.bottom + 6, left: Math.max(8, r.right - 280) });
2387
+ }],
2388
+ onCreateAlert && ["Create alert", BELL, () => openAlert(text)]
2389
+ ].filter(Boolean);
2390
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { ref: root, className: `pqb ${className}`, children: [
2391
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "flex min-w-0 items-start gap-2", children: [
2392
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(QueryBox, { text, setText, schema, onRun, tools: extra, actions: actions.length > 0 && actions.map(([label, d, go]) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("button", { disabled: !valid, onMouseDown: (e) => e.preventDefault(), onClick: go, className: "flex h-6 items-center gap-1.5 rounded px-1.5 text-left hover:bg-surface-hover-l1-hover disabled:cursor-not-allowed disabled:opacity-50", children: [
2393
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("svg", { ...ICON, width: 14, height: 14, className: "shrink-0 text-icon-default", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("path", { d }) }),
2394
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "whitespace-nowrap text-interface-body-s-normal text-text-default-regular", children: label })
2395
+ ] }, label)), runErrors, setRunErrors, runRef, adv, setAdv, placeholder }),
2396
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("button", { onClick: () => {
2397
+ var _a;
2398
+ return (_a = runRef.current) == null ? void 0 : _a.call(runRef);
2399
+ }, className: "flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-stroke-active bg-surface-default-action px-3 hover:bg-surface-default-action-hover", children: [
2400
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react7.Play, { size: 14, weight: "fill", className: "text-text-default-static" }),
2401
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "whitespace-nowrap text-interface-labels-xs-normal font-semibold text-text-default-static", children: runLabel })
2402
+ ] })
2403
+ ] }),
2404
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Tips, { root }),
2405
+ draft && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
2406
+ "div",
2407
+ {
2408
+ ref: popRef,
2409
+ role: "dialog",
2410
+ "aria-label": "Save query as",
2411
+ onKeyDown: (e) => {
2412
+ if (e.key === "Escape") setDraft(null);
2413
+ else if (e.key === "Enter" && e.target.tagName !== "BUTTON") e.preventDefault(), submitDraft();
2414
+ },
2415
+ style: { position: "fixed", top: draft.top, left: draft.left, width: 280, zIndex: 60 },
2416
+ className: "flex flex-col gap-2 rounded-md border border-stroke-subsection bg-surface-default-l1 p-3 shadow-e300",
2417
+ children: [
2418
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "text-interface-body-s-heavy text-text-default-regular", children: "Save query as" }),
2419
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { autoFocus: true, "aria-label": "Name", value: draft.name, onFocus: (e) => e.target.select(), onChange: (e) => setDraft({ ...draft, name: e.target.value }), className: "rounded-md border border-stroke-subsection bg-surface-default-underground px-2 py-1.5 text-interface-body-s-normal font-medium text-text-default-regular outline-none focus:border-stroke-active" }),
2420
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { className: "flex cursor-pointer items-center gap-1.5 text-interface-labels-xs-normal font-medium text-text-default-subdued", children: [
2421
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "checkbox", checked: draft.pinned, onChange: (e) => setDraft({ ...draft, pinned: e.target.checked }), style: { width: 14, height: 14, margin: 0, accentColor: "var(--color-stroke-active)" } }),
2422
+ "Pin to the top of Queries"
2423
+ ] }),
2424
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(QueryChip, { query: clean, schema }),
2425
+ taken && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("p", { className: "text-interface-labels-xs-normal text-text-color-red", children: [
2426
+ "A saved query is already called ",
2427
+ draft.name.trim()
2428
+ ] }),
2429
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "flex justify-end gap-2", children: [
2430
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { onClick: () => setDraft(null), className: "h-6 rounded px-2 text-interface-labels-xs-normal font-semibold text-text-default-regular hover:bg-surface-hover-l1-hover", children: "Cancel" }),
2431
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { disabled: !draft.name.trim() || taken, onClick: submitDraft, className: "h-6 rounded-md border border-stroke-active bg-surface-default-action px-2.5 text-interface-labels-xs-normal font-semibold text-text-default-static hover:bg-surface-default-action-hover disabled:cursor-not-allowed disabled:opacity-50", children: match ? "Update" : "Save" })
2432
+ ] })
2433
+ ]
2434
+ }
2435
+ )
2436
+ ] });
2437
+ });
2438
+ var PostgresQueryBox_default = PostgresQueryBox;
2439
+
2440
+ // src/core/sql.js
2441
+ var OCT = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
2442
+ var V4 = `(${OCT}\\.){3}${OCT}`;
2443
+ var H = "[0-9a-f]{1,4}";
2444
+ var V6 = [
2445
+ `(${H}:){7}${H}`,
2446
+ `(${H}:){1,7}:`,
2447
+ `(${H}:){1,6}:${H}`,
2448
+ `(${H}:){1,5}(:${H}){1,2}`,
2449
+ `(${H}:){1,4}(:${H}){1,3}`,
2450
+ `(${H}:){1,3}(:${H}){1,4}`,
2451
+ `(${H}:){1,2}(:${H}){1,5}`,
2452
+ `${H}:(:${H}){1,6}`,
2453
+ `:((:${H}){1,7}|:)`,
2454
+ `(${H}:){6}${V4}`,
2455
+ `(${H}:){1,5}:${V4}`,
2456
+ `::(${H}:){0,5}${V4}`
2457
+ ];
2458
+ var IP_RE = `^(${V4}|${V6.join("|")})$`;
2459
+ var NUM_RE = "^-?\\d+(\\.\\d+)?$";
2460
+ var SQL_OP = { "==": "=", "!=": "<>", "<": "<", "<=": "<=", ">": ">", ">=": ">=" };
2461
+ var str = (s) => {
2462
+ if (s.includes("\0")) throw new Error("Text values cannot contain a NUL character");
2463
+ return "'" + s.replace(/'/g, "''") + "'";
2464
+ };
2465
+ function toSql(ast, schema) {
2466
+ const segs = (field) => {
2467
+ var _a, _b;
2468
+ return ((_b = (_a = schema == null ? void 0 : schema.byPath) == null ? void 0 : _a[field]) == null ? void 0 : _b.segs) || field.split(".");
2469
+ };
2470
+ const path = (field, last2) => {
2471
+ const s = segs(field).map(str);
2472
+ return `data${s.slice(0, -1).map((k) => `->${k}`).join("")}${last2}${s[s.length - 1]}`;
2473
+ };
2474
+ const json = (field) => `NULLIF(${path(field, "->")},'null'::jsonb)`;
2475
+ const text = (field) => path(field, "->>");
2476
+ const num = (field) => {
2477
+ if (field === "@latency") {
2478
+ const a = path(LAT_A, "->");
2479
+ const b = path(LAT_B, "->");
2480
+ return `(CASE WHEN jsonb_typeof(${a}) = 'number' AND jsonb_typeof(${b}) = 'number' THEN (${a})::numeric - (${b})::numeric END)`;
2481
+ }
2482
+ const t = text(field);
2483
+ return `(CASE WHEN ${t} ~ '${NUM_RE}' THEN (${t})::numeric END)`;
2484
+ };
2485
+ const numLit = (x) => /^-?\d+(\.\d+)?$/.test(x.raw) ? x.raw : String(Number(x.v));
2486
+ const jv = (x) => `to_jsonb(${typeof x.v === "string" ? str(x.v) + "::text" : typeof x.v === "boolean" ? String(x.v) : numLit(x)})`;
2487
+ const ipCond = (field, vals) => {
2488
+ const t = text(field);
2489
+ const v = `(${t})::inet`;
2490
+ const m = `(CASE WHEN ${v}<<='::ffff:0.0.0.0/96' THEN '0.0.0.0'::inet+(${v}-'::ffff:0.0.0.0'::inet) ELSE ${v} END)`;
2491
+ const nets = vals.filter((x) => !x.includes("-"));
2492
+ const tests = vals.filter((x) => x.includes("-")).map((x) => `${m} BETWEEN ${str(x.split("-")[0])}::inet AND ${str(x.split("-")[1])}::inet`);
2493
+ if (nets.length) tests.unshift(`${m}<<=ANY(ARRAY[${nets.map(str).join(",")}]::inet[])`);
2494
+ return `(CASE WHEN ${t}~*'${IP_RE}' THEN ${tests.join(" OR ")} END)`;
2495
+ };
2496
+ const cond = (n) => {
2497
+ const { field, op } = n;
2498
+ if (op === "PRESENT") return `${text(field)} IS NOT NULL`;
2499
+ if (op === "ABSENT") return `${text(field)} IS NULL`;
2500
+ if (op === "BETWEEN") return `${num(field)} BETWEEN ${numLit(n.lo)} AND ${numLit(n.hi)}`;
2501
+ if (op === "ANYONE" || op === "NONEOF") return `${json(field)} ${op === "NONEOF" ? "NOT IN" : "IN"} (${n.vals.map(jv).join(", ")})`;
2502
+ if (op.startsWith("IP")) return `${op === "IP NOT_IN_RANGE" ? "NOT " : ""}${ipCond(field, n.vals.map((x) => x.v))}`;
2503
+ const v = n.val.v;
2504
+ if (op === "CONTAINS") return `strpos(${text(field)}, ${str(v)}) > 0`;
2505
+ if (op === "NOT CONTAINS") return `strpos(${text(field)}, ${str(v)}) = 0`;
2506
+ if (op.includes("~")) return `${text(field)} ${op} ${str(v)}`;
2507
+ if (op === "==" || op === "!=") return `${json(field)} ${SQL_OP[op]} ${jv(n.val)}`;
2508
+ return `${num(field)} ${SQL_OP[op]} ${numLit(n.val)}`;
2509
+ };
2510
+ const one = (n) => {
2511
+ if (n.k === "cond") return cond(n);
2512
+ if (n.k === "group") return `(${one(n.x)})`;
2513
+ if (n.k === "not") return `NOT (${one(n.x)})`;
2514
+ return n.items.map(one).join(` ${n.k.toUpperCase()} `);
2515
+ };
2516
+ if (!ast) return { where: "", count: null };
2517
+ const items = ast.k === "and" ? ast.items : [ast];
2518
+ const last = items[items.length - 1];
2519
+ const c = last.k === "count" ? last : null;
2520
+ const rest = c ? items.slice(0, -1) : items;
2521
+ const where = rest.length ? `(${one(rest.length === 1 ? rest[0] : { k: "and", items: rest })})` : "";
2522
+ const count = c && { op: SQL_OP[c.op], value: c.n, window: c.ms || 0, by: c.by ? segs(c.by) : null };
2523
+ return { where, count };
2524
+ }
2525
+
2526
+ // src/core/index.js
2527
+ var validate = (text, schema) => {
2528
+ var _a;
2529
+ return text.trim() ? ((_a = parse(text, schema).errors[0]) == null ? void 0 : _a.msg) || "" : "";
2530
+ };
2531
+ // Annotate the CommonJS export names for ESM import in node:
2532
+ 0 && (module.exports = {
2533
+ LATENCY,
2534
+ LAT_FIELD,
2535
+ METHODS,
2536
+ OP_INFO,
2537
+ PostgresQueryBox,
2538
+ STATUS_CODES,
2539
+ TYPE_LABEL,
2540
+ buildSchema,
2541
+ context,
2542
+ evaluate,
2543
+ format,
2544
+ fromTree,
2545
+ ipToBig,
2546
+ opsFor,
2547
+ parse,
2548
+ parseRange,
2549
+ schemaFromFields,
2550
+ toSql,
2551
+ toTree,
2552
+ tokenize,
2553
+ validate
2554
+ });
2555
+ //# sourceMappingURL=index.cjs.map