@elaraai/east 1.0.104 → 1.0.105

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.
Files changed (62) hide show
  1. package/dist/src/compile/builtins/primitives.d.ts +1 -1
  2. package/dist/src/compile/control.d.ts.map +1 -1
  3. package/dist/src/compile/control.js +10 -5
  4. package/dist/src/compile/control.js.map +1 -1
  5. package/dist/src/compile.open_beast.spec.js +7 -3
  6. package/dist/src/compile.open_beast.spec.js.map +1 -1
  7. package/dist/src/query/jq/narrow.d.ts +68 -0
  8. package/dist/src/query/jq/narrow.d.ts.map +1 -0
  9. package/dist/src/query/jq/narrow.js +691 -0
  10. package/dist/src/query/jq/narrow.js.map +1 -0
  11. package/dist/src/query/jq/split.d.ts +35 -11
  12. package/dist/src/query/jq/split.d.ts.map +1 -1
  13. package/dist/src/query/jq/split.js +205 -35
  14. package/dist/src/query/jq/split.js.map +1 -1
  15. package/dist/src/query/jq/translate-builtins.d.ts.map +1 -1
  16. package/dist/src/query/jq/translate-builtins.js +43 -8
  17. package/dist/src/query/jq/translate-builtins.js.map +1 -1
  18. package/dist/src/query/jq/translate.d.ts +55 -4
  19. package/dist/src/query/jq/translate.d.ts.map +1 -1
  20. package/dist/src/query/jq/translate.js +174 -21
  21. package/dist/src/query/jq/translate.js.map +1 -1
  22. package/dist/src/runner_exec.d.ts +10 -0
  23. package/dist/src/runner_exec.d.ts.map +1 -1
  24. package/dist/src/runner_exec.js +11 -3
  25. package/dist/src/runner_exec.js.map +1 -1
  26. package/dist/src/runner_exec.spec.js +40 -2
  27. package/dist/src/runner_exec.spec.js.map +1 -1
  28. package/dist/src/serialization/beast2/index.d.ts +2 -1
  29. package/dist/src/serialization/beast2/index.d.ts.map +1 -1
  30. package/dist/src/serialization/beast2/index.js +2 -1
  31. package/dist/src/serialization/beast2/index.js.map +1 -1
  32. package/dist/src/serialization/beast2/v5/codec.d.ts +30 -1
  33. package/dist/src/serialization/beast2/v5/codec.d.ts.map +1 -1
  34. package/dist/src/serialization/beast2/v5/codec.js +24 -3
  35. package/dist/src/serialization/beast2/v5/codec.js.map +1 -1
  36. package/dist/src/serialization/beast2/v5/lazy.d.ts +23 -4
  37. package/dist/src/serialization/beast2/v5/lazy.d.ts.map +1 -1
  38. package/dist/src/serialization/beast2/v5/lazy.js +84 -19
  39. package/dist/src/serialization/beast2/v5/lazy.js.map +1 -1
  40. package/dist/src/serialization/beast2/v5/project.d.ts +156 -0
  41. package/dist/src/serialization/beast2/v5/project.d.ts.map +1 -0
  42. package/dist/src/serialization/beast2/v5/project.js +830 -0
  43. package/dist/src/serialization/beast2/v5/project.js.map +1 -0
  44. package/dist/src/serialization/beast2/v5/project.spec.d.ts +6 -0
  45. package/dist/src/serialization/beast2/v5/project.spec.d.ts.map +1 -0
  46. package/dist/src/serialization/beast2/v5/project.spec.js +273 -0
  47. package/dist/src/serialization/beast2/v5/project.spec.js.map +1 -0
  48. package/dist/src/serialization/beast2/v5/runs.d.ts +78 -7
  49. package/dist/src/serialization/beast2/v5/runs.d.ts.map +1 -1
  50. package/dist/src/serialization/beast2/v5/runs.js +218 -7
  51. package/dist/src/serialization/beast2/v5/runs.js.map +1 -1
  52. package/dist/src/serialization/beast2/v5/runs.spec.js +223 -6
  53. package/dist/src/serialization/beast2/v5/runs.spec.js.map +1 -1
  54. package/dist/src/serialization/beast2/v5/stream.d.ts +30 -2
  55. package/dist/src/serialization/beast2/v5/stream.d.ts.map +1 -1
  56. package/dist/src/serialization/beast2/v5/stream.js +30 -5
  57. package/dist/src/serialization/beast2/v5/stream.js.map +1 -1
  58. package/dist/src/serialization/index.d.ts +1 -1
  59. package/dist/src/serialization/index.d.ts.map +1 -1
  60. package/dist/src/serialization/index.js +1 -1
  61. package/dist/src/serialization/index.js.map +1 -1
  62. package/package.json +1 -1
@@ -0,0 +1,691 @@
1
+ /**
2
+ * Copyright (c) 2025 Elara AI Pty Ltd
3
+ * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.
4
+ */
5
+ /**
6
+ * A query's rows narrowed to the fields its later steps read (#1141).
7
+ *
8
+ * A stage that builds each row, `map(. + {region: …})`, gives it every field
9
+ * of the row it came from, and one that keeps each row, `map(select(…))`, keeps
10
+ * the dataset's row whole, though the steps after either may read two fields.
11
+ * The translator and the split planner run the program {@link narrowRows}
12
+ * gives them: the checked program, with each such row built of the fields read
13
+ * after it, checked again.
14
+ *
15
+ * - An object a step builds, `{a: f, b: g}` or `. + {c: h}`, keeps the fields
16
+ * the steps after it read. A field none reads is left out where making it
17
+ * can neither raise nor give other than one value, so no answer changes:
18
+ * `{a: .x, b: (.y / .z)} | .a` keeps `b`, whose division may raise.
19
+ * - A stage over a dataset's rows that passes them on, `map(select(p))`, ends
20
+ * by building each row of the fields read after it: `map(select(p) | {id,
21
+ * total})`. A row built of what it reads is what the paged loops of #1112
22
+ * decode a dataset's rows to, and what a piece keeps and sends on.
23
+ * - A value read whole — reaching the output, `keys`, `tojson`, `length` of
24
+ * an object, `==`, a variable bound to it, anything not understood here — is
25
+ * built whole, and so is every value in a `try`'s body, where the checker
26
+ * lets a value of the wrong kind by, to raise; a program with a `def` is
27
+ * left as written.
28
+ *
29
+ * The narrowed program is checked again over the program's text, each node at
30
+ * the range of the text it came from, so a runtime error and an explanation
31
+ * name the query as written; where it does not check to the same output type,
32
+ * multiplicity and reads, the program runs as written.
33
+ *
34
+ * @packageDocumentation
35
+ */
36
+ import { none, some, variant } from "../../containers/variant.js";
37
+ import { isTypeEqual } from "../../types.js";
38
+ import { checkJq } from "./check.js";
39
+ import { unwrap } from "./shapes.js";
40
+ import { childPath, jqChildren, jqPatternChildren } from "./spans.js";
41
+ // ─── What a step leaves unmade ─────────────────────────────────────────────
42
+ /**
43
+ * Builtins that raise for nothing the checker lets reach them, by name and
44
+ * arity: given arguments that never raise, they never raise. The checker
45
+ * refuses a value of a kind a builtin cannot take, outside a lenient place,
46
+ * so what is left to raise at run time is a value's own: a zero divisor, a
47
+ * string that is no number, a count below zero, `error`.
48
+ */
49
+ const NEVER_RAISE = new Set([
50
+ "select/1", "not/0", "length/0", "utf8bytelength/0", "type/0", "tostring/0", "tojson/0", "empty/0", "keys/0", "keys_unsorted/0",
51
+ "has/1", "in/1", "contains/1", "inside/1", "startswith/1", "endswith/1", "ltrimstr/1", "rtrimstr/1", "ascii_downcase/0", "ascii_upcase/0",
52
+ "floor/0", "ceil/0", "round/0", "fabs/0", "sqrt/0", "abs/0", "values/0", "nulls/0", "numbers/0", "strings/0", "booleans/0", "arrays/0",
53
+ "objects/0", "iterables/0", "scalars/0", "map/1", "add/0", "any/0", "all/0", "min/0", "max/0",
54
+ ]);
55
+ /**
56
+ * Whether a filter never raises, whatever its input: what a step may leave
57
+ * unmade, a stage's rows past the ones a step needs (#1140) or a field no step
58
+ * reads (#1141), since a value that raises makes the whole query raise.
59
+ * Conservative: paths, literals, comparisons, `and`, `or`, `+`, `-` and `*`,
60
+ * objects, arrays, strings, `if`, `//`, `try`, a `label` and a `break` to it,
61
+ * and the builtins in {@link NEVER_RAISE}, of parts that never raise. `/` and
62
+ * `%` (a zero divisor), a `def` or a call of one, a function value, any other
63
+ * builtin, and a `break` out of the filter, which leaves it as a raise does,
64
+ * may raise.
65
+ *
66
+ * @param node - the filter
67
+ * @param defs - the defs in scope, by `name/arity`: a call of one may raise
68
+ * @param labels - the labels the filter is inside, which a `break` may leave
69
+ * @returns whether it never raises
70
+ *
71
+ * @internal
72
+ */
73
+ export function cannotRaise(node, defs, labels = new Set()) {
74
+ const all = (nodes) => nodes.every(n => cannotRaise(n, defs, labels));
75
+ switch (node.type) {
76
+ case "identity":
77
+ case "literal":
78
+ case "variable":
79
+ case "descend":
80
+ return true;
81
+ case "break": return labels.has(node.value);
82
+ case "field": return all([node.value.target]);
83
+ // An index or a bound jq may refuse for its value (`null`, a key of another kind) only when computed: a literal never is.
84
+ case "index": return node.value.index.type === "literal" && all([node.value.target]);
85
+ case "slice": {
86
+ const { from, target, to } = node.value;
87
+ return (from.type === "none" || from.value.type === "literal") && (to.type === "none" || to.value.type === "literal")
88
+ && all([target]);
89
+ }
90
+ case "iterate": return all([node.value.target]);
91
+ case "pipe":
92
+ case "comma":
93
+ case "alternative": return all([node.value.left, node.value.right]);
94
+ case "binary": return node.value.op !== "/" && node.value.op !== "%" && all([node.value.left, node.value.right]);
95
+ case "negate": return all([node.value]);
96
+ case "array": return node.value.type === "none" || all([node.value.value]);
97
+ // A computed key that is no string raises.
98
+ case "object":
99
+ return node.value.every(entry => entry.key.type !== "computed" && (entry.value.type === "none" || all([entry.value.value])));
100
+ case "string":
101
+ return node.value.every(part => part.type === "text" || all([part.value]));
102
+ case "if": {
103
+ const { branches, otherwise } = node.value;
104
+ return branches.every(b => all([b.condition, b.then])) && (otherwise.type === "none" || all([otherwise.value]));
105
+ }
106
+ // What `try` runs raises into its handler, which may raise; a `break` leaves it.
107
+ case "try": return !breaksOut(node.value.body, labels) && (node.value.catch.type === "none" || all([node.value.catch.value]));
108
+ case "label": return cannotRaise(node.value.body, defs, new Set(labels).add(node.value.name));
109
+ // A pattern that destructures may not match its value.
110
+ case "bind": return node.value.patterns.every(pattern => pattern.type === "variable") && all([node.value.source, node.value.body]);
111
+ case "call": {
112
+ const key = `${node.value.name}/${node.value.args.length}`;
113
+ return NEVER_RAISE.has(key) && !defs.has(key) && all(node.value.args);
114
+ }
115
+ default:
116
+ return false;
117
+ }
118
+ }
119
+ /** Whether a filter may `break` to a label it is not inside: leave itself, as a raise does. */
120
+ function breaksOut(node, labels) {
121
+ if (node.type === "break")
122
+ return !labels.has(node.value);
123
+ const inner = node.type === "label" ? new Set(labels).add(node.value.name) : labels;
124
+ return jqChildren(node).some(child => child.node !== undefined && breaksOut(child.node, inner));
125
+ }
126
+ const WHOLE = { kind: "whole" };
127
+ const NONE = { kind: "none" };
128
+ function fieldsOf(...names) {
129
+ return { kind: "fields", fields: new Set(names) };
130
+ }
131
+ function elementsOf(element) {
132
+ return { kind: "elements", element };
133
+ }
134
+ /** What two readers of one value read between them. */
135
+ function both(a, b) {
136
+ if (a.kind === "none")
137
+ return b;
138
+ if (b.kind === "none")
139
+ return a;
140
+ if (a.kind === "fields" && b.kind === "fields")
141
+ return { kind: "fields", fields: new Set([...a.fields, ...b.fields]) };
142
+ if (a.kind === "elements" && b.kind === "elements")
143
+ return elementsOf(both(a.element, b.element));
144
+ return WHOLE;
145
+ }
146
+ /** What is read of each element of an array read as `d` reads it. */
147
+ function elementOf(d) {
148
+ return d.kind === "elements" ? d.element : d.kind === "none" ? NONE : WHOLE;
149
+ }
150
+ /** Builtins of no arguments that give their input or nothing: a type's `select`. */
151
+ const PASS_THROUGH = new Set([
152
+ "values", "nulls", "booleans", "numbers", "strings", "arrays", "objects", "iterables", "scalars",
153
+ ]);
154
+ /** A filter's input as a step after the root reads it: a dataset's rows. */
155
+ function readsRootField(node) {
156
+ return node.type === "field" && node.value.target.type === "identity" && !node.value.optional;
157
+ }
158
+ /** Whether a filter's outputs are its input or none: `select(p)`, `.`, and pipes, commas and branches of them. */
159
+ function passesThrough(node) {
160
+ switch (node.type) {
161
+ case "identity": return true;
162
+ case "pipe":
163
+ case "comma": return passesThrough(node.value.left) && passesThrough(node.value.right);
164
+ case "if":
165
+ return node.value.branches.every(b => passesThrough(b.then))
166
+ && (node.value.otherwise.type === "none" || passesThrough(node.value.otherwise.value));
167
+ case "call":
168
+ return (node.value.name === "select" && node.value.args.length === 1) || (node.value.name === "empty" && node.value.args.length === 0)
169
+ || (node.value.args.length === 0 && PASS_THROUGH.has(node.value.name));
170
+ default: return false;
171
+ }
172
+ }
173
+ /** Whether a program defines a function anywhere: a call may then be of it, not of the builtin. */
174
+ function definesAny(node) {
175
+ return node.type === "def" || jqChildren(node).some(child => child.node !== undefined && definesAny(child.node));
176
+ }
177
+ /** A field `{name}` reads of its input, as an object's entry. */
178
+ function shorthand(name) {
179
+ return { key: variant("name", name), value: none };
180
+ }
181
+ /** The demand analysis and the rewrite over one checked program. */
182
+ class Narrower {
183
+ checked;
184
+ /** Each node the rewrite made, and the path of the node whose text it stands for. */
185
+ from = new Map();
186
+ /** What the steps after each node read of its outputs, by its path. */
187
+ demands = new Map();
188
+ /** Whether any node was rewritten. */
189
+ changed = false;
190
+ constructor(checked) {
191
+ this.checked = checked;
192
+ }
193
+ /** The type of a node's outputs, as the checker gave it. */
194
+ typeOf(path) {
195
+ return this.checked.typeAt(path)?.type;
196
+ }
197
+ /** Whether a node's input is an array. */
198
+ arrayInput(path) {
199
+ const shape = this.checked.inputAt(path, "");
200
+ return shape !== null && shape.kind === "type" && unwrap(shape.type).type === "Array";
201
+ }
202
+ /** Whether an entry's value may be left out: making it never raises, and gives exactly one value. */
203
+ droppable(value, path, place) {
204
+ if (place.lenient)
205
+ return false;
206
+ if (value === undefined)
207
+ return true;
208
+ return cannotRaise(value, new Set()) && this.checked.typeAt(path)?.multiplicity === "one";
209
+ }
210
+ /** A node made by the rewrite, standing for the node at `path`. */
211
+ made(node, path) {
212
+ this.from.set(node, path);
213
+ return node;
214
+ }
215
+ /** `node` with a new payload, where any of its children changed. */
216
+ remade(node, path, value, changed) {
217
+ return changed ? this.made(variant(node.type, value), path) : node;
218
+ }
219
+ /**
220
+ * Narrows a filter to what the steps after it read of its outputs.
221
+ *
222
+ * @param node - the filter
223
+ * @param path - its path
224
+ * @param out - what the steps after it read of each output
225
+ * @param place - where it is
226
+ * @returns the filter, rewritten where it builds fields none reads, and
227
+ * what it reads of its input
228
+ */
229
+ narrow(node, path, out, place) {
230
+ this.demands.set(path, out);
231
+ const at = (step) => childPath(path, step);
232
+ const keep = (reads) => ({ node, reads });
233
+ // Where a filter's input is not the root, nor a dataset's rows.
234
+ const inner = { lenient: place.lenient, root: false, rows: false };
235
+ switch (node.type) {
236
+ case "identity": return keep(out);
237
+ case "literal":
238
+ case "variable":
239
+ case "break": return keep(NONE);
240
+ case "field": {
241
+ const target = this.narrow(node.value.target, at("field.target"), fieldsOf(node.value.name), place);
242
+ return { node: this.remade(node, path, { ...node.value, target: target.node }, target.node !== node.value.target), reads: target.reads };
243
+ }
244
+ case "index": {
245
+ const { index, target } = node.value;
246
+ if (index.type === "literal" && index.value.type === "string") {
247
+ const t = this.narrow(target, at("index.target"), fieldsOf(index.value.value), place);
248
+ return { node: this.remade(node, path, { ...node.value, target: t.node }, t.node !== target), reads: t.reads };
249
+ }
250
+ const t = this.narrow(target, at("index.target"), elementsOf(out), place);
251
+ const i = this.narrow(index, at("index.index"), WHOLE, place);
252
+ return { node: this.remade(node, path, { ...node.value, index: i.node, target: t.node }, t.node !== target || i.node !== index), reads: both(t.reads, i.reads) };
253
+ }
254
+ case "slice": {
255
+ const { from, target, to } = node.value;
256
+ const t = this.narrow(target, at("slice.target"), out, place);
257
+ const f = from.type === "some" ? this.narrow(from.value, at("slice.from.some"), WHOLE, place) : undefined;
258
+ const e = to.type === "some" ? this.narrow(to.value, at("slice.to.some"), WHOLE, place) : undefined;
259
+ const changed = t.node !== target || (f !== undefined && f.node !== from.value) || (e !== undefined && e.node !== to.value);
260
+ const value = { ...node.value, from: f === undefined ? from : some(f.node), target: t.node, to: e === undefined ? to : some(e.node) };
261
+ return { node: this.remade(node, path, value, changed), reads: both(t.reads, both(f?.reads ?? NONE, e?.reads ?? NONE)) };
262
+ }
263
+ case "iterate": {
264
+ const type = this.typeOf(at("iterate.target"));
265
+ const array = type !== undefined && unwrap(type).type === "Array";
266
+ const t = this.narrow(node.value.target, at("iterate.target"), array ? elementsOf(out) : WHOLE, place);
267
+ return { node: this.remade(node, path, { ...node.value, target: t.node }, t.node !== node.value.target), reads: t.reads };
268
+ }
269
+ case "pipe": {
270
+ const { left, right } = node.value;
271
+ const r = this.narrow(right, at("pipe.right"), out, { lenient: place.lenient, root: false, rows: place.root && readsRootField(left) });
272
+ const l = this.narrow(left, at("pipe.left"), r.reads, place);
273
+ return { node: this.remade(node, path, { left: l.node, right: r.node }, l.node !== left || r.node !== right), reads: l.reads };
274
+ }
275
+ case "comma":
276
+ case "alternative": {
277
+ const { left, right } = node.value;
278
+ const l = this.narrow(left, at(`${node.type}.left`), out, place);
279
+ const r = this.narrow(right, at(`${node.type}.right`), out, place);
280
+ return { node: this.remade(node, path, { left: l.node, right: r.node }, l.node !== left || r.node !== right), reads: both(l.reads, r.reads) };
281
+ }
282
+ case "binary": {
283
+ const { left, op, right } = node.value;
284
+ if (op === "+" && left.type === "identity" && right.type === "object" && (out.kind === "fields" || out.kind === "none") && !place.lenient) {
285
+ const merged = this.merged(right, path, out, place);
286
+ if (merged !== undefined)
287
+ return merged;
288
+ }
289
+ const l = this.narrow(left, at("binary.left"), WHOLE, place);
290
+ const r = this.narrow(right, at("binary.right"), WHOLE, place);
291
+ return { node: this.remade(node, path, { left: l.node, op, right: r.node }, l.node !== left || r.node !== right), reads: both(l.reads, r.reads) };
292
+ }
293
+ case "negate": {
294
+ const v = this.narrow(node.value, at("negate"), WHOLE, place);
295
+ return { node: this.remade(node, path, v.node, v.node !== node.value), reads: v.reads };
296
+ }
297
+ case "array": {
298
+ if (node.value.type === "none")
299
+ return keep(NONE);
300
+ const body = node.value.value;
301
+ const element = elementOf(out);
302
+ const b = this.narrow(body, at("array.some"), element, { ...place, rows: false });
303
+ // `[.[] | f]` over a dataset's rows, as `map(f)` is.
304
+ let made = b.node;
305
+ if (place.rows && made.type === "pipe" && made.value.left.type === "iterate" && made.value.left.value.target.type === "identity") {
306
+ const f = this.project(made.value.right, at("array.some.pipe.right"), element, place);
307
+ if (f !== undefined)
308
+ made = this.made(variant("pipe", { left: made.value.left, right: f }), at("array.some"));
309
+ }
310
+ return { node: this.remade(node, path, some(made), made !== body), reads: b.reads };
311
+ }
312
+ case "object": return this.object(node, path, out, place);
313
+ case "string": {
314
+ let reads = NONE;
315
+ let changed = false;
316
+ const parts = node.value.map((part, i) => {
317
+ if (part.type !== "interpolate")
318
+ return part;
319
+ const p = this.narrow(part.value, at(`string[${i}].interpolate`), WHOLE, place);
320
+ reads = both(reads, p.reads);
321
+ if (p.node === part.value)
322
+ return part;
323
+ changed = true;
324
+ return variant("interpolate", p.node);
325
+ });
326
+ return { node: this.remade(node, path, parts, changed), reads };
327
+ }
328
+ case "format": {
329
+ // `@csv` formats its input; `@csv "\(f)"` each value it interpolates.
330
+ if (node.value.string.type === "none")
331
+ return keep(WHOLE);
332
+ const s = this.narrow(node.value.string.value, at("format.string.some"), WHOLE, place);
333
+ return { node: this.remade(node, path, { ...node.value, string: some(s.node) }, s.node !== node.value.string.value), reads: s.reads };
334
+ }
335
+ case "if": {
336
+ let reads = NONE;
337
+ let changed = false;
338
+ const branches = node.value.branches.map((branch, i) => {
339
+ const c = this.narrow(branch.condition, at(`if.branches[${i}].condition`), WHOLE, place);
340
+ const t = this.narrow(branch.then, at(`if.branches[${i}].then`), out, place);
341
+ reads = both(reads, both(c.reads, t.reads));
342
+ if (c.node === branch.condition && t.node === branch.then)
343
+ return branch;
344
+ changed = true;
345
+ return { condition: c.node, then: t.node };
346
+ });
347
+ let otherwise = node.value.otherwise;
348
+ if (otherwise.type === "some") {
349
+ const o = this.narrow(otherwise.value, at("if.otherwise.some"), out, place);
350
+ reads = both(reads, o.reads);
351
+ if (o.node !== otherwise.value) {
352
+ changed = true;
353
+ otherwise = some(o.node);
354
+ }
355
+ }
356
+ else {
357
+ // No `else` gives the input.
358
+ reads = both(reads, out);
359
+ }
360
+ return { node: this.remade(node, path, { branches, otherwise }, changed), reads };
361
+ }
362
+ case "try": {
363
+ // The handler's input is the error, not the filter's.
364
+ const b = this.narrow(node.value.body, at("try.body"), out, { ...place, lenient: true });
365
+ return { node: this.remade(node, path, { ...node.value, body: b.node }, b.node !== node.value.body), reads: b.reads };
366
+ }
367
+ case "label": {
368
+ const b = this.narrow(node.value.body, at("label.body"), out, place);
369
+ return { node: this.remade(node, path, { ...node.value, body: b.node }, b.node !== node.value.body), reads: b.reads };
370
+ }
371
+ case "bind": {
372
+ // What the source gives is bound, and read as the body reads its variables: whole.
373
+ const s = this.narrow(node.value.source, at("bind.source"), WHOLE, { ...place, rows: false });
374
+ const b = this.narrow(node.value.body, at("bind.body"), out, place);
375
+ const changed = s.node !== node.value.source || b.node !== node.value.body;
376
+ return { node: this.remade(node, path, { ...node.value, body: b.node, source: s.node }, changed), reads: both(s.reads, b.reads) };
377
+ }
378
+ case "reduce":
379
+ case "foreach": {
380
+ // The update's input is the state; the source's outputs are bound, and read whole.
381
+ const s = this.narrow(node.value.source, at(`${node.type}.source`), WHOLE, { ...place, rows: false });
382
+ const i = this.narrow(node.value.init, at(`${node.type}.init`), WHOLE, { ...place, rows: false });
383
+ const changed = s.node !== node.value.source || i.node !== node.value.init;
384
+ return { node: this.remade(node, path, { ...node.value, init: i.node, source: s.node }, changed), reads: both(s.reads, i.reads) };
385
+ }
386
+ case "call": return this.call(node, path, out, place, inner);
387
+ default:
388
+ // `..`, an update, a `def`: the input whole, and nothing rewritten.
389
+ return keep(WHOLE);
390
+ }
391
+ }
392
+ /** A builtin's call: those that read their input's fields or elements apart, and any other, which reads it whole. */
393
+ call(node, path, out, place, inner) {
394
+ const { args, name } = node.value;
395
+ const arg = (i, demand, where) => this.narrow(args[i], childPath(path, `call.args[${i}]`), demand, where);
396
+ const call = (made, reads) => {
397
+ const changed = made.some((m, i) => m.node !== args[i]);
398
+ return { node: this.remade(node, path, { args: made.map(m => m.node), name }, changed), reads };
399
+ };
400
+ // The same input as the call's, which is no dataset's rows.
401
+ const same = { ...place, rows: false };
402
+ const key = `${name}/${args.length}`;
403
+ if (args.length === 0 && PASS_THROUGH.has(name))
404
+ return { node, reads: out };
405
+ switch (key) {
406
+ case "empty/0": return { node, reads: NONE };
407
+ case "select/1": {
408
+ const p = arg(0, WHOLE, same);
409
+ return call([p], both(out, p.reads));
410
+ }
411
+ case "first/1":
412
+ case "last/1": {
413
+ const f = arg(0, out, same);
414
+ return call([f], f.reads);
415
+ }
416
+ case "limit/2": {
417
+ const n = arg(0, WHOLE, same);
418
+ const f = arg(1, out, same);
419
+ return call([n, f], both(n.reads, f.reads));
420
+ }
421
+ case "any/2":
422
+ case "all/2": {
423
+ // The condition's input is each output of the generator.
424
+ const c = arg(1, WHOLE, inner);
425
+ const g = arg(0, c.reads, same);
426
+ return call([g, c], g.reads);
427
+ }
428
+ }
429
+ if (!this.arrayInput(path))
430
+ return { node, reads: WHOLE };
431
+ switch (key) {
432
+ case "length/0": return { node, reads: elementsOf(NONE) };
433
+ case "first/0":
434
+ case "last/0": return { node, reads: elementsOf(out) };
435
+ case "reverse/0": return { node, reads: elementsOf(elementOf(out)) };
436
+ case "map/1": {
437
+ const element = elementOf(out);
438
+ const f = arg(0, element, inner);
439
+ const projected = place.rows ? this.project(f.node, childPath(path, "call.args[0]"), element, place) : undefined;
440
+ return call([projected === undefined ? f : { node: projected, reads: f.reads }], elementsOf(f.reads));
441
+ }
442
+ case "any/1":
443
+ case "all/1": {
444
+ const f = arg(0, WHOLE, inner);
445
+ return call([f], elementsOf(f.reads));
446
+ }
447
+ case "group_by/1": {
448
+ const f = arg(0, WHOLE, inner);
449
+ return call([f], elementsOf(both(elementOf(elementOf(out)), f.reads)));
450
+ }
451
+ case "sort_by/1":
452
+ case "unique_by/1": {
453
+ const f = arg(0, WHOLE, inner);
454
+ return call([f], elementsOf(both(elementOf(out), f.reads)));
455
+ }
456
+ case "min_by/1":
457
+ case "max_by/1": {
458
+ const f = arg(0, WHOLE, inner);
459
+ return call([f], elementsOf(both(out, f.reads)));
460
+ }
461
+ default: return { node, reads: WHOLE };
462
+ }
463
+ }
464
+ /** An object's entry kept, its value narrowed to what is read of it. */
465
+ entry(entry, path, demand, place) {
466
+ if (entry.value.type === "none") {
467
+ // `{a}` reads `.a`; `{$x}` reads `$x`.
468
+ return { entry, reads: entry.key.type === "name" ? fieldsOf(entry.key.value) : NONE };
469
+ }
470
+ const v = this.narrow(entry.value.value, path, demand, place);
471
+ return { entry: v.node === entry.value.value ? entry : { key: entry.key, value: some(v.node) }, reads: v.reads };
472
+ }
473
+ /** `{…}`: the fields the steps after it read, and those it cannot leave unmade. */
474
+ object(node, path, out, place) {
475
+ // A computed key builds a dict, read by its keys.
476
+ if (node.value.some(entry => entry.key.type === "computed"))
477
+ return { node, reads: WHOLE };
478
+ const wanted = out.kind === "fields" ? out.fields : out.kind === "none" ? new Set() : undefined;
479
+ let reads = NONE;
480
+ let changed = false;
481
+ const entries = [];
482
+ node.value.forEach((entry, i) => {
483
+ const name = entry.key.value;
484
+ const valuePath = childPath(path, `object[${i}].value.some`);
485
+ const value = entry.value.type === "some" ? entry.value.value : undefined;
486
+ if (wanted !== undefined && !wanted.has(name) && this.droppable(value, valuePath, place)) {
487
+ changed = true;
488
+ this.changed = true;
489
+ return;
490
+ }
491
+ const kept = this.entry(entry, valuePath, wanted === undefined || wanted.has(name) ? WHOLE : NONE, place);
492
+ if (kept.entry !== entry)
493
+ changed = true;
494
+ entries.push(kept.entry);
495
+ reads = both(reads, kept.reads);
496
+ });
497
+ return { node: this.remade(node, path, entries, changed), reads };
498
+ }
499
+ /**
500
+ * `. + {…}` on a struct, as the object of the fields read after it: the
501
+ * input's that `{…}` does not set, then `{…}`'s, in its order.
502
+ */
503
+ merged(right, path, out, place) {
504
+ const type = this.typeOf(childPath(path, "binary.left"));
505
+ const struct = type === undefined ? undefined : unwrap(type);
506
+ if (struct?.type !== "Struct" || right.value.some(entry => entry.key.type === "computed"))
507
+ return undefined;
508
+ const wanted = out.kind === "fields" ? out.fields : new Set();
509
+ const set = new Set(right.value.map(entry => entry.key.value));
510
+ const names = Object.keys(struct.fields);
511
+ let dropped = names.some(name => !wanted.has(name) && !set.has(name));
512
+ const entries = [];
513
+ let reads = NONE;
514
+ for (const name of names) {
515
+ if (!wanted.has(name) || set.has(name))
516
+ continue;
517
+ entries.push(shorthand(name));
518
+ reads = both(reads, fieldsOf(name));
519
+ }
520
+ right.value.forEach((entry, i) => {
521
+ const name = entry.key.value;
522
+ const valuePath = childPath(path, `binary.right.object[${i}].value.some`);
523
+ const value = entry.value.type === "some" ? entry.value.value : undefined;
524
+ if (!wanted.has(name) && this.droppable(value, valuePath, place)) {
525
+ dropped = true;
526
+ return;
527
+ }
528
+ const kept = this.entry(entry, valuePath, wanted.has(name) ? WHOLE : NONE, place);
529
+ entries.push(kept.entry);
530
+ reads = both(reads, kept.reads);
531
+ });
532
+ if (!dropped)
533
+ return undefined;
534
+ this.changed = true;
535
+ return { node: this.made(variant("object", entries), path), reads };
536
+ }
537
+ /**
538
+ * A stage's row work over a dataset's rows that passes them on, ending with
539
+ * each row built of the fields the steps after it read; `undefined` when it
540
+ * does not pass them on, or the steps after it read every field, or none
541
+ * (`length`), and so keep no row.
542
+ */
543
+ project(f, path, element, place) {
544
+ if (place.lenient || element.kind !== "fields" || !passesThrough(f))
545
+ return undefined;
546
+ const type = this.typeOf(path);
547
+ const struct = type === undefined ? undefined : unwrap(type);
548
+ if (struct?.type !== "Struct")
549
+ return undefined;
550
+ const names = Object.keys(struct.fields);
551
+ const kept = names.filter(name => element.fields.has(name));
552
+ if (kept.length === names.length)
553
+ return undefined;
554
+ this.changed = true;
555
+ const object = this.made(variant("object", kept.map(shorthand)), path);
556
+ return this.made(variant("pipe", { left: f, right: object }), path);
557
+ }
558
+ /**
559
+ * The spans of a rewritten program: each node at the range of the node it
560
+ * came from, or of the node a node the rewrite made stands for.
561
+ *
562
+ * @returns the spans, or `undefined` when a node has no range
563
+ */
564
+ spansOf(program, original) {
565
+ const spans = this.checked.source.spans;
566
+ const origin = new Map();
567
+ const indexPattern = (pattern, path) => {
568
+ origin.set(pattern, path);
569
+ for (const child of jqPatternChildren(pattern))
570
+ indexPattern(child.pattern, childPath(path, child.step));
571
+ };
572
+ const index = (node, path) => {
573
+ origin.set(node, path);
574
+ for (const child of jqChildren(node)) {
575
+ if (child.node !== undefined)
576
+ index(child.node, childPath(path, child.step));
577
+ else
578
+ indexPattern(child.pattern, childPath(path, child.step));
579
+ }
580
+ };
581
+ index(original, "");
582
+ for (const [node, path] of this.from)
583
+ origin.set(node, path);
584
+ const out = new Map();
585
+ let complete = true;
586
+ const set = (node, path) => {
587
+ const from = origin.get(node);
588
+ const range = path === "" ? { from: 0, to: this.checked.source.text.length } : from === undefined ? undefined : spans.get(from);
589
+ if (range === undefined)
590
+ complete = false;
591
+ else
592
+ out.set(path, range);
593
+ };
594
+ const visitPattern = (pattern, path) => {
595
+ set(pattern, path);
596
+ for (const child of jqPatternChildren(pattern))
597
+ visitPattern(child.pattern, childPath(path, child.step));
598
+ };
599
+ const visit = (node, path) => {
600
+ set(node, path);
601
+ for (const child of jqChildren(node)) {
602
+ if (child.node !== undefined)
603
+ visit(child.node, childPath(path, child.step));
604
+ else
605
+ visitPattern(child.pattern, childPath(path, child.step));
606
+ }
607
+ };
608
+ visit(program, "");
609
+ return complete ? out : undefined;
610
+ }
611
+ }
612
+ /** The programs {@link narrowRows} has narrowed, by the check it was given. */
613
+ const narrowedOf = new WeakMap();
614
+ /**
615
+ * Checks a program again: the same program, over the same text, against the
616
+ * same input or another.
617
+ *
618
+ * @param checked - the program, checked
619
+ * @param program - the program to check: `checked`'s, or one rewritten from it
620
+ * @param spans - each node's range in `checked`'s text
621
+ * @param input - the input's type
622
+ * @returns the check, or `undefined` when it does not check to `checked`'s
623
+ * output type, multiplicity and reads
624
+ *
625
+ * @internal
626
+ */
627
+ export function checkAgain(checked, program, spans, input) {
628
+ if (checked.elementType === null || checked.multiplicity === null)
629
+ return undefined;
630
+ const parsed = { text: checked.source.text, program: some(program), spans, diagnostics: [] };
631
+ const again = checkJq(parsed, input, { root: checked.source.root });
632
+ if (again.program === null || again.elementType === null || again.diagnostics.some(d => d.severity.type === "error"))
633
+ return undefined;
634
+ if (!isTypeEqual(again.elementType, checked.elementType) || again.multiplicity !== checked.multiplicity)
635
+ return undefined;
636
+ if (again.reads.length !== checked.reads.length || again.reads.some((name, i) => name !== checked.reads[i]))
637
+ return undefined;
638
+ return again;
639
+ }
640
+ /**
641
+ * The program a checked query runs: its rows narrowed to the fields its later
642
+ * steps read (#1141), checked again.
643
+ *
644
+ * @param checked - the program as written, checked
645
+ * @returns the narrowed program, checked; or `checked` itself, where nothing
646
+ * narrows or the narrowed program does not check to `checked`'s output
647
+ * type, multiplicity and reads
648
+ *
649
+ * @internal
650
+ */
651
+ export function narrowRows(checked) {
652
+ const known = narrowedOf.get(checked);
653
+ if (known !== undefined)
654
+ return known;
655
+ let narrowed = checked;
656
+ const program = checked.program;
657
+ if (program !== null && !definesAny(program)) {
658
+ const n = new Narrower(checked);
659
+ const { node } = n.narrow(program, "", WHOLE, { lenient: false, root: checked.source.root, rows: false });
660
+ const spans = n.changed ? n.spansOf(node, program) : undefined;
661
+ if (spans !== undefined)
662
+ narrowed = checkAgain(checked, node, spans, checked.inputType) ?? checked;
663
+ }
664
+ narrowedOf.set(checked, narrowed);
665
+ return narrowed;
666
+ }
667
+ /**
668
+ * The fields of each row the program reads of the collection a node gives,
669
+ * as {@link narrowRows} finds them: a re-keyed join's pieces send only those
670
+ * (#1141).
671
+ *
672
+ * @param checked - the program, checked
673
+ * @param path - the node's path: a dataset's read from the root
674
+ * @returns the fields, or `undefined` when a row is read whole, or the
675
+ * program defines a function
676
+ *
677
+ * @internal
678
+ */
679
+ export function rowsRead(checked, path) {
680
+ const program = checked.program;
681
+ if (program === null || definesAny(program))
682
+ return undefined;
683
+ const n = new Narrower(checked);
684
+ n.narrow(program, "", WHOLE, { lenient: false, root: checked.source.root, rows: false });
685
+ const demand = n.demands.get(path);
686
+ if (demand?.kind !== "elements")
687
+ return undefined;
688
+ const element = demand.element;
689
+ return element.kind === "fields" ? element.fields : element.kind === "none" ? new Set() : undefined;
690
+ }
691
+ //# sourceMappingURL=narrow.js.map