@elaraai/e3 1.0.107 → 1.0.109

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 (81) hide show
  1. package/dist/src/export.d.ts.map +1 -1
  2. package/dist/src/export.js +13 -6
  3. package/dist/src/export.js.map +1 -1
  4. package/dist/src/export.spec.js +25 -3
  5. package/dist/src/export.spec.js.map +1 -1
  6. package/dist/src/function.d.ts +136 -57
  7. package/dist/src/function.d.ts.map +1 -1
  8. package/dist/src/function.js +47 -12
  9. package/dist/src/function.js.map +1 -1
  10. package/dist/src/function.spec.d.ts +3 -1
  11. package/dist/src/function.spec.d.ts.map +1 -1
  12. package/dist/src/function.spec.js +246 -3
  13. package/dist/src/function.spec.js.map +1 -1
  14. package/dist/src/index-input.d.ts +162 -0
  15. package/dist/src/index-input.d.ts.map +1 -0
  16. package/dist/src/index-input.js +216 -0
  17. package/dist/src/index-input.js.map +1 -0
  18. package/dist/src/index-input.spec.d.ts +6 -0
  19. package/dist/src/index-input.spec.d.ts.map +1 -0
  20. package/dist/src/index-input.spec.js +269 -0
  21. package/dist/src/index-input.spec.js.map +1 -0
  22. package/dist/src/index-read.d.ts +428 -0
  23. package/dist/src/index-read.d.ts.map +1 -0
  24. package/dist/src/index-read.js +747 -0
  25. package/dist/src/index-read.js.map +1 -0
  26. package/dist/src/index-read.spec.d.ts +6 -0
  27. package/dist/src/index-read.spec.d.ts.map +1 -0
  28. package/dist/src/index-read.spec.js +1447 -0
  29. package/dist/src/index-read.spec.js.map +1 -0
  30. package/dist/src/index.d.ts +10 -3
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +4 -1
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/package.d.ts.map +1 -1
  35. package/dist/src/package.js +3 -4
  36. package/dist/src/package.js.map +1 -1
  37. package/dist/src/record-area.d.ts +12 -0
  38. package/dist/src/record-area.d.ts.map +1 -1
  39. package/dist/src/record-area.js +26 -0
  40. package/dist/src/record-area.js.map +1 -1
  41. package/dist/src/record-area.spec.js +4 -14
  42. package/dist/src/record-area.spec.js.map +1 -1
  43. package/dist/src/record-builders.d.ts +39 -14
  44. package/dist/src/record-builders.d.ts.map +1 -1
  45. package/dist/src/record-builders.js.map +1 -1
  46. package/dist/src/record-entries.spec.js +2 -15
  47. package/dist/src/record-entries.spec.js.map +1 -1
  48. package/dist/src/record-index.d.ts +11 -5
  49. package/dist/src/record-index.d.ts.map +1 -1
  50. package/dist/src/record-index.js.map +1 -1
  51. package/dist/src/record-interval.d.ts +7 -0
  52. package/dist/src/record-interval.d.ts.map +1 -1
  53. package/dist/src/record-interval.js +7 -0
  54. package/dist/src/record-interval.js.map +1 -1
  55. package/dist/src/record-nested-programs.d.ts +63 -511
  56. package/dist/src/record-nested-programs.d.ts.map +1 -1
  57. package/dist/src/record-nested-programs.js +403 -222
  58. package/dist/src/record-nested-programs.js.map +1 -1
  59. package/dist/src/record-nested.d.ts +60 -10
  60. package/dist/src/record-nested.d.ts.map +1 -1
  61. package/dist/src/record-nested.js +65 -23
  62. package/dist/src/record-nested.js.map +1 -1
  63. package/dist/src/record-nested.spec.js +113 -34
  64. package/dist/src/record-nested.spec.js.map +1 -1
  65. package/dist/src/record-series.spec.js +6 -31
  66. package/dist/src/record-series.spec.js.map +1 -1
  67. package/dist/src/record.d.ts +9 -0
  68. package/dist/src/record.d.ts.map +1 -1
  69. package/dist/src/record.js +14 -0
  70. package/dist/src/record.js.map +1 -1
  71. package/dist/src/task.d.ts +28 -16
  72. package/dist/src/task.d.ts.map +1 -1
  73. package/dist/src/task.js +33 -5
  74. package/dist/src/task.js.map +1 -1
  75. package/dist/src/test-helpers.d.ts +35 -0
  76. package/dist/src/test-helpers.d.ts.map +1 -0
  77. package/dist/src/test-helpers.js +56 -0
  78. package/dist/src/test-helpers.js.map +1 -0
  79. package/dist/src/types.d.ts +86 -13
  80. package/dist/src/types.d.ts.map +1 -1
  81. package/package.json +3 -3
@@ -0,0 +1,1447 @@
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 reader for each kind of index (#1618): each reads the rows its words say
7
+ * and no others, each once — held, for seeded records and windows, to a plain
8
+ * loop over the whole record — by the window's edges, in the index's order,
9
+ * and refuses what it is not given where it is called.
10
+ *
11
+ * The entries a reader reads are the ones each index's own build program
12
+ * files for the rows, so a reader is held to the index as it is stored.
13
+ */
14
+ import { describe, it } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import { ArrayType, BooleanType, DateTimeType, DictType, East, FloatType, IntegerType, NullType, OptionType, RecursiveType, SetType, SortedMap, SortedSet, StringType, StructType, compareFor, decodeBeast2For, encodeBeast2For, equalFor, none, printFor, some, variant, } from '@elaraai/east';
17
+ import { RecordLevelType, RecordNestedTotalsType, RecordSummaryTotalsType } from '@elaraai/e3-types';
18
+ import { function_ } from './function.js';
19
+ import { index } from './index-input.js';
20
+ import { NestedUnderType } from './index-read.js';
21
+ import { input as input_ } from './input.js';
22
+ import { output } from './output.js';
23
+ import { record } from './record.js';
24
+ import { builtIndex, indexBuildProgram, summaryMergeProgram } from './record-programs.js';
25
+ import { TILE_FNS } from './record-tiles.js';
26
+ import { partition, streamTask, task } from './task.js';
27
+ import { assertEast, at, seededStream } from './test-helpers.js';
28
+ /** A print job: the press it runs on, the crews on it, its state, and when it runs, or not yet. */
29
+ const JobRow = StructType({
30
+ press: StringType, crews: SetType(StringType), state: StringType,
31
+ start: OptionType(DateTimeType), end: OptionType(DateTimeType), title: StringType, sheets: FloatType,
32
+ });
33
+ const JobsType = DictType(StringType, JobRow);
34
+ const keyOrder = compareFor(StringType);
35
+ const decodeJob = decodeBeast2For(JobRow);
36
+ const encodeJob = encodeBeast2For(JobRow);
37
+ const jobs = record('jobs', JobsType, {
38
+ initial: new Map(),
39
+ indexes: (index) => ({
40
+ by_press: index.on(['press']),
41
+ by_state: index.on(['state']),
42
+ by_state_press: index.on(['state', 'press']),
43
+ by_crew: index.on(['crews']),
44
+ by_state_crew: index.on(['state', 'crews']),
45
+ titles: index.key(East.function([StringType, JobRow], StringType, (_$, _key, job) => job.press), { value: East.function([StringType, JobRow], StringType, (_$, _key, job) => job.title) }),
46
+ in_time: index.interval({ from: 'start', to: 'end' }),
47
+ in_time_by_state: index.interval({ on: ['state'], from: 'start', to: 'end' }),
48
+ press_weeks: index.series({ key: 'press', from: 'start', to: 'end', tile: 'week' }),
49
+ press_days_by_state: index.series({ on: ['state'], key: 'press', from: 'start', to: 'end', tile: 'day' }),
50
+ press_quarters: index.series({ key: 'press', from: 'start', to: 'end', tile: 'quarter' }),
51
+ press_load: index.summary({ key: 'press', from: 'start', to: 'end', tile: 'week' }),
52
+ press_load_by_state: index.summary({ on: ['state'], key: 'press', from: 'start', to: 'end', tile: 'month' }),
53
+ }),
54
+ mutations: (mutation) => ({ patch: mutation.patch() }),
55
+ });
56
+ /** A press's shift: always placed, its start and end plain DateTimes. */
57
+ const ShiftRow = StructType({ press: StringType, start: DateTimeType, end: DateTimeType });
58
+ const ShiftsType = DictType(StringType, ShiftRow);
59
+ const shifts = record('shifts', ShiftsType, {
60
+ initial: new Map(),
61
+ indexes: (index) => ({
62
+ shifts_in_time: index.interval({ from: 'start', to: 'end' }),
63
+ shifts_by_press: index.series({ key: 'press', from: 'start', to: 'end', tile: 'day' }),
64
+ }),
65
+ });
66
+ const DAY = 86400000n;
67
+ const HOUR = 3600000n;
68
+ const printInstant = printFor(DateTimeType);
69
+ /** The instant `ms` milliseconds from the epoch, made by East. */
70
+ const instant = East.compile(East.function([IntegerType], DateTimeType, (_$, ms) => East.DateTime.fromEpochMilliseconds(ms)), []);
71
+ /** An instant's milliseconds from the epoch, read by East. */
72
+ const millisecondsOf = East.compile(East.function([DateTimeType], IntegerType, (_$, t) => t.toEpochMilliseconds()), []);
73
+ const PRESSES = ['P-1001', 'P-1002', 'P-1003'];
74
+ const STATES = ['confirmed', 'proposed'];
75
+ const CREWS = [[], ['north'], ['north', 'south'], ['east', 'north', 'south']];
76
+ /** Monday 5 October 2026, which the seeded jobs are scheduled around. */
77
+ const OCT_5 = millisecondsOf(at('2026-10-05T00:00:00.000'));
78
+ /** A job, as a write carries it: on a press, crewed, and scheduled from `start` to `end`, or not yet. */
79
+ function job(n, start, end) {
80
+ return decodeJob(encodeJob({
81
+ press: PRESSES[n % PRESSES.length],
82
+ crews: new SortedSet(CREWS[n % CREWS.length], keyOrder),
83
+ state: STATES[n % STATES.length],
84
+ start: start === undefined ? none : some(instant(start)),
85
+ end: end === undefined ? none : some(instant(end)),
86
+ title: `Job ${n}`,
87
+ sheets: 1000 + n,
88
+ }));
89
+ }
90
+ /**
91
+ * The jobs the readers read: lengths from an hour to three years, around
92
+ * October 2026 and across the turns of the years either side; some from a
93
+ * day's midnight, some instants with no end, some ending before they start,
94
+ * some not yet scheduled; and the edges, by name.
95
+ */
96
+ function seededJobs() {
97
+ const draw = seededStream(1618);
98
+ const rows = new SortedMap(undefined, keyOrder);
99
+ for (let n = 0; n < 400; n++) {
100
+ const start = OCT_5 + BigInt(Math.floor((draw() - 0.5) * 900)) * DAY + BigInt(Math.floor(draw() * 24)) * HOUR;
101
+ // Most are short; one in eight is months long, and one in twenty years long.
102
+ const scale = n % 20 === 7 ? 1100 : n % 8 === 3 ? 200 : 12;
103
+ const length = HOUR + BigInt(Math.floor(draw() ** 2 * scale * 24)) * HOUR;
104
+ const key = `W-${String(n).padStart(4, '0')}`;
105
+ switch (n % 10) {
106
+ case 0:
107
+ rows.set(key, job(n, undefined, undefined));
108
+ break;
109
+ case 1:
110
+ rows.set(key, job(n, start, undefined));
111
+ break;
112
+ case 2:
113
+ rows.set(key, job(n, start, start - HOUR));
114
+ break;
115
+ case 3:
116
+ rows.set(key, job(n, start - ((start % DAY) + DAY) % DAY, start - ((start % DAY) + DAY) % DAY + length));
117
+ break;
118
+ default:
119
+ rows.set(key, job(n, start, start + length));
120
+ break;
121
+ }
122
+ }
123
+ const ms = (text) => millisecondsOf(at(text));
124
+ // The edges of the week from Monday 12 October, on the first press, confirmed.
125
+ rows.set('E-ends-at-from', job(0, ms('2026-10-05T00:00:00.000'), ms('2026-10-12T00:00:00.000')));
126
+ rows.set('E-instant-at-from', job(0, ms('2026-10-12T00:00:00.000'), undefined));
127
+ rows.set('E-instant-at-to', job(0, ms('2026-10-19T00:00:00.000'), undefined));
128
+ rows.set('E-starts-at-to', job(0, ms('2026-10-19T00:00:00.000'), ms('2026-10-20T00:00:00.000')));
129
+ rows.set('E-no-end', job(0, ms('2026-10-13T09:00:00.000'), undefined));
130
+ rows.set('E-no-start', job(0, undefined, ms('2026-10-13T09:00:00.000')));
131
+ rows.set('E-ends-before-start', job(0, ms('2026-10-14T09:00:00.000'), ms('2026-10-13T09:00:00.000')));
132
+ rows.set('E-past-a-year', job(0, ms('2025-11-20T06:00:00.000'), ms('2027-02-10T18:00:00.000')));
133
+ rows.set('E-a-millisecond-in', job(0, ms('2026-10-11T00:00:00.000'), ms('2026-10-12T00:00:00.001')));
134
+ return rows;
135
+ }
136
+ const ROWS = seededJobs();
137
+ /** The windows the readers read: the week of the edges, one narrower than a tile, one wider than a year, and seeded ones. */
138
+ function windows() {
139
+ const draw = seededStream(55);
140
+ const out = [
141
+ { from: at('2026-10-12T00:00:00.000'), to: at('2026-10-19T00:00:00.000') },
142
+ { from: at('2026-10-12T09:00:00.000'), to: at('2026-10-12T10:00:00.000') },
143
+ { from: at('2025-06-01T00:00:00.000'), to: at('2027-06-01T00:00:00.000') },
144
+ { from: at('2026-12-31T23:59:59.999'), to: at('2027-01-01T00:00:00.001') },
145
+ { from: at('2026-10-12T00:00:00.000'), to: at('2026-10-12T00:00:00.000') },
146
+ { from: at('2026-10-19T00:00:00.000'), to: at('2026-10-12T00:00:00.000') },
147
+ ];
148
+ for (let n = 0; n < 60; n++) {
149
+ const from = OCT_5 + BigInt(Math.floor((draw() - 0.5) * 1000)) * DAY + BigInt(Math.floor(draw() * 24)) * HOUR;
150
+ const length = n % 3 === 0 ? HOUR * BigInt(1 + Math.floor(draw() * 30)) : DAY * BigInt(1 + Math.floor(draw() ** 2 * 500));
151
+ out.push({ from: instant(from), to: instant(from + length) });
152
+ }
153
+ return out;
154
+ }
155
+ const WINDOWS = windows();
156
+ /** An index's entries as its record's state holds them: what its own build program files for the rows. Typed as
157
+ * whatever a compiled function takes them as, which is the index's own entries' type. */
158
+ function entriesOf(rec, declared, rows) {
159
+ const def = builtIndex(rec, declared);
160
+ // A summary's entries, and a span's, are summed by their merge and name no row
161
+ const summary = def.summary !== undefined || def.span !== undefined;
162
+ const entryType = StructType({ ik: def.keyType, k: summary ? NullType : rec.type.key });
163
+ const entries = new SortedMap(undefined, compareFor(entryType));
164
+ const merge = summary ? summaryMergeProgram(def).compile([]) : undefined;
165
+ const build = indexBuildProgram(rec.type, def).compile([]);
166
+ build(rows, (entry, value) => {
167
+ const held = entries.get(entry);
168
+ entries.set(entry, held === undefined || merge === undefined ? value : merge(entry, held, value));
169
+ return null;
170
+ });
171
+ return entries;
172
+ }
173
+ const window = (w) => `[${printInstant(w.from)}, ${printInstant(w.to)})`;
174
+ /**
175
+ * Whether a read gave its rows as a walk of the index meets them: each at an
176
+ * entry after the one the row before it was given at. An index may file a row
177
+ * under several entries, so the walk takes the first that fits.
178
+ *
179
+ * @param type - The type the read names a row by: its key, or a nested item's
180
+ * @param entries - The index's entries, in its order
181
+ * @param named - What an entry names its row by, as the read does
182
+ * @param given - What the read gave, in the order it gave it
183
+ * @returns Whether every row given was met, in order
184
+ */
185
+ function inIndexOrder(type, entries, named, given) {
186
+ const same = equalFor(type);
187
+ let met = 0;
188
+ for (const entry of entries) {
189
+ const name = named(entry);
190
+ if (met < given.length && name !== undefined && same(name, given[met]))
191
+ met += 1;
192
+ }
193
+ return met === given.length;
194
+ }
195
+ // ── The plain test, as a loop over the whole record ──────────────────────────
196
+ /** Whether a job overlaps `[from, to)`, by the interval index's edges. */
197
+ const overlaps = East.function([JobRow, DateTimeType, DateTimeType], BooleanType, ($, job, from, to) => {
198
+ $.match(job.start, {
199
+ some: ($, start) => {
200
+ const end = $.let(job.end.unwrap('some', () => start));
201
+ // No end, or one at or before the start: an instant, inside from `from` and outside at `to`.
202
+ $.if(East.lessEqual(end, start), ($) => { $.return(East.greaterEqual(start, from).and(() => East.less(start, to))); });
203
+ $.return(East.less(start, to).and(() => East.greater(end, from)));
204
+ },
205
+ });
206
+ return false;
207
+ });
208
+ /** The jobs of a state, or of every state, on a press, or on every press, that overlap a window: a loop over them all. */
209
+ const jobsIn = East.compile(East.function([JobsType, OptionType(StringType), OptionType(StringType), DateTimeType, DateTimeType], JobsType, ($, rows, state, press, from, to) => {
210
+ const inWindow = $.const(overlaps);
211
+ return rows.filter(($, job) => East.less(from, to)
212
+ .and(() => state.match({ none: () => true, some: (_$, s) => East.equal(job.state, s) }))
213
+ .and(() => press.match({ none: () => true, some: (_$, p) => East.equal(job.press, p) }))
214
+ .and(() => inWindow(job, from, to)));
215
+ }), []);
216
+ /** The keys of some rows, each carrying nothing: what a read of an index that carries nothing collects. */
217
+ const keysOf = East.compile(East.function([JobsType], DictType(StringType, NullType), (_$, rows) => rows.map(() => null)), []);
218
+ // ── The indexes' entries, and the reads ──────────────────────────────────────
219
+ const input = {
220
+ by_press: index(jobs.indexes.by_press),
221
+ by_state_press: index(jobs.indexes.by_state_press),
222
+ by_crew: index(jobs.indexes.by_crew),
223
+ by_state_crew: index(jobs.indexes.by_state_crew),
224
+ titles: index(jobs.indexes.titles),
225
+ in_time: index(jobs.indexes.in_time),
226
+ in_time_by_state: index(jobs.indexes.in_time_by_state),
227
+ press_weeks: index(jobs.indexes.press_weeks),
228
+ press_days_by_state: index(jobs.indexes.press_days_by_state),
229
+ press_quarters: index(jobs.indexes.press_quarters),
230
+ press_load: index(jobs.indexes.press_load),
231
+ press_load_by_state: index(jobs.indexes.press_load_by_state),
232
+ };
233
+ const held = Object.fromEntries(Object.entries(input).map(([name, at]) => [name, entriesOf(jobs, at.index, ROWS)]));
234
+ const Keys = DictType(StringType, NullType);
235
+ describe('a read of an index', () => {
236
+ it('gives each row to a body, which may skip one, add to what it holds, and leave the function', () => {
237
+ const byPress = input.by_press;
238
+ const sheets = East.compile(East.function([byPress.type, JobsType, StringType], FloatType, ($, entries, rows, press) => {
239
+ const total = $.let(0.0);
240
+ byPress.read(entries).of(press).each($, ($, _carried, key) => {
241
+ const job = $.let(rows.get(key));
242
+ $.if(East.equal(job.state, 'confirmed'), ($) => { $.assign(total, total.add(job.sheets)); });
243
+ });
244
+ return total;
245
+ }), []);
246
+ const expected = [...ROWS.values()].filter((row) => row.press === 'P-1002' && row.state === 'confirmed').reduce((sum, row) => sum + row.sheets, 0);
247
+ assert.equal(sheets(held.by_press, ROWS, 'P-1002'), expected);
248
+ // The first row of a read, by leaving the function from the body
249
+ const first = East.compile(East.function([byPress.type, StringType], OptionType(StringType), ($, entries, press) => {
250
+ byPress.read(entries).of(press).each($, ($, _carried, key) => { $.return(some(key)); });
251
+ return none;
252
+ }), []);
253
+ assertEast(OptionType(StringType), first(held.by_press, 'P-1003'), some([...ROWS].find(([, row]) => row.press === 'P-1003')[0]), 'the first job on the press');
254
+ assertEast(OptionType(StringType), first(held.by_press, 'P-9999'), none, 'a press with no job');
255
+ });
256
+ it('gives its rows in the index\'s own order, and collects them by the row\'s key', () => {
257
+ const byState = input.by_state_press;
258
+ const inOrder = East.compile(East.function([byState.type, StringType], ArrayType(StringType), ($, entries, state) => {
259
+ const keys = $.let([], ArrayType(StringType));
260
+ byState.read(entries).of({ state }).each($, ($, _carried, key) => { $(keys.pushLast(key)); });
261
+ return keys;
262
+ }), []);
263
+ // By press, then by the row's key: the index's order under a state
264
+ const expected = [...ROWS].filter(([, row]) => row.state === 'proposed')
265
+ .sort(([a, x], [b, y]) => keyOrder(x.press, y.press) || keyOrder(a, b)).map(([key]) => key);
266
+ assertEast(ArrayType(StringType), inOrder(held.by_state_press, 'proposed'), expected, 'the proposed jobs, by press');
267
+ });
268
+ });
269
+ describe('a plain index\'s readers', () => {
270
+ it('of: the rows under an index key, and under a leading part of one', () => {
271
+ const byPress = input.by_press;
272
+ const on = East.compile(East.function([byPress.type, StringType], Keys, ($, entries, press) => byPress.read(entries).of(press).collect($)), []);
273
+ for (const press of [...PRESSES, 'P-9999']) {
274
+ assertEast(Keys, on(held.by_press, press), keysOf(new SortedMap([...ROWS].filter(([, row]) => row.press === press), keyOrder)), `the jobs on ${press}`);
275
+ }
276
+ const byState = input.by_state_press;
277
+ const whole = East.compile(East.function([byState.type, StringType, StringType], Keys, ($, entries, state, press) => byState.read(entries).of({ state, press }).collect($)), []);
278
+ const leading = East.compile(East.function([byState.type, StringType], Keys, ($, entries, state) => byState.read(entries).of({ state }).collect($)), []);
279
+ for (const state of STATES) {
280
+ assertEast(Keys, leading(held.by_state_press, state), keysOf(new SortedMap([...ROWS].filter(([, row]) => row.state === state), keyOrder)), `the ${state} jobs`);
281
+ assertEast(Keys, whole(held.by_state_press, state, 'P-1001'), keysOf(new SortedMap([...ROWS].filter(([, row]) => row.state === state && row.press === 'P-1001'), keyOrder)), `the ${state} jobs on P-1001`);
282
+ }
283
+ });
284
+ it('of: what the index carries, where it carries a value of its own', () => {
285
+ const titles = input.titles;
286
+ const on = East.compile(East.function([titles.type, StringType], DictType(StringType, StringType), ($, entries, press) => titles.read(entries).of(press).collect($)), []);
287
+ const expected = new SortedMap([...ROWS].filter(([, row]) => row.press === 'P-1003').map(([key, row]) => [key, row.title]), keyOrder);
288
+ assertEast(DictType(StringType, StringType), on(held.titles, 'P-1003'), expected, 'the titles on P-1003');
289
+ });
290
+ it('between: the rows from one index key up to another, either end left out', () => {
291
+ const byPress = input.by_press;
292
+ const between = East.compile(East.function([byPress.type, StringType, StringType], Keys, ($, entries, from, to) => byPress.read(entries).between({ from, to }).collect($)), []);
293
+ const from = East.compile(East.function([byPress.type, StringType], Keys, ($, entries, from) => byPress.read(entries).between({ from }).collect($)), []);
294
+ const upTo = East.compile(East.function([byPress.type, StringType], Keys, ($, entries, to) => byPress.read(entries).between({ to }).collect($)), []);
295
+ const every = East.compile(East.function([byPress.type], Keys, ($, entries) => byPress.read(entries).between({}).collect($)), []);
296
+ const where = (test) => keysOf(new SortedMap([...ROWS].filter(([, row]) => test(row.press)), keyOrder));
297
+ assertEast(Keys, between(held.by_press, 'P-1001', 'P-1003'), where((press) => press === 'P-1001' || press === 'P-1002'), 'from P-1001 up to P-1003');
298
+ assertEast(Keys, between(held.by_press, 'P-1003', 'P-1001'), where(() => false), 'an inverted range');
299
+ assertEast(Keys, from(held.by_press, 'P-1002'), where((press) => press !== 'P-1001'), 'from P-1002');
300
+ assertEast(Keys, upTo(held.by_press, 'P-1002'), where((press) => press === 'P-1001'), 'up to P-1002');
301
+ assertEast(Keys, every(held.by_press), where(() => true), 'both ends left out');
302
+ });
303
+ it('gives a row once where the index files it under several keys: a Set field fanned out', () => {
304
+ const byCrew = input.by_crew;
305
+ // One crew's rows are filed under it once each; a range of crews holds a row once for each crew it is on
306
+ const counted = East.compile(East.function([byCrew.type, StringType, StringType], StructType({ given: IntegerType, rows: Keys }), ($, entries, from, to) => {
307
+ const given = $.let(0n);
308
+ const read = byCrew.read(entries).between({ from, to });
309
+ read.each($, ($) => { $.assign(given, given.add(1n)); });
310
+ return { given, rows: read.collect($) };
311
+ }), []);
312
+ const onAny = (crews) => keysOf(new SortedMap([...ROWS].filter(([, row]) => crews.some((crew) => row.crews.has(crew))), keyOrder));
313
+ const northToSouth = counted(held.by_crew, 'north', 'south\u0000');
314
+ assertEast(Keys, northToSouth.rows, onAny(['north', 'south']), 'the rows on north or south');
315
+ assert.equal(northToSouth.given, BigInt(northToSouth.rows.size), 'each given once, though most are on both');
316
+ assert.ok([...ROWS.values()].filter((row) => row.crews.has('north') && row.crews.has('south')).length > 50, 'most rows on north are on south too');
317
+ const of = East.compile(East.function([byCrew.type, StringType], Keys, ($, entries, crew) => byCrew.read(entries).of(crew).collect($)), []);
318
+ assertEast(Keys, of(held.by_crew, 'south'), onAny(['south']), 'the rows on south');
319
+ // Under a leading part of a key whose Set fans out
320
+ const byStateCrew = input.by_state_crew;
321
+ const inState = East.compile(East.function([byStateCrew.type, StringType], Keys, ($, entries, state) => byStateCrew.read(entries).of({ state }).collect($)), []);
322
+ const crewed = keysOf(new SortedMap([...ROWS].filter(([, row]) => row.state === 'confirmed' && row.crews.size > 0), keyOrder));
323
+ assertEast(Keys, inState(held.by_state_crew, 'confirmed'), crewed, 'the confirmed rows with a crew');
324
+ });
325
+ });
326
+ describe('an interval index\'s readers', () => {
327
+ const inTime = input.in_time;
328
+ const overlapping = East.compile(East.function([inTime.type, DateTimeType, DateTimeType], Keys, ($, entries, from, to) => inTime.read(entries).overlapping({ from, to }).collect($)), []);
329
+ const counted = East.compile(East.function([inTime.type, DateTimeType, DateTimeType], IntegerType, ($, entries, from, to) => {
330
+ const given = $.let(0n);
331
+ inTime.read(entries).overlapping({ from, to }).each($, ($) => { $.assign(given, given.add(1n)); });
332
+ return given;
333
+ }), []);
334
+ it('overlapping: the rows that overlap a window, each once, for seeded windows', () => {
335
+ for (const w of WINDOWS) {
336
+ const expected = keysOf(jobsIn(ROWS, none, none, w.from, w.to));
337
+ assertEast(Keys, overlapping(held.in_time, w.from, w.to), expected, `the jobs in ${window(w)}`);
338
+ assert.equal(counted(held.in_time, w.from, w.to), BigInt(expected.size), `each once in ${window(w)}`);
339
+ }
340
+ });
341
+ it('overlapping: the window\'s edges', () => {
342
+ const week = overlapping(held.in_time, at('2026-10-12T00:00:00.000'), at('2026-10-19T00:00:00.000'));
343
+ const inside = (key) => week.has(key);
344
+ assert.equal(inside('E-ends-at-from'), false, 'an event that ends at `from` is outside');
345
+ assert.equal(inside('E-a-millisecond-in'), true, 'one that ends a millisecond after it is inside');
346
+ assert.equal(inside('E-instant-at-from'), true, 'an instant at `from` is inside');
347
+ assert.equal(inside('E-instant-at-to'), false, 'an instant at `to` is outside');
348
+ assert.equal(inside('E-starts-at-to'), false, 'an event that starts at `to` is outside');
349
+ assert.equal(inside('E-no-end'), true, 'an event with no end is an instant');
350
+ assert.equal(inside('E-ends-before-start'), true, 'one that ends before its start is an instant at its start');
351
+ assert.equal(inside('E-no-start'), false, 'a row with no start is in no window');
352
+ assert.equal(inside('E-past-a-year'), true, 'an event that began a year before reaches in');
353
+ });
354
+ it('overlapping: gives its rows as a walk of the index meets them — the starts in the window, then each node above it from the root down', () => {
355
+ const inOrder = East.compile(East.function([inTime.type, DateTimeType, DateTimeType], ArrayType(StringType), ($, entries, from, to) => {
356
+ const keys = $.let([], ArrayType(StringType));
357
+ inTime.read(entries).overlapping({ from, to }).each($, ($, _carried, key) => { $(keys.pushLast(key)); });
358
+ return keys;
359
+ }), []);
360
+ const filed = [...held.in_time.keys()];
361
+ let carried = 0;
362
+ for (const w of WINDOWS) {
363
+ const given = inOrder(held.in_time, w.from, w.to);
364
+ // The rows the window's later runs hold: those that began before it
365
+ carried += given.filter((key) => { const start = ROWS.get(key).start; return start.type === 'some' && compareFor(DateTimeType)(start.value, w.from) < 0; }).length;
366
+ assert.ok(inIndexOrder(StringType, filed, (entry) => entry.k, given), `the jobs in ${window(w)} come in the index's order`);
367
+ }
368
+ assert.ok(carried > 500, `the windows hold rows of more than one run: ${carried}`);
369
+ });
370
+ it('overlapping: under each leading field, exactly', () => {
371
+ const byState = input.in_time_by_state;
372
+ const inState = East.compile(East.function([byState.type, StringType, DateTimeType, DateTimeType], Keys, ($, entries, state, from, to) => byState.read(entries).overlapping({ on: { state }, from, to }).collect($)), []);
373
+ for (const w of WINDOWS.slice(0, 20)) {
374
+ for (const state of STATES) {
375
+ assertEast(Keys, inState(held.in_time_by_state, state, w.from, w.to), keysOf(jobsIn(ROWS, some(state), none, w.from, w.to)), `the ${state} jobs in ${window(w)}`);
376
+ }
377
+ }
378
+ });
379
+ it('unset: the rows with no start', () => {
380
+ const unset = East.compile(East.function([inTime.type], Keys, ($, entries) => inTime.read(entries).unset().collect($)), []);
381
+ assertEast(Keys, unset(held.in_time), keysOf(new SortedMap([...ROWS].filter(([, row]) => row.start.type === 'none'), keyOrder)), 'the jobs not yet scheduled');
382
+ const byState = input.in_time_by_state;
383
+ const unsetIn = East.compile(East.function([byState.type, StringType], Keys, ($, entries, state) => byState.read(entries).unset({ on: { state } }).collect($)), []);
384
+ assertEast(Keys, unsetIn(held.in_time_by_state, 'proposed'), keysOf(new SortedMap([...ROWS].filter(([, row]) => row.start.type === 'none' && row.state === 'proposed'), keyOrder)), 'the proposed jobs not yet scheduled');
385
+ });
386
+ });
387
+ describe('a series index\'s readers', () => {
388
+ for (const name of ['press_weeks', 'press_quarters']) {
389
+ const series = input[name];
390
+ const events = East.compile(East.function([series.type, StringType, DateTimeType, DateTimeType], JobsType, ($, entries, press, from, to) => series.read(entries).events({ key: press, from, to }).collect($)), []);
391
+ const counted = East.compile(East.function([series.type, StringType, DateTimeType, DateTimeType], IntegerType, ($, entries, press, from, to) => {
392
+ const given = $.let(0n);
393
+ series.read(entries).events({ key: press, from, to }).each($, ($) => { $.assign(given, given.add(1n)); });
394
+ return given;
395
+ }), []);
396
+ it(`events: a key's events that overlap a window, each once with its row, for seeded windows (${name})`, () => {
397
+ for (const w of WINDOWS) {
398
+ for (const press of PRESSES) {
399
+ const expected = jobsIn(ROWS, none, some(press), w.from, w.to);
400
+ assertEast(JobsType, events(held[name], press, w.from, w.to), expected, `the jobs on ${press} in ${window(w)}`);
401
+ assert.equal(counted(held[name], press, w.from, w.to), BigInt(expected.size), `each once on ${press} in ${window(w)}`);
402
+ }
403
+ }
404
+ });
405
+ }
406
+ it('events: the window\'s edges, and an event past a year across a year\'s turn', () => {
407
+ const series = input.press_weeks;
408
+ const events = East.compile(East.function([series.type, StringType, DateTimeType, DateTimeType], JobsType, ($, entries, press, from, to) => series.read(entries).events({ key: press, from, to }).collect($)), []);
409
+ const week = events(held.press_weeks, 'P-1001', at('2026-10-12T00:00:00.000'), at('2026-10-19T00:00:00.000'));
410
+ assert.deepEqual(['E-ends-at-from', 'E-a-millisecond-in', 'E-instant-at-from', 'E-instant-at-to', 'E-starts-at-to', 'E-no-end', 'E-ends-before-start', 'E-no-start', 'E-past-a-year']
411
+ .map((key) => week.has(key)), [false, true, true, false, false, true, true, false, true]);
412
+ // Filed under 2025, 2026 and 2027: a window across both turns meets it under each, and gives it once
413
+ const across = events(held.press_weeks, 'P-1001', at('2025-12-01T00:00:00.000'), at('2027-01-15T00:00:00.000'));
414
+ assert.equal(across.has('E-past-a-year'), true);
415
+ const filed = [...held.press_weeks.keys()].filter((entry) => keyOrder(entry.k, 'E-past-a-year') === 0).length;
416
+ assert.equal(filed, 3, 'the index files it under each of the three years it touches');
417
+ });
418
+ it('events: gives its rows as a walk of the index meets them — a run a level, in the index\'s order of its levels', () => {
419
+ const series = input.press_days_by_state;
420
+ const inOrder = East.compile(East.function([series.type, StringType, StringType, DateTimeType, DateTimeType], ArrayType(StringType), ($, entries, state, press, from, to) => {
421
+ const keys = $.let([], ArrayType(StringType));
422
+ series.read(entries).events({ on: { state }, key: press, from, to }).each($, ($, _job, key) => { $(keys.pushLast(key)); });
423
+ return keys;
424
+ }), []);
425
+ const filed = [...held.press_days_by_state.keys()];
426
+ // The index orders a level by East's order of its cases, which is no order of their lengths
427
+ const levelOrder = compareFor(RecordLevelType);
428
+ assert.ok(levelOrder(variant('month', null), variant('week', null)) < 0 && levelOrder(variant('week', null), variant('year', null)) < 0, 'a month is before a week in the index');
429
+ const levels = new SortedSet(undefined, levelOrder);
430
+ for (const w of WINDOWS) {
431
+ for (const state of STATES) {
432
+ const given = inOrder(held.press_days_by_state, state, 'P-1001', w.from, w.to);
433
+ for (const entry of filed)
434
+ if (given.some((key) => keyOrder(key, entry.k) === 0) && keyOrder(entry.ik.key, 'P-1001') === 0)
435
+ levels.add(entry.ik.level);
436
+ assert.ok(inIndexOrder(StringType, filed, (entry) => entry.k, given), `the ${state} jobs on P-1001 in ${window(w)} come in the index's order`);
437
+ }
438
+ }
439
+ assert.equal(levels.size, 5, 'the windows read events filed at every level, a day to a year');
440
+ });
441
+ it('events: under each leading field, exactly', () => {
442
+ const series = input.press_days_by_state;
443
+ const events = East.compile(East.function([series.type, StringType, StringType, DateTimeType, DateTimeType], JobsType, ($, entries, state, press, from, to) => series.read(entries).events({ on: { state }, key: press, from, to }).collect($)), []);
444
+ for (const w of WINDOWS.slice(0, 20)) {
445
+ for (const state of STATES) {
446
+ assertEast(JobsType, events(held.press_days_by_state, state, 'P-1002', w.from, w.to), jobsIn(ROWS, some(state), some('P-1002'), w.from, w.to), `the ${state} jobs on P-1002 in ${window(w)}`);
447
+ }
448
+ }
449
+ });
450
+ it('events: rows whose start and end are plain DateTimes', () => {
451
+ const shiftRows = new SortedMap(undefined, keyOrder);
452
+ for (let n = 0; n < 60; n++) {
453
+ const start = OCT_5 + BigInt(n) * 8n * HOUR;
454
+ shiftRows.set(`S-${String(n).padStart(3, '0')}`, decodeBeast2For(ShiftRow)(encodeBeast2For(ShiftRow)({ press: PRESSES[n % 3], start: instant(start), end: instant(start + 8n * HOUR) })));
455
+ }
456
+ const byPress = index(shifts.indexes.shifts_by_press);
457
+ const events = East.compile(East.function([byPress.type, StringType, DateTimeType, DateTimeType], DictType(StringType, NullType), ($, entries, press, from, to) => {
458
+ const keys = $.let(new Map(), DictType(StringType, NullType));
459
+ byPress.read(entries).events({ key: press, from, to }).each($, ($, _shift, key) => { $(keys.insert(key, null)); });
460
+ return keys;
461
+ }), []);
462
+ const from = at('2026-10-06T08:00:00.000');
463
+ const to = at('2026-10-08T00:00:00.000');
464
+ const expected = new SortedMap([...shiftRows].filter(([, shift]) => shift.press === 'P-1001' && shift.start < to && shift.end > from).map(([key]) => [key, null]), keyOrder);
465
+ assert.ok(expected.size > 0);
466
+ assertEast(DictType(StringType, NullType), events(entriesOf(shifts, shifts.indexes.shifts_by_press, shiftRows), 'P-1001', from, to), expected, 'the shifts on P-1001');
467
+ });
468
+ });
469
+ describe('a summary index\'s readers', () => {
470
+ const Totals = DictType(DateTimeType, RecordSummaryTotalsType);
471
+ const nextOf = East.compile(TILE_FNS.tileNext, []);
472
+ /** The totals an index holds of a key's tiles that overlap a window: a loop over every entry of it, each typed by the index's own entries. */
473
+ function totalsIn(load, entries, tile, on, press, w) {
474
+ const expected = new SortedMap(undefined, compareFor(DateTimeType));
475
+ const sameOn = equalFor(load.type.key.fields.ik.fields.on);
476
+ const before = compareFor(DateTimeType);
477
+ for (const [entry, totals] of entries) {
478
+ if (!sameOn(entry.ik.on, on) || !equalFor(StringType)(entry.ik.key, press))
479
+ continue;
480
+ const after = nextOf(variant(tile, null), entry.ik.tile);
481
+ if (before(w.from, w.to) < 0 && before(entry.ik.tile, w.to) < 0 && before(after, w.from) > 0)
482
+ expected.set(entry.ik.tile, totals);
483
+ }
484
+ return expected;
485
+ }
486
+ it('totals: each tile of a key that overlaps a window, with its totals and its start', () => {
487
+ const load = input.press_load;
488
+ const totals = East.compile(East.function([load.type, StringType, DateTimeType, DateTimeType], Totals, ($, entries, press, from, to) => load.read(entries).totals({ key: press, from, to }).collect($)), []);
489
+ let tiles = 0;
490
+ for (const w of WINDOWS) {
491
+ for (const press of PRESSES) {
492
+ const expected = totalsIn(load, held.press_load, 'week', {}, press, w);
493
+ tiles += expected.size;
494
+ assertEast(Totals, totals(held.press_load, press, w.from, w.to), expected, `the load on ${press} in ${window(w)}`);
495
+ }
496
+ }
497
+ assert.ok(tiles > 500, `the windows hold tiles to read: ${tiles}`);
498
+ });
499
+ it('totals: under each leading field, exactly', () => {
500
+ const load = input.press_load_by_state;
501
+ const totals = East.compile(East.function([load.type, StringType, StringType, DateTimeType, DateTimeType], Totals, ($, entries, state, press, from, to) => load.read(entries).totals({ on: { state }, key: press, from, to }).collect($)), []);
502
+ for (const w of WINDOWS.slice(0, 20)) {
503
+ assertEast(Totals, totals(held.press_load_by_state, 'confirmed', 'P-1003', w.from, w.to), totalsIn(load, held.press_load_by_state, 'month', { state: 'confirmed' }, 'P-1003', w), `the confirmed load on P-1003 in ${window(w)}`);
504
+ }
505
+ });
506
+ });
507
+ // ── Area and entries indexes ─────────────────────────────────────────────────
508
+ /** A rack on a floor: its zone, its place — its box's centre — or none yet, and its size, in metres. */
509
+ const RackRow = StructType({ zone: StringType, x: OptionType(FloatType), y: OptionType(FloatType), w: FloatType, h: FloatType, name: StringType });
510
+ const RacksType = DictType(StringType, RackRow);
511
+ const racks = record('racks', RacksType, {
512
+ initial: new Map(),
513
+ indexes: (index) => ({
514
+ by_area: index.area({ x: 'x', y: 'y', width: 'w', height: 'h', at: 'centre', cell: 0.01 }),
515
+ by_zone_area: index.area({ on: ['zone'], x: 'x', y: 'y', width: 'w', height: 'h', cell: 0.5 }),
516
+ points: index.area({ x: 'x', y: 'y', cell: 0.01 }),
517
+ }),
518
+ });
519
+ /** A marker on a floor, always placed: a point. */
520
+ const MarkRow = StructType({ x: FloatType, y: FloatType });
521
+ const marks = record('marks', DictType(StringType, MarkRow), { initial: new Map(), indexes: (index) => ({ marks_by_area: index.area({ x: 'x', y: 'y', cell: 1 }) }) });
522
+ const ZONES = ['inbound', 'storage', 'dispatch'];
523
+ /** The racks the readers read: across a floor of a hundred metres by sixty, a fifth of a metre to thirty wide; some not
524
+ * yet placed, and the ones an index files under its root: outside its domain, wider than half of it, and not finite. */
525
+ function seededRacks() {
526
+ const draw = seededStream(1385);
527
+ const rows = new SortedMap(undefined, keyOrder);
528
+ const rack = (n, x, y, w, h) => decodeBeast2For(RackRow)(encodeBeast2For(RackRow)({ zone: ZONES[n % 3], x: x === undefined ? none : some(x), y: y === undefined ? none : some(y), w, h, name: `Rack ${n}` }));
529
+ for (let n = 0; n < 600; n++) {
530
+ const size = n % 25 === 0 ? 5 + draw() * 25 : 0.2 + draw() * 2;
531
+ const key = `R-${String(n).padStart(4, '0')}`;
532
+ if (n % 40 === 13)
533
+ rows.set(key, rack(n, undefined, undefined, size, size));
534
+ else
535
+ rows.set(key, rack(n, draw() * 100, draw() * 60, size, n % 3 === 0 ? size : size / 2));
536
+ }
537
+ rows.set('E-touches', rack(0, 51, 30, 2, 2));
538
+ rows.set('E-outside-the-domain', rack(0, 5_000_000, 10, 1, 1));
539
+ rows.set('E-half-placed', rack(0, 10, undefined, 1, 1));
540
+ rows.set('E-wider-than-the-domain', rack(0, 50, 30, 3_000_000, 1));
541
+ rows.set('E-not-finite', rack(0, Infinity, 30, 1, 1));
542
+ return rows;
543
+ }
544
+ const RACKS = seededRacks();
545
+ /** The windows the area readers read: a rack's own, a room, the floor, one past it, a point, and seeded ones. */
546
+ function areaWindows() {
547
+ const draw = seededStream(266);
548
+ const out = [
549
+ { x: 40, y: 20, width: 10, height: 10 },
550
+ { x: 0, y: 0, width: 100, height: 60 },
551
+ { x: -1_000, y: -1_000, width: 10_000_000, height: 10_000_000 },
552
+ { x: 52, y: 20, width: 5, height: 20 },
553
+ { x: 50, y: 30, width: 0, height: 0 },
554
+ { x: 10, y: 10, width: -1, height: 5 },
555
+ { x: 4_999_990, y: 0, width: 20, height: 20 },
556
+ ];
557
+ for (let n = 0; n < 40; n++) {
558
+ const side = n % 4 === 0 ? 0.5 + draw() * 2 : 2 + draw() ** 2 * 80;
559
+ out.push({ x: draw() * 110 - 5, y: draw() * 70 - 5, width: side, height: side * (0.3 + draw()) });
560
+ }
561
+ return out;
562
+ }
563
+ const AREA_WINDOWS = areaWindows();
564
+ /** The racks of a zone, or of every zone, whose box meets a window, edges included: a loop over them all, the box by
565
+ * its centre or by its corner. */
566
+ const racksIn = (centred, sized) => East.compile(East.function([RacksType, OptionType(StringType), FloatType, FloatType, FloatType, FloatType], RacksType, ($, rows, zone, x, y, width, height) => rows.filter(($, rack) => {
567
+ $.if(East.less(width, 0.0).or(() => East.less(height, 0.0)), ($) => { $.return(false); });
568
+ $.if(zone.match({ none: () => false, some: (_$, z) => East.notEqual(rack.zone, z) }), ($) => { $.return(false); });
569
+ $.match(rack.x, {
570
+ some: ($, rx) => {
571
+ $.match(rack.y, {
572
+ some: ($, ry) => {
573
+ const w = $.const(sized ? rack.w : East.value(0.0));
574
+ const h = $.const(sized ? rack.h : East.value(0.0));
575
+ const minX = $.const(centred ? rx.subtract(w.divide(2.0)) : rx);
576
+ const minY = $.const(centred ? ry.subtract(h.divide(2.0)) : ry);
577
+ $.return(East.lessEqual(minX, x.add(width)).and(() => East.greaterEqual(minX.add(w), x))
578
+ .and(() => East.lessEqual(minY, y.add(height))).and(() => East.greaterEqual(minY.add(h), y)));
579
+ },
580
+ });
581
+ },
582
+ });
583
+ return false;
584
+ })), []);
585
+ describe('an area index\'s readers', () => {
586
+ const window = (w) => `${w.width} by ${w.height} at ${w.x}, ${w.y}`;
587
+ it('within: the rows whose box meets a window, each once with its row, for seeded windows — boxes by their centre', () => {
588
+ const byArea = index(racks.indexes.by_area);
589
+ const within = East.compile(East.function([byArea.type, FloatType, FloatType, FloatType, FloatType], RacksType, ($, entries, x, y, width, height) => byArea.read(entries).within({ x, y, width, height }).collect($)), []);
590
+ const counted = East.compile(East.function([byArea.type, FloatType, FloatType, FloatType, FloatType], IntegerType, ($, entries, x, y, width, height) => {
591
+ const given = $.let(0n);
592
+ byArea.read(entries).within({ x, y, width, height }).each($, ($) => { $.assign(given, given.add(1n)); });
593
+ return given;
594
+ }), []);
595
+ const held = entriesOf(racks, racks.indexes.by_area, RACKS);
596
+ const oracle = racksIn(true, true);
597
+ let rows = 0;
598
+ for (const w of AREA_WINDOWS) {
599
+ const expected = oracle(RACKS, none, w.x, w.y, w.width, w.height);
600
+ rows += expected.size;
601
+ assertEast(RacksType, within(held, w.x, w.y, w.width, w.height), expected, `the racks within ${window(w)}`);
602
+ assert.equal(counted(held, w.x, w.y, w.width, w.height), BigInt(expected.size), `each once within ${window(w)}`);
603
+ }
604
+ assert.ok(rows > 2000, `the windows hold racks to read: ${rows}`);
605
+ // The edges: a box that touches the window is in it; a row outside the domain, and one wider than it, are read from the root
606
+ const touching = within(held, 52, 20, 5, 20);
607
+ assert.equal(touching.has('E-touches'), true, 'a rack whose side is the window\'s edge');
608
+ assert.equal(within(held, 52.001, 20, 5, 20).has('E-touches'), false, 'and is out of one a millimetre on');
609
+ assert.equal(within(held, 4_999_990, 0, 20, 20).has('E-outside-the-domain'), true, 'a rack outside the index\'s domain');
610
+ assert.equal(touching.has('E-wider-than-the-domain'), true, 'a rack wider than half the domain');
611
+ assert.equal(touching.has('E-half-placed'), false, 'a rack with no y is not placed');
612
+ });
613
+ it('within: under each leading field, exactly — boxes by their corner', () => {
614
+ const byZone = index(racks.indexes.by_zone_area);
615
+ const within = East.compile(East.function([byZone.type, StringType, FloatType, FloatType, FloatType, FloatType], RacksType, ($, entries, zone, x, y, width, height) => byZone.read(entries).within({ on: { zone }, x, y, width, height }).collect($)), []);
616
+ const held = entriesOf(racks, racks.indexes.by_zone_area, RACKS);
617
+ const oracle = racksIn(false, true);
618
+ for (const w of AREA_WINDOWS) {
619
+ for (const zone of ZONES) {
620
+ assertEast(RacksType, within(held, zone, w.x, w.y, w.width, w.height), oracle(RACKS, some(zone), w.x, w.y, w.width, w.height), `the ${zone} racks within ${window(w)}`);
621
+ }
622
+ }
623
+ });
624
+ it('within: points, which have no size', () => {
625
+ const points = index(racks.indexes.points);
626
+ const within = East.compile(East.function([points.type, FloatType, FloatType, FloatType, FloatType], RacksType, ($, entries, x, y, width, height) => points.read(entries).within({ x, y, width, height }).collect($)), []);
627
+ const held = entriesOf(racks, racks.indexes.points, RACKS);
628
+ const oracle = racksIn(false, false);
629
+ for (const w of AREA_WINDOWS) {
630
+ assertEast(RacksType, within(held, w.x, w.y, w.width, w.height), oracle(RACKS, none, w.x, w.y, w.width, w.height), `the points within ${window(w)}`);
631
+ }
632
+ });
633
+ it('within: gives its rows as a walk of the index meets them — a cell before the cells inside it, along the curve', () => {
634
+ const byArea = index(racks.indexes.by_area);
635
+ const inOrder = East.compile(East.function([byArea.type, FloatType, FloatType, FloatType, FloatType], ArrayType(StringType), ($, entries, x, y, width, height) => {
636
+ const keys = $.let([], ArrayType(StringType));
637
+ byArea.read(entries).within({ x, y, width, height }).each($, ($, _rack, key) => { $(keys.pushLast(key)); });
638
+ return keys;
639
+ }), []);
640
+ const held = entriesOf(racks, racks.indexes.by_area, RACKS);
641
+ const filed = [...held.keys()];
642
+ let rows = 0;
643
+ for (const w of AREA_WINDOWS) {
644
+ const given = inOrder(held, w.x, w.y, w.width, w.height);
645
+ rows += given.length;
646
+ assert.ok(inIndexOrder(StringType, filed, (entry) => entry.k, given), `the racks within ${window(w)} come in the index's order`);
647
+ }
648
+ assert.ok(rows > 2000, `the windows hold racks to read: ${rows}`);
649
+ });
650
+ it('within: a zero is one edge whatever its sign — a window\'s width, its corner, and a box\'s own', () => {
651
+ const byArea = index(racks.indexes.by_area);
652
+ const within = East.compile(East.function([byArea.type, FloatType, FloatType, FloatType, FloatType], RacksType, ($, entries, x, y, width, height) => byArea.read(entries).within({ x, y, width, height }).collect($)), []);
653
+ const held = entriesOf(racks, racks.indexes.by_area, RACKS);
654
+ // A window of no width and no height, each written as the zero below zero
655
+ const point = within(held, 50, 30, 0, 0);
656
+ assert.ok(point.has('E-touches'), 'a rack holds the point');
657
+ assertEast(RacksType, within(held, 50, 30, -0, -0), point, 'a window whose width and height are -0.0');
658
+ // A box at the zero below zero, of that width, by its corner: it touches a window that starts at zero
659
+ const byZone = index(racks.indexes.by_zone_area);
660
+ const inZone = East.compile(East.function([byZone.type, FloatType, FloatType, FloatType, FloatType], RacksType, ($, entries, x, y, width, height) => byZone.read(entries).within({ on: { zone: 'inbound' }, x, y, width, height }).collect($)), []);
661
+ const edge = new SortedMap(undefined, keyOrder);
662
+ edge.set('E-at-zero', decodeBeast2For(RackRow)(encodeBeast2For(RackRow)({ zone: 'inbound', x: some(-0), y: some(-0), w: -0, h: -0, name: 'At the corner' })));
663
+ edge.set('E-to-zero', decodeBeast2For(RackRow)(encodeBeast2For(RackRow)({ zone: 'inbound', x: some(-4), y: some(-4), w: 4, h: 4, name: 'Up to the corner' })));
664
+ const filedEdge = entriesOf(racks, racks.indexes.by_zone_area, edge);
665
+ for (const [x, y] of [[0, 0], [-0, -0], [0, -0]]) {
666
+ assertEast(RacksType, inZone(filedEdge, x, y, 5, 5), edge, `both touch a window from ${Object.is(x, -0) ? '-0.0' : '0.0'}, ${Object.is(y, -0) ? '-0.0' : '0.0'}`);
667
+ assertEast(RacksType, inZone(filedEdge, x, y, -0, -0), edge, 'and a window that is that point alone');
668
+ }
669
+ });
670
+ it('within: refuses a window that is not finite, as it runs', () => {
671
+ const byArea = index(racks.indexes.by_area);
672
+ const within = East.compile(East.function([byArea.type, FloatType], IntegerType, ($, entries, width) => byArea.read(entries).within({ x: 0, y: 0, width, height: 1 }).collect($).size()), []);
673
+ const held = entriesOf(racks, racks.indexes.by_area, RACKS);
674
+ assert.throws(() => within(held, Infinity), /e3\.index 'racks\.by_area' within: a window's x, y, width and height are finite numbers/);
675
+ assert.throws(() => within(held, NaN), /are finite numbers/);
676
+ });
677
+ it('unplaced: the rows with no place', () => {
678
+ const byArea = index(racks.indexes.by_area);
679
+ const unplaced = East.compile(East.function([byArea.type], DictType(StringType, StringType), ($, entries) => {
680
+ const names = $.let(new Map(), DictType(StringType, StringType));
681
+ byArea.read(entries).unplaced().each($, ($, rack, key) => { $(names.insert(key, rack.name)); });
682
+ return names;
683
+ }), []);
684
+ const expected = new SortedMap([...RACKS].filter(([, rack]) => rack.x.type === 'none' || rack.y.type === 'none').map(([key, rack]) => [key, rack.name]), keyOrder);
685
+ assert.ok(expected.size > 10);
686
+ assertEast(DictType(StringType, StringType), unplaced(entriesOf(racks, racks.indexes.by_area, RACKS)), expected, 'the racks not yet placed');
687
+ const byZone = index(racks.indexes.by_zone_area);
688
+ const inZone = East.compile(East.function([byZone.type, StringType], IntegerType, ($, entries, zone) => byZone.read(entries).unplaced({ on: { zone } }).collect($).size()), []);
689
+ assert.equal(inZone(entriesOf(racks, racks.indexes.by_zone_area, RACKS), 'storage'), BigInt([...RACKS.values()].filter((rack) => rack.zone === 'storage' && (rack.x.type === 'none' || rack.y.type === 'none')).length));
690
+ });
691
+ });
692
+ describe('an entries index\'s readers', () => {
693
+ /** A station: its name, and the parcels it handled, by service. */
694
+ const StationRow = StructType({ name: StringType, byService: DictType(StringType, IntegerType) });
695
+ const StationsType = DictType(StringType, StationRow);
696
+ const stations = record('stations', StationsType, { initial: new Map(), indexes: (index) => ({ by_service: index.entries('byService') }) });
697
+ const SERVICES = ['economy', 'express', 'freight', 'returns'];
698
+ const rows = new SortedMap(undefined, keyOrder);
699
+ for (let n = 0; n < 120; n++) {
700
+ const handled = new SortedMap(SERVICES.filter((_service, at) => (n + at) % 3 !== 0).map((service, at) => [service, BigInt(n * 10 + at)]), keyOrder);
701
+ rows.set(`S-${String(n).padStart(3, '0')}`, decodeBeast2For(StationRow)(encodeBeast2For(StationRow)({ name: `Station ${n}`, byService: handled })));
702
+ }
703
+ it('of: a key\'s entry on every row that holds one, with its value', () => {
704
+ const byService = index(stations.indexes.by_service);
705
+ const of = East.compile(East.function([byService.type, StringType], DictType(StringType, IntegerType), ($, entries, service) => byService.read(entries).of(service).collect($)), []);
706
+ const held = entriesOf(stations, stations.indexes.by_service, rows);
707
+ for (const service of [...SERVICES, 'overnight']) {
708
+ const expected = new SortedMap([...rows].flatMap(([key, station]) => {
709
+ const parcels = station.byService.get(service);
710
+ return parcels === undefined ? [] : [[key, parcels]];
711
+ }), keyOrder);
712
+ assertEast(DictType(StringType, IntegerType), of(held, service), expected, `the stations' ${service} parcels`);
713
+ }
714
+ });
715
+ it('reads its lean rows as a plain index: each row by its key, its field emptied', () => {
716
+ const lean = index(stations.indexes.by_service.entries.rows);
717
+ const named = East.compile(East.function([lean.type, StringType, StringType], DictType(StringType, StringType), ($, entries, from, to) => {
718
+ const names = $.let(new Map(), DictType(StringType, StringType));
719
+ lean.read(entries).between({ from, to }).each($, ($, station, key) => {
720
+ $.if(East.equal(station.byService.size(), 0n), ($) => { $(names.insert(key, station.name)); });
721
+ });
722
+ return names;
723
+ }), []);
724
+ const expected = new SortedMap([...rows].filter(([key]) => key >= 'S-010' && key < 'S-020').map(([key, station]) => [key, station.name]), keyOrder);
725
+ assertEast(DictType(StringType, StringType), named(entriesOf(stations, stations.indexes.by_service.entries.rows, rows), 'S-010', 'S-020'), expected, 'ten stations, lean');
726
+ });
727
+ it('reads a nested series index\'s span as a plain index, giving each tile\'s key in a row\'s key\'s place', () => {
728
+ const Machine = StructType({ name: StringType, load: DictType(DateTimeType, FloatType) });
729
+ const machines = record('machines', DictType(StringType, Machine), {
730
+ initial: new Map(),
731
+ indexes: (index) => ({ machines_in_time: index.nested({ collections: { load: index.nested.values() }, tile: 'week', summary: 'month' }) }),
732
+ });
733
+ const fleet = new SortedMap(undefined, keyOrder);
734
+ for (let n = 0; n < 6; n++) {
735
+ const load = new SortedMap(Array.from({ length: 5 }, (_, day) => [instant(OCT_5 + BigInt(n * 20 + day) * DAY), n + day / 10]), compareFor(DateTimeType));
736
+ fleet.set(`M-${n}`, decodeBeast2For(Machine)(encodeBeast2For(Machine)({ name: `Machine ${n}`, load })));
737
+ }
738
+ const span = index(machines.indexes.machines_in_time.nested.span);
739
+ const SpanKey = span.index.keyType;
740
+ const months = East.compile(East.function([span.type], DictType(SpanKey, RecordSummaryTotalsType), ($, entries) => span.read(entries).of({ collection: variant('step', { key: 'load', rest: variant('end', null) }) }).collect($)), []);
741
+ const read = months(entriesOf(machines, machines.indexes.machines_in_time.nested.span, fleet));
742
+ // The fleet's values run from October into January: a month's entry counts the values in it, across the machines
743
+ assert.ok(read.size >= 3, `the months the load touches: ${read.size}`);
744
+ assert.equal([...read.values()].reduce((sum, totals) => sum + totals.count, 0n), 30n, 'every value counted once, in its month');
745
+ assert.ok([...read.keys()].every((key) => key.collection.type === 'step'), 'each under the collection\'s place');
746
+ });
747
+ it('refuses a key that is not the field\'s, where the reader is called', () => {
748
+ const byService = index(stations.indexes.by_service);
749
+ assert.throws(() => East.function([byService.type], NullType, (_$, entries) => { byService.read(entries).of(7n); return null; }));
750
+ });
751
+ });
752
+ // ── A nested series index ────────────────────────────────────────────────────
753
+ /** A check on a team: its note, and the instant it was made. */
754
+ const CheckRow = StructType({ note: StringType, at: DateTimeType });
755
+ const ChecksType = DictType(StringType, CheckRow);
756
+ const HoursType = DictType(DateTimeType, FloatType);
757
+ const NotesType = DictType(DateTimeType, StringType);
758
+ /** A team of a yard: its jobs, its checks, the hours it logged, a value a day, and the teams within it, to any depth. */
759
+ const TeamRow = RecursiveType((self) => StructType({
760
+ name: StringType, jobs: JobsType, checks: ChecksType, hours: HoursType, teams: DictType(StringType, self),
761
+ }));
762
+ /** A yard: its visits, its notes, each at an instant, and its teams. */
763
+ const YardRow = StructType({ name: StringType, visits: JobsType, notes: NotesType, teams: DictType(StringType, TeamRow) });
764
+ const YardsType = DictType(StringType, YardRow);
765
+ const yards = record('yards', YardsType, {
766
+ initial: new Map(),
767
+ indexes: (index) => ({
768
+ yards_in_time: index.nested({
769
+ collections: {
770
+ visits: index.nested.items({ from: 'start', to: 'end' }),
771
+ notes: index.nested.values(),
772
+ teams: index.nested.rows({
773
+ jobs: index.nested.items({ from: 'start', to: 'end' }, { rollup: true }),
774
+ checks: index.nested.items({ at: 'at' }),
775
+ hours: index.nested.values({ rollup: ['sum', { fold: 'last', aggregate: 'max' }] }),
776
+ teams: index.nested.recursive(),
777
+ }),
778
+ },
779
+ tile: 'week',
780
+ summary: 'month',
781
+ }),
782
+ }),
783
+ });
784
+ /** A team with none within it, which logs hours. */
785
+ const CREW = { hours: true, teams: {} };
786
+ /** A yard's teams: two, two within each, and one more within the first of those. */
787
+ const teamSeeds = (second) => ({
788
+ 'T-1': { hours: false, teams: { 'T-1a': { hours: false, teams: { 'T-1a-i': CREW } }, 'T-1b': CREW } },
789
+ // In the second yard this team logs hours of its own: it draws them, and keeps no subtotal of the teams within it.
790
+ 'T-2': { hours: second, teams: { 'T-2a': CREW, 'T-2b': CREW } },
791
+ });
792
+ /** The seeded jobs the first yard's visits and its deepest team's jobs hold whatever else they are dealt: the edges, by name. */
793
+ const EDGES = [
794
+ 'E-ends-at-from', 'E-instant-at-from', 'E-instant-at-to', 'E-starts-at-to', 'E-no-end', 'E-no-start', 'E-ends-before-start',
795
+ 'E-past-a-year', 'E-a-millisecond-in',
796
+ ];
797
+ const instantOrder = compareFor(DateTimeType);
798
+ /**
799
+ * The yards the nested readers read: the seeded jobs dealt out among each
800
+ * yard's visits and each of its teams' jobs; checks and notes at seeded
801
+ * instants, and at the edges of the week from Monday 12 October; and a value a
802
+ * day, most days from August to the year's end, for each team that logs hours.
803
+ */
804
+ function seededYards() {
805
+ const draw = seededStream(1434);
806
+ const dealt = [];
807
+ const hand = () => {
808
+ const held = new SortedMap(undefined, keyOrder);
809
+ dealt.push(held);
810
+ return held;
811
+ };
812
+ const instants = (count) => [
813
+ ...Array.from({ length: count }, () => instant(OCT_5 + BigInt(Math.floor((draw() - 0.5) * 400)) * DAY + BigInt(Math.floor(draw() * 24)) * HOUR)),
814
+ at('2026-10-12T00:00:00.000'), at('2026-10-19T00:00:00.000'),
815
+ ];
816
+ const team = (key, seed) => ({
817
+ name: `Team ${key}`,
818
+ jobs: hand(),
819
+ checks: new SortedMap(instants(15).map((made, n) => [`C-${String(n).padStart(2, '0')}`, { note: `Check ${n}`, at: made }]), keyOrder),
820
+ // Quarters of an hour, so a sum is exact in whatever order it is added.
821
+ hours: new SortedMap(seed.hours
822
+ ? Array.from({ length: 150 }, (_, day) => [instant(OCT_5 + BigInt(day - 60) * DAY + 6n * HOUR), Math.floor(draw() * 64) / 4]).filter(() => draw() > 0.2)
823
+ : [], instantOrder),
824
+ teams: new SortedMap(Object.entries(seed.teams).map(([below, within]) => [below, team(below, within)]), keyOrder),
825
+ });
826
+ const rows = new SortedMap(undefined, keyOrder);
827
+ for (const [key, seeds] of [['Y-1', teamSeeds(false)], ['Y-2', teamSeeds(true)]]) {
828
+ rows.set(key, {
829
+ name: `Yard ${key}`,
830
+ visits: hand(),
831
+ notes: new SortedMap(instants(25).map((made, n) => [made, `Note ${n}`]), instantOrder),
832
+ teams: new SortedMap(Object.entries(seeds).map(([below, within]) => [below, team(below, within)]), keyOrder),
833
+ });
834
+ }
835
+ let n = 0;
836
+ for (const [key, row] of ROWS)
837
+ dealt[n++ % dealt.length].set(key, row);
838
+ // The first yard's visits are dealt first, and its deepest team's jobs fourth: T-1, T-1a, then T-1a-i.
839
+ for (const name of EDGES) {
840
+ const row = ROWS.get(name);
841
+ assert.ok(row !== undefined, `the seeded jobs hold ${name}`);
842
+ dealt[0].set(name, row);
843
+ dealt[3].set(name, row);
844
+ }
845
+ return decodeBeast2For(YardsType)(encodeBeast2For(YardsType)(rows));
846
+ }
847
+ const YARDS = seededYards();
848
+ /** Every team beneath some teams, each with the keys from them down to it. */
849
+ function teamsBeneath(teams, path = []) {
850
+ return [...teams].flatMap(([key, team]) => [{ path: [...path, key], team }, ...teamsBeneath(team.teams, [...path, key])]);
851
+ }
852
+ /** Every team of every yard, by its yard and the keys from the yard down. */
853
+ const TEAMS = [...YARDS].flatMap(([yard, row]) => teamsBeneath(row.teams).map((found) => ({ yard, ...found })));
854
+ const PathType = ArrayType(StringType);
855
+ /** The index's ids (#1540): a team's key under `teams`, a job's id under `teams.jobs`, each in its own type. */
856
+ const YardIdType = yards.indexes.yards_in_time.keyType.fields.path.node.cases.step.fields.key;
857
+ /** A node's keys as a reader is given them: each team's key an id of the index's, under the teams' case. */
858
+ const teamIds = (path) => path.map((_$, key) => East.value(variant('teams', key), YardIdType));
859
+ const MonthTotals = DictType(DateTimeType, RecordNestedTotalsType);
860
+ const TileFloats = DictType(DateTimeType, FloatType);
861
+ /** An item of a subtree, as the yards' index names it: the teams' keys down to the team holding it, and its id. */
862
+ const UnderType = NestedUnderType(yards.indexes.yards_in_time);
863
+ const BeneathType = DictType(UnderType, JobRow);
864
+ // The plain tests, each a loop over what a node holds
865
+ /** A node's checks made in `[from, to)`. */
866
+ const checksIn = East.compile(East.function([ChecksType, DateTimeType, DateTimeType], ChecksType, (_$, checks, from, to) => checks.filter((_$, check) => East.greaterEqual(check.at, from).and(() => East.less(check.at, to)))), []);
867
+ /** A node's hours logged in `[from, to)`. */
868
+ const hoursIn = East.compile(East.function([HoursType, DateTimeType, DateTimeType], HoursType, (_$, hours, from, to) => hours.filter((_$, _value, logged) => East.greaterEqual(logged, from).and(() => East.less(logged, to)))), []);
869
+ /** A yard's notes made in `[from, to)`. */
870
+ const notesIn = East.compile(East.function([NotesType, DateTimeType, DateTimeType], NotesType, (_$, notes, from, to) => notes.filter((_$, _note, made) => East.greaterEqual(made, from).and(() => East.less(made, to)))), []);
871
+ /**
872
+ * Some jobs' totals a month: for each month that overlaps a window, how many
873
+ * of them touch it and the milliseconds of it they cover — a loop over them
874
+ * all, a month at a time.
875
+ */
876
+ const jobMonths = East.compile(East.function([ArrayType(JobRow), DateTimeType, DateTimeType], MonthTotals, ($, jobs, from, to) => {
877
+ const months = $.let(new Map(), MonthTotals);
878
+ $.if(East.less(from, to), ($) => {
879
+ const startOf = $.const(TILE_FNS.tileStart);
880
+ const nextOf = $.const(TILE_FNS.tileNext);
881
+ const month = $.const(variant('month', null), RecordLevelType);
882
+ const tile = $.let(startOf(month, from));
883
+ $.while(East.less(tile, to), ($) => {
884
+ const next = $.const(nextOf(month, tile));
885
+ const count = $.let(0n);
886
+ const ms = $.let(0n);
887
+ $.for(jobs, ($, job) => {
888
+ $.match(job.start, {
889
+ some: ($, start) => {
890
+ const end = $.const(job.end.unwrap('some', () => start));
891
+ // An instant touches the month it is in, and covers none of it.
892
+ $.if(East.lessEqual(end, start).and(() => East.greaterEqual(start, tile)).and(() => East.less(start, next)), ($) => {
893
+ $.assign(count, count.add(1n));
894
+ });
895
+ $.if(East.greater(end, start).and(() => East.less(start, next)).and(() => East.greater(end, tile)), ($) => {
896
+ $.assign(count, count.add(1n));
897
+ $.assign(ms, ms.add(East.min(end, next).toEpochMilliseconds().subtract(East.max(start, tile).toEpochMilliseconds())));
898
+ });
899
+ },
900
+ });
901
+ });
902
+ $.if(East.greater(count, 0n), ($) => { $(months.insert(tile, { count, ms, values: none })); });
903
+ $.assign(tile, next);
904
+ });
905
+ });
906
+ return months;
907
+ }), []);
908
+ /** Some instants' totals a month: for each month that overlaps a window, how many are in it. */
909
+ const instantMonths = East.compile(East.function([ArrayType(DateTimeType), DateTimeType, DateTimeType], MonthTotals, ($, instants, from, to) => {
910
+ const months = $.let(new Map(), MonthTotals);
911
+ $.if(East.less(from, to), ($) => {
912
+ const startOf = $.const(TILE_FNS.tileStart);
913
+ const nextOf = $.const(TILE_FNS.tileNext);
914
+ const month = $.const(variant('month', null), RecordLevelType);
915
+ const tile = $.let(startOf(month, from));
916
+ $.while(East.less(tile, to), ($) => {
917
+ const next = $.const(nextOf(month, tile));
918
+ const count = $.let(0n);
919
+ $.for(instants, ($, made) => {
920
+ $.if(East.greaterEqual(made, tile).and(() => East.less(made, next)), ($) => { $.assign(count, count.add(1n)); });
921
+ });
922
+ $.if(East.greater(count, 0n), ($) => { $(months.insert(tile, { count, ms: 0n, values: none })); });
923
+ $.assign(tile, next);
924
+ });
925
+ });
926
+ return months;
927
+ }), []);
928
+ /** A node's hours' totals a month: how many, their sum, the least, the greatest and the latest, taken in the order logged. */
929
+ const hourMonths = East.compile(East.function([HoursType, DateTimeType, DateTimeType], MonthTotals, ($, hours, from, to) => {
930
+ const months = $.let(new Map(), MonthTotals);
931
+ $.if(East.less(from, to), ($) => {
932
+ const startOf = $.const(TILE_FNS.tileStart);
933
+ const nextOf = $.const(TILE_FNS.tileNext);
934
+ const month = $.const(variant('month', null), RecordLevelType);
935
+ const tile = $.let(startOf(month, from));
936
+ $.while(East.less(tile, to), ($) => {
937
+ const next = $.const(nextOf(month, tile));
938
+ const count = $.let(0n);
939
+ const sum = $.let(0.0);
940
+ const least = $.let(0.0);
941
+ const greatest = $.let(0.0);
942
+ const last = $.let(0.0);
943
+ $.for(hours, ($, value, logged) => {
944
+ $.if(East.greaterEqual(logged, tile).and(() => East.less(logged, next)), ($) => {
945
+ $.assign(least, East.equal(count, 0n).ifElse(() => value, () => East.min(least, value)));
946
+ $.assign(greatest, East.equal(count, 0n).ifElse(() => value, () => East.max(greatest, value)));
947
+ $.assign(sum, sum.add(value));
948
+ $.assign(last, value);
949
+ $.assign(count, count.add(1n));
950
+ });
951
+ });
952
+ $.if(East.greater(count, 0n), ($) => { $(months.insert(tile, { count, ms: 0n, values: some({ sum, min: least, max: greatest, last }) })); });
953
+ $.assign(tile, next);
954
+ });
955
+ });
956
+ return months;
957
+ }), []);
958
+ /** Some Floats' sum, added in order. */
959
+ const totalOf = East.compile(East.function([ArrayType(FloatType)], FloatType, (_$, values) => values.reduce((_$, sum, value) => sum.add(value), 0.0)), []);
960
+ /** The greatest of some Floats, of which there is one at least. */
961
+ const greatestOf = East.compile(East.function([ArrayType(FloatType)], FloatType, (_$, values) => values.reduce((_$, most, value) => East.max(most, value), values.get(0n))), []);
962
+ /** A node's teams' keys as the index's key holds them: a path, each key under the teams' case. */
963
+ const pathOf = (path) => path.reduceRight((rest, key) => variant('step', { key: variant('teams', key), rest }), variant('end', null));
964
+ const tileStartOf = East.compile(TILE_FNS.tileStart, []);
965
+ const tileNextOf = East.compile(TILE_FNS.tileNext, []);
966
+ /** The tiles of a level that overlap a window, each with the start of the one after it. */
967
+ function tilesIn(level, from, to) {
968
+ const tiles = [];
969
+ if (instantOrder(from, to) >= 0)
970
+ return tiles;
971
+ for (let tile = tileStartOf(variant(level, null), from); instantOrder(tile, to) < 0; tile = tileNextOf(variant(level, null), tile)) {
972
+ tiles.push({ tile, next: tileNextOf(variant(level, null), tile) });
973
+ }
974
+ return tiles;
975
+ }
976
+ /** What some teams draw in a tile, aggregated; none where none of them draws. */
977
+ function gathered(draws, rollup) {
978
+ const held = draws.flatMap((draw) => (draw === undefined ? [] : [draw]));
979
+ if (held.length === 0)
980
+ return undefined;
981
+ return rollup.aggregate === 'sum' ? totalOf(held) : greatestOf(held);
982
+ }
983
+ /**
984
+ * What a team draws of its hours in a tile by a rollup: its own in the tile,
985
+ * folded, where it logs any at all; else what the teams within it draw,
986
+ * aggregated.
987
+ */
988
+ function drawn(team, tile, next, rollup) {
989
+ if (team.hours.size === 0)
990
+ return gathered([...team.teams.values()].map((within) => drawn(within, tile, next, rollup)), rollup);
991
+ const logged = [...hoursIn(team.hours, tile, next).values()];
992
+ if (logged.length === 0)
993
+ return undefined;
994
+ return rollup.fold === 'sum' ? totalOf(logged) : logged[logged.length - 1];
995
+ }
996
+ describe('a nested series index\'s readers', () => {
997
+ const inTime = index(yards.indexes.yards_in_time);
998
+ const held = entriesOf(yards, yards.indexes.yards_in_time, YARDS);
999
+ const WINDOW = [inTime.type, StringType, PathType, DateTimeType, DateTimeType];
1000
+ /** A node, as a failure names it. */
1001
+ const node = (yard, path) => [yard, ...path].join(' › ');
1002
+ it('items: a node\'s own items that overlap a window, each once with its id, at every level it files at, for seeded windows', () => {
1003
+ const jobsOf = East.compile(East.function([...WINDOW], JobsType, ($, entries, yard, path, from, to) => inTime.read(entries).items({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).collect($)), []);
1004
+ let given = 0;
1005
+ for (const { yard, path, team } of TEAMS) {
1006
+ for (const w of WINDOWS) {
1007
+ const expected = jobsIn(team.jobs, none, none, w.from, w.to);
1008
+ given += expected.size;
1009
+ assertEast(JobsType, jobsOf(held, yard, path, w.from, w.to), expected, `the jobs of ${node(yard, path)} in ${window(w)}`);
1010
+ }
1011
+ }
1012
+ assert.ok(given > 2000, `the windows hold jobs to read: ${given}`);
1013
+ // The row's own, its path left out
1014
+ const visitsOf = East.compile(East.function([inTime.type, StringType, DateTimeType, DateTimeType], JobsType, ($, entries, yard, from, to) => inTime.read(entries).items({ collection: ['visits'], row: yard, from, to }).collect($)), []);
1015
+ for (const [yard, row] of YARDS) {
1016
+ for (const w of WINDOWS)
1017
+ assertEast(JobsType, visitsOf(held, yard, w.from, w.to), jobsIn(row.visits, none, none, w.from, w.to), `the visits to ${yard} in ${window(w)}`);
1018
+ }
1019
+ });
1020
+ it('items: the window\'s edges, an item past a year once, and no row or node that is not there', () => {
1021
+ const idsOf = East.compile(East.function([...WINDOW], ArrayType(StringType), ($, entries, yard, path, from, to) => {
1022
+ const ids = $.let([], ArrayType(StringType));
1023
+ inTime.read(entries).items({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).each($, ($, _job, id) => { $(ids.pushLast(id)); });
1024
+ return ids;
1025
+ }), []);
1026
+ const deepest = ['T-1', 'T-1a', 'T-1a-i'];
1027
+ const week = idsOf(held, 'Y-1', deepest, at('2026-10-12T00:00:00.000'), at('2026-10-19T00:00:00.000'));
1028
+ const edges = new SortedSet(week.filter((id) => EDGES.some((name) => keyOrder(name, id) === 0)), keyOrder);
1029
+ assertEast(SetType(StringType), edges, new SortedSet(['E-instant-at-from', 'E-no-end', 'E-ends-before-start', 'E-past-a-year', 'E-a-millisecond-in'], keyOrder), 'the edges inside the week');
1030
+ // Two years hold the job past a year under each of three: a body is given it once
1031
+ const years = idsOf(held, 'Y-1', deepest, at('2025-06-01T00:00:00.000'), at('2027-06-01T00:00:00.000'));
1032
+ assert.equal(years.filter((id) => keyOrder(id, 'E-past-a-year') === 0).length, 1, 'a job past a year, once');
1033
+ assert.equal(new SortedSet(years, keyOrder).size, years.length, 'each job once');
1034
+ assert.deepEqual(idsOf(held, 'Y-9', deepest, at('2025-06-01T00:00:00.000'), at('2027-06-01T00:00:00.000')), [], 'no such yard');
1035
+ assert.deepEqual(idsOf(held, 'Y-1', ['T-1', 'T-9'], at('2025-06-01T00:00:00.000'), at('2027-06-01T00:00:00.000')), [], 'no such team');
1036
+ });
1037
+ it('items, subtree: give their rows as a walk of the index meets them — a run a level, in the index\'s order of its levels', () => {
1038
+ const filed = [...held.keys()];
1039
+ const idsOf = East.compile(East.function([...WINDOW], ArrayType(StringType), ($, entries, yard, path, from, to) => {
1040
+ const ids = $.let([], ArrayType(StringType));
1041
+ inTime.read(entries).items({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).each($, ($, _job, id) => { $(ids.pushLast(id)); });
1042
+ return ids;
1043
+ }), []);
1044
+ const beneathOf = East.compile(East.function([...WINDOW], ArrayType(UnderType), ($, entries, yard, path, from, to) => {
1045
+ const under = $.let([], ArrayType(UnderType));
1046
+ inTime.read(entries).subtree({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).each($, ($, _job, at) => { $(under.pushLast(at)); });
1047
+ return under;
1048
+ }), []);
1049
+ const samePath = equalFor(inTime.index.keyType.fields.path);
1050
+ const levels = new SortedSet(undefined, compareFor(RecordLevelType));
1051
+ let given = 0;
1052
+ for (const w of WINDOWS.slice(0, 12)) {
1053
+ for (const { yard, path } of TEAMS) {
1054
+ // The node's own entries of each run: its row, and the path down to it
1055
+ const ofNode = filed.filter((entry) => keyOrder(entry.ik.row, yard) === 0 && samePath(entry.ik.path, pathOf(path)));
1056
+ const own = idsOf(held, yard, path, w.from, w.to);
1057
+ const beneath = beneathOf(held, yard, path, w.from, w.to);
1058
+ given += own.length + beneath.length;
1059
+ // A job's id is held under its collection's case of the index's ids.
1060
+ const idOf = (entry) => entry.ik.item.type === 'id' ? entry.ik.item.value.value : undefined;
1061
+ for (const entry of ofNode)
1062
+ if (own.some((id) => idOf(entry) !== undefined && keyOrder(id, idOf(entry)) === 0))
1063
+ levels.add(entry.ik.level);
1064
+ assert.ok(inIndexOrder(StringType, ofNode, (entry) => entry.ik.run.type === 'items' ? idOf(entry) : undefined, own), `the jobs of ${node(yard, path)} in ${window(w)} come in the index's order`);
1065
+ assert.ok(inIndexOrder(UnderType, ofNode, (entry) => entry.ik.run.type === 'subtree' && entry.ik.item.type === 'under' ? entry.ik.item.value : undefined, beneath), `the jobs beneath ${node(yard, path)} in ${window(w)} come in the index's order`);
1066
+ }
1067
+ }
1068
+ assert.ok(given > 500, `the windows hold jobs to read: ${given}`);
1069
+ assert.ok(levels.size >= 4, `the windows read jobs filed at a week, a month, a quarter and a year: ${levels.size}`);
1070
+ });
1071
+ it('items: instants, by the instant each is at; and values, each with its instant', () => {
1072
+ const checksOf = East.compile(East.function([...WINDOW], ChecksType, ($, entries, yard, path, from, to) => inTime.read(entries).items({ collection: ['teams', 'checks'], row: yard, path: teamIds(path), from, to }).collect($)), []);
1073
+ const hoursOf = East.compile(East.function([...WINDOW], HoursType, ($, entries, yard, path, from, to) => inTime.read(entries).items({ collection: ['teams', 'hours'], row: yard, path: teamIds(path), from, to }).collect($)), []);
1074
+ let checks = 0;
1075
+ let hours = 0;
1076
+ for (const { yard, path, team } of TEAMS) {
1077
+ for (const w of WINDOWS) {
1078
+ const made = checksIn(team.checks, w.from, w.to);
1079
+ const logged = hoursIn(team.hours, w.from, w.to);
1080
+ checks += made.size;
1081
+ hours += logged.size;
1082
+ assertEast(ChecksType, checksOf(held, yard, path, w.from, w.to), made, `the checks of ${node(yard, path)} in ${window(w)}`);
1083
+ assertEast(HoursType, hoursOf(held, yard, path, w.from, w.to), logged, `the hours of ${node(yard, path)} in ${window(w)}`);
1084
+ }
1085
+ }
1086
+ assert.ok(checks > 500 && hours > 2000, `the windows hold checks and hours to read: ${checks}, ${hours}`);
1087
+ // A check at the window's first instant is inside it, and one at its end outside
1088
+ const week = checksOf(held, 'Y-1', ['T-2'], at('2026-10-12T00:00:00.000'), at('2026-10-19T00:00:00.000'));
1089
+ assert.ok(week.has('C-15') && !week.has('C-16'), 'the checks at the week\'s edges');
1090
+ // Values that are no numbers, on the row itself
1091
+ const notesOf = East.compile(East.function([inTime.type, StringType, DateTimeType, DateTimeType], NotesType, ($, entries, yard, from, to) => inTime.read(entries).items({ collection: ['notes'], row: yard, from, to }).collect($)), []);
1092
+ for (const [yard, row] of YARDS) {
1093
+ for (const w of WINDOWS)
1094
+ assertEast(NotesType, notesOf(held, yard, w.from, w.to), notesIn(row.notes, w.from, w.to), `the notes of ${yard} in ${window(w)}`);
1095
+ }
1096
+ });
1097
+ it('subtree: the items of every node beneath a node that overlap a window, each once, with the keys down to the node holding it', () => {
1098
+ const beneathOf = East.compile(East.function([...WINDOW], BeneathType, ($, entries, yard, path, from, to) => inTime.read(entries).subtree({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).collect($)), []);
1099
+ // The yards themselves, each team, and one with none within it
1100
+ const parents = [
1101
+ ...[...YARDS].map(([yard, row]) => ({ yard, path: [], teams: row.teams })),
1102
+ ...TEAMS.map(({ yard, path, team }) => ({ yard, path, teams: team.teams })),
1103
+ ];
1104
+ let given = 0;
1105
+ for (const { yard, path, teams } of parents) {
1106
+ for (const w of WINDOWS.slice(0, 30)) {
1107
+ const expected = new SortedMap(undefined, compareFor(UnderType));
1108
+ for (const within of teamsBeneath(teams)) {
1109
+ for (const [id, row] of jobsIn(within.team.jobs, none, none, w.from, w.to))
1110
+ expected.set({ path: pathOf(within.path), id: variant('teams.jobs', id) }, row);
1111
+ }
1112
+ given += expected.size;
1113
+ assertEast(BeneathType, beneathOf(held, yard, path, w.from, w.to), expected, `the jobs beneath ${node(yard, path)} in ${window(w)}`);
1114
+ }
1115
+ }
1116
+ assert.ok(given > 2000, `the windows hold jobs beneath to read: ${given}`);
1117
+ });
1118
+ it('totals, subtreeTotals: a node\'s totals a month, and those of the items beneath it, for each month that overlaps a window', () => {
1119
+ const totalsOf = (place) => East.compile(East.function([...WINDOW], MonthTotals, ($, entries, yard, path, from, to) => inTime.read(entries).totals({ collection: place, row: yard, path: teamIds(path), from, to }).collect($)), []);
1120
+ const jobTotals = totalsOf(['teams', 'jobs']);
1121
+ const checkTotals = totalsOf(['teams', 'checks']);
1122
+ const hourTotals = totalsOf(['teams', 'hours']);
1123
+ const beneathTotals = East.compile(East.function([...WINDOW], MonthTotals, ($, entries, yard, path, from, to) => inTime.read(entries).subtreeTotals({ collection: ['teams', 'jobs'], row: yard, path: teamIds(path), from, to }).collect($)), []);
1124
+ let months = 0;
1125
+ for (const { yard, path, team } of TEAMS) {
1126
+ for (const w of WINDOWS.slice(0, 30)) {
1127
+ const where = `${node(yard, path)} in ${window(w)}`;
1128
+ const expected = jobMonths([...team.jobs.values()], w.from, w.to);
1129
+ months += expected.size;
1130
+ assertEast(MonthTotals, jobTotals(held, yard, path, w.from, w.to), expected, `the jobs' months of ${where}`);
1131
+ assertEast(MonthTotals, checkTotals(held, yard, path, w.from, w.to), instantMonths([...team.checks.values()].map((check) => check.at), w.from, w.to), `the checks' months of ${where}`);
1132
+ assertEast(MonthTotals, hourTotals(held, yard, path, w.from, w.to), hourMonths(team.hours, w.from, w.to), `the hours' months of ${where}`);
1133
+ assertEast(MonthTotals, beneathTotals(held, yard, path, w.from, w.to), jobMonths(teamsBeneath(team.teams).flatMap((within) => [...within.team.jobs.values()]), w.from, w.to), `the months of the jobs beneath ${where}`);
1134
+ }
1135
+ }
1136
+ assert.ok(months > 1000, `the windows hold months to read: ${months}`);
1137
+ // The row's own collections, and what is beneath the row
1138
+ const rowTotals = (place) => East.compile(East.function([inTime.type, StringType, DateTimeType, DateTimeType], MonthTotals, ($, entries, yard, from, to) => inTime.read(entries).totals({ collection: place, row: yard, from, to }).collect($)), []);
1139
+ const visitTotals = rowTotals(['visits']);
1140
+ const noteTotals = rowTotals(['notes']);
1141
+ for (const [yard, row] of YARDS) {
1142
+ for (const w of WINDOWS.slice(0, 30)) {
1143
+ assertEast(MonthTotals, visitTotals(held, yard, w.from, w.to), jobMonths([...row.visits.values()], w.from, w.to), `the visits' months of ${yard} in ${window(w)}`);
1144
+ assertEast(MonthTotals, noteTotals(held, yard, w.from, w.to), instantMonths([...row.notes.keys()], w.from, w.to), `the notes' months of ${yard} in ${window(w)}`);
1145
+ assertEast(MonthTotals, beneathTotals(held, yard, [], w.from, w.to), jobMonths(teamsBeneath(row.teams).flatMap((within) => [...within.team.jobs.values()]), w.from, w.to), `the months of the jobs beneath ${yard} in ${window(w)}`);
1146
+ }
1147
+ }
1148
+ });
1149
+ it('subtotals: a parent\'s subtotals by a rollup at a level, for each tile that overlaps a window; none for a node that draws its own', () => {
1150
+ const rollups = [{ fold: 'sum', aggregate: 'sum' }, { fold: 'last', aggregate: 'max' }];
1151
+ const levels = ['week', 'month', 'quarter', 'year'];
1152
+ const parents = [
1153
+ ...[...YARDS].map(([yard, row]) => ({ yard, path: [], hours: 0, teams: row.teams })),
1154
+ ...TEAMS.map(({ yard, path, team }) => ({ yard, path, hours: team.hours.size, teams: team.teams })),
1155
+ ];
1156
+ let subtotals = 0;
1157
+ for (const rollup of rollups) {
1158
+ for (const level of levels) {
1159
+ const subtotalsOf = East.compile(East.function([...WINDOW], TileFloats, ($, entries, yard, path, from, to) => inTime.read(entries).subtotals({
1160
+ collection: ['teams', 'hours'], row: yard, path: teamIds(path), from, to, level,
1161
+ rollup: rollup.fold === 'sum' ? 'sum' : { fold: 'last', aggregate: 'max' },
1162
+ }).collect($)), []);
1163
+ for (const { yard, path, hours, teams } of parents) {
1164
+ for (const w of WINDOWS.slice(0, 12)) {
1165
+ const expected = new SortedMap(undefined, instantOrder);
1166
+ // A node that logs hours of its own draws them, and keeps no subtotal
1167
+ if (hours === 0) {
1168
+ for (const { tile, next } of tilesIn(level, w.from, w.to)) {
1169
+ const drew = gathered([...teams.values()].map((within) => drawn(within, tile, next, rollup)), rollup);
1170
+ if (drew !== undefined)
1171
+ expected.set(tile, drew);
1172
+ }
1173
+ }
1174
+ subtotals += expected.size;
1175
+ assertEast(TileFloats, subtotalsOf(held, yard, path, w.from, w.to), expected, `the ${rollup.fold} of hours a ${level} beneath ${node(yard, path)} in ${window(w)}`);
1176
+ }
1177
+ }
1178
+ }
1179
+ }
1180
+ assert.ok(subtotals > 500, `the windows hold subtotals to read: ${subtotals}`);
1181
+ // The level left out is the index's tile
1182
+ const weeks = East.compile(East.function([inTime.type, StringType, DateTimeType, DateTimeType], TileFloats, ($, entries, yard, from, to) => inTime.read(entries).subtotals({ collection: ['teams', 'hours'], row: yard, rollup: 'sum', from, to }).collect($)), []);
1183
+ const read = weeks(held, 'Y-1', at('2026-10-05T00:00:00.000'), at('2026-11-02T00:00:00.000'));
1184
+ assert.equal(read.size, 4, 'four weeks of October');
1185
+ });
1186
+ it('types what a read gives by the collection\'s place, and refuses a place the index does not file', () => {
1187
+ East.function([inTime.type, StringType, DateTimeType, DateTimeType], FloatType, ($, entries, yard, from, to) => {
1188
+ const readers = inTime.read(entries);
1189
+ const total = $.let(0.0);
1190
+ const latest = $.let(from);
1191
+ // A value is its collection's Float, at its instant; an item its struct, by its id
1192
+ readers.items({ collection: ['teams', 'hours'], row: yard, path: [variant('teams', 'T-1'), variant('teams', 'T-1b')], from, to }).each($, ($, hours, logged) => {
1193
+ $.assign(total, total.add(hours));
1194
+ $.assign(latest, logged);
1195
+ });
1196
+ readers.items({ collection: ['teams', 'jobs'], row: yard, path: [variant('teams', 'T-1')], from, to }).each($, ($, job, id) => {
1197
+ $.if(East.equal(id, 'W-0001'), ($) => { $.assign(total, total.add(job.sheets)); });
1198
+ });
1199
+ readers.subtree({ collection: ['teams', 'jobs'], row: yard, from, to }).each($, ($, job, under) => {
1200
+ $.if(East.equal(under.id, East.value(variant('teams.jobs', 'W-0001'), YardIdType)), ($) => { $.assign(total, total.add(job.sheets)); });
1201
+ });
1202
+ // @ts-expect-error — the index files no collection at ['teams']: its rows hold the collections
1203
+ assert.throws(() => readers.items({ collection: ['teams'], row: yard, from, to }), /items: the index files no collection at \["teams"\]/);
1204
+ // @ts-expect-error — nor at a field it does not name
1205
+ assert.throws(() => readers.totals({ collection: ['crews'], row: yard, from, to }), /totals: the index files no collection at \["crews"\]/);
1206
+ return total;
1207
+ });
1208
+ });
1209
+ it('refuses what the index does not keep, where the reader is called, naming what it does', () => {
1210
+ const over = (body) => () => East.function([inTime.type], NullType, (_$, entries) => { body(inTime.read(entries)); return null; });
1211
+ const from = at('2026-10-12T00:00:00.000');
1212
+ const to = at('2026-10-19T00:00:00.000');
1213
+ assert.throws(over((readers) => readers.items({ collection: ['teams', 'tasks'], row: 'Y-1', from, to })), /^Error: e3\.index 'yards\.yards_in_time' items: the index files no collection at \["teams","tasks"\] — it files \['notes'\], \['visits'\], \['teams', 'checks'\], \['teams', 'hours'\], \['teams', 'jobs'\], each by its field names from the row down$/);
1214
+ assert.throws(over((readers) => readers.items({ collection: ['visits'], from, to })), /items: `row` is left out — the key of the record's row the node is in/);
1215
+ assert.throws(over((readers) => readers.items({ collection: ['visits'], row: 'Y-1', from })), /items: `to` is left out — a window is \[from, to\), each a DateTime/);
1216
+ assert.throws(over((readers) => readers.subtree({ collection: ['visits'], row: 'Y-1', from, to })), /^Error: e3\.index 'yards\.yards_in_time' subtree: the collection at \['visits'\] is not rolled up, so no node holds the items beneath it — declare it index\.nested\.items\(times, \{ rollup: true \}\)$/);
1217
+ assert.throws(over((readers) => readers.subtreeTotals({ collection: ['teams', 'hours'], row: 'Y-1', from, to })), /subtreeTotals: the collection at \['teams', 'hours'\] is not rolled up/);
1218
+ assert.throws(over((readers) => readers.subtotals({ collection: ['teams', 'hours'], row: 'Y-1', rollup: 'mean', from, to })), /^Error: e3\.index 'yards\.yards_in_time' subtotals: the collection at \['teams', 'hours'\] keeps no subtotal by mean — it keeps sum, \{ fold: 'last', aggregate: 'max' \}$/);
1219
+ assert.throws(over((readers) => readers.subtotals({ collection: ['teams', 'jobs'], row: 'Y-1', rollup: 'sum', from, to })), /subtotals: the collection at \['teams', 'jobs'\] keeps no subtotal by sum — it keeps none: declare index\.nested\.values\(\{ rollup \}\)/);
1220
+ assert.throws(over((readers) => readers.subtotals({ collection: ['teams', 'hours'], row: 'Y-1', rollup: 'median', from, to })), /subtotals: the collection at \['teams', 'hours'\] rolls up by "median", which is no rollup/);
1221
+ assert.throws(over((readers) => readers.subtotals({ collection: ['teams', 'hours'], row: 'Y-1', rollup: 'sum', level: 'day', from, to })), /subtotals: the index keeps subtotals at week, month, quarter, year, and none at "day"/);
1222
+ // A node's path given as its keys alone, where each is an id of the index's (#1540): refused in words that write it.
1223
+ assert.throws(over((readers) => readers.items({ collection: ['teams', 'jobs'], row: 'Y-1', path: ['T-1'], from, to })), /^Error: e3\.index 'yards\.yards_in_time' items: `path` names a node by its child rows' keys from the row down, each an id of the index's under its rows' place — path: \[variant\('teams', key\)\]$/);
1224
+ assert.throws(over((readers) => readers.items({ collection: ['visits'], row: 'Y-1', path: ['T-1'], from, to })), /items: `path` names a node by its child rows' keys from the row down, each an id of the index's under its rows' place — a collection of the row itself has no path: leave `path` out$/);
1225
+ // An index that declares no summary keeps no totals
1226
+ const Shed = StructType({ name: StringType, visits: JobsType });
1227
+ const sheds = record('sheds', DictType(StringType, Shed), {
1228
+ initial: new Map(),
1229
+ indexes: (index) => ({ sheds_in_time: index.nested({ collections: { visits: index.nested.items({ from: 'start', to: 'end' }) }, tile: 'day' }) }),
1230
+ });
1231
+ const shedsInTime = index(sheds.indexes.sheds_in_time);
1232
+ assert.throws(() => East.function([shedsInTime.type], NullType, (_$, entries) => {
1233
+ shedsInTime.read(entries).totals({ collection: ['visits'], row: 'S-1', from, to });
1234
+ return null;
1235
+ }), /^Error: e3\.index 'sheds\.sheds_in_time' totals: the index keeps no totals — declare the tile they are kept by, as index\.nested\(\{ …, summary: 'month' \}\)$/);
1236
+ });
1237
+ it('arrives on the body\'s parameter in a function with a spec', () => {
1238
+ const fn = function_('hours_of_team', {
1239
+ inputs: [inTime],
1240
+ args: [StringType, PathType, DateTimeType, DateTimeType],
1241
+ output: FloatType,
1242
+ }, ($, yardsInTime, yard, path, from, to) => {
1243
+ const hours = $.let(0.0);
1244
+ yardsInTime.items({ collection: ['teams', 'hours'], row: yard, path: teamIds(path), from, to }).each($, ($, logged) => { $.assign(hours, hours.add(logged)); });
1245
+ return hours;
1246
+ });
1247
+ const run = fn.body.compile([]);
1248
+ const from = at('2026-10-05T00:00:00.000');
1249
+ const to = at('2026-11-02T00:00:00.000');
1250
+ const crew = TEAMS.find((found) => found.team.hours.size > 0);
1251
+ assert.ok(crew !== undefined);
1252
+ const logged = [...hoursIn(crew.team.hours, from, to).values()];
1253
+ assert.ok(logged.length > 10);
1254
+ assert.equal(run(held, crew.yard, crew.path, from, to), totalOf(logged));
1255
+ });
1256
+ });
1257
+ describe('where a reader is refused', () => {
1258
+ /** Builds a function over an index's entries, for the refusal its body raises. */
1259
+ const over = (at, body) => () => East.function([at.type], NullType, (_$, entries) => { body(entries); return null; });
1260
+ it('refuses a leading field left out, one that leads nothing, and one of another type, naming the fields', () => {
1261
+ const byState = input.in_time_by_state;
1262
+ const from = at('2026-10-12T00:00:00.000');
1263
+ const to = at('2026-10-19T00:00:00.000');
1264
+ assert.throws(over(byState, (entries) => byState.read(entries).overlapping({ from, to })), /^Error: e3\.index 'jobs\.in_time_by_state' overlapping: 'state' is left out — the index is led by 'state', and takes each exactly, as on: \{ state: … \}$/);
1265
+ assert.throws(over(byState, (entries) => byState.read(entries).overlapping({ on: { state: 'open', press: 'P-1001' }, from, to })), /overlapping: 'press' leads nothing — the index is led by 'state'/);
1266
+ assert.throws(over(byState, (entries) => byState.read(entries).overlapping({ on: { state: 7n }, from, to })), /^Error: e3\.index 'jobs\.in_time_by_state' overlapping: a leading field is given a value of another type — `on` is \{ state: \.String \}: /);
1267
+ // @ts-expect-error — an index led by a field takes it: `unset` with no `on` does not type
1268
+ assert.throws(over(byState, (entries) => byState.read(entries).unset()), /unset: 'state' is left out/);
1269
+ const inTime = input.in_time;
1270
+ assert.throws(over(inTime, (entries) => inTime.read(entries).overlapping({ on: { state: 'open' }, from, to })), /^Error: e3\.index 'jobs\.in_time' overlapping: 'state' leads nothing — the index is led by no field, and takes no `on`$/);
1271
+ const series = input.press_days_by_state;
1272
+ assert.throws(over(series, (entries) => series.read(entries).events({ key: 'P-1001', from, to })), /events: 'state' is left out/);
1273
+ const load = input.press_load_by_state;
1274
+ assert.throws(over(load, (entries) => load.read(entries).totals({ on: {}, key: 'P-1001', from, to })), /totals: 'state' is left out/);
1275
+ });
1276
+ it('refuses a window or a key left out, naming it', () => {
1277
+ const series = input.press_weeks;
1278
+ const from = at('2026-10-12T00:00:00.000');
1279
+ assert.throws(over(series, (entries) => series.read(entries).events({ key: 'P-1001', from })), /events: `to` is left out — a window is \[from, to\), each a DateTime/);
1280
+ assert.throws(over(series, (entries) => series.read(entries).events({ from, to: from })), /events: `key` is left out — the key the events are on/);
1281
+ });
1282
+ it('refuses the rows with no start of an index whose start is no Option, naming the field', () => {
1283
+ const inTime = index(shifts.indexes.shifts_in_time);
1284
+ assert.throws(over(inTime, (entries) => inTime.read(entries).unset()), /^Error: e3\.index 'shifts\.shifts_in_time' unset: the index's start, 'start', is a DateTime field, so every row has one/);
1285
+ });
1286
+ it('refuses the rows not yet placed of an index whose place is no Option, and a window\'s part left out, naming it', () => {
1287
+ const byArea = index(marks.indexes.marks_by_area);
1288
+ assert.throws(over(byArea, (entries) => byArea.read(entries).unplaced()), /^Error: e3\.index 'marks\.marks_by_area' unplaced: the index's place, 'x' and 'y', is Float fields, so every row is placed/);
1289
+ assert.throws(over(byArea, (entries) => byArea.read(entries).within({ x: 0, y: 0, width: 1 })), /within: `height` is left out — a window is \{ x, y, width, height \}, each a Float/);
1290
+ const byZone = index(racks.indexes.by_zone_area);
1291
+ // @ts-expect-error — an index led by a field takes it: `unplaced` with no `on` does not type
1292
+ assert.throws(over(byZone, (entries) => byZone.read(entries).unplaced()), /unplaced: 'zone' is left out/);
1293
+ });
1294
+ it('refuses a key that is no leading part of a plain index\'s, in the range read\'s words', () => {
1295
+ const byState = input.by_state_press;
1296
+ assert.throws(over(byState, (entries) => byState.read(entries).of({ press: 'P-1001' })), /state/);
1297
+ });
1298
+ it('gives an index the readers of its kind, and refuses another index\'s entries, naming both', () => {
1299
+ const byPress = input.by_press;
1300
+ const series = input.press_weeks;
1301
+ assert.throws(() => East.function([series.type], NullType, (_$, entries) => { byPress.read(entries); return null; }), /^Error: e3\.index 'jobs\.by_press' reads its own entries, .* and was given an expression of .* — pass the body's parameter for this index$/);
1302
+ East.function([series.type, byPress.type], NullType, (_$, events, rows) => {
1303
+ const readers = series.read(events);
1304
+ // @ts-expect-error — a series index has no `of`: its reader is `events`
1305
+ assert.equal(readers.of, undefined);
1306
+ // @ts-expect-error — a plain index has no `events`: its readers are `of` and `between`
1307
+ assert.equal(byPress.read(rows).events, undefined);
1308
+ return null;
1309
+ });
1310
+ });
1311
+ });
1312
+ describe('e3.index(def).read', () => {
1313
+ it('gives the expression it was handed, still the entries, with the index\'s readers on it', () => {
1314
+ const byPress = input.by_press;
1315
+ const both = East.compile(East.function([byPress.type, StringType], StructType({ sized: IntegerType, read: IntegerType }), ($, entries, press) => {
1316
+ const read = byPress.read(entries);
1317
+ assert.equal(read, entries, 'the same expression');
1318
+ const given = $.let(0n);
1319
+ read.of(press).each($, ($) => { $.assign(given, given.add(1n)); });
1320
+ return { sized: read.prefix({ ik: press }).size(), read: given };
1321
+ }), []);
1322
+ const onPress = BigInt([...ROWS.values()].filter((row) => row.press === 'P-1001').length);
1323
+ assert.deepEqual(both(held.by_press, 'P-1001'), { sized: onPress, read: onPress });
1324
+ });
1325
+ it('gives back what already carries its readers as it is, and refuses what carries another index\'s of the same type, naming it', () => {
1326
+ const byPress = input.by_press;
1327
+ const byState = index(jobs.indexes.by_state);
1328
+ const refused = /^Error: e3\.index 'jobs\.by_state' reads its own entries, and was given those of e3\.index 'jobs\.by_press', which are of the same type — pass the body's parameter for this index$/;
1329
+ // A body's parameter for an index carries that index's readers: another index of its type does not read it
1330
+ function_('jobs_by_two', { inputs: [byPress, byState], args: [], output: NullType }, (_$, pressEntries, stateEntries) => {
1331
+ const of = pressEntries.of;
1332
+ assert.equal(byPress.read(pressEntries), pressEntries, 'its own parameter, as it is');
1333
+ assert.equal(pressEntries.of, of, 'its readers not made again');
1334
+ assert.throws(() => byState.read(pressEntries), refused);
1335
+ assert.equal(byState.read(stateEntries), stateEntries);
1336
+ return null;
1337
+ });
1338
+ // In a task's own function a parameter is known by its type alone, until an index's read is given it
1339
+ East.function([byPress.type, byState.type], NullType, (_$, pressEntries) => {
1340
+ const read = byPress.read(pressEntries);
1341
+ const of = read.of;
1342
+ assert.equal(byPress.read(read).of, of, 'read again, the same readers');
1343
+ assert.throws(() => byState.read(pressEntries), refused);
1344
+ return null;
1345
+ });
1346
+ });
1347
+ });
1348
+ describe('what a read gives, beside an index that files the rows\' fields apart', () => {
1349
+ /** A shift on a press: when it runs, and the hands on it by grade — a field an entries index files apart. */
1350
+ const CrewedShift = StructType({ press: StringType, start: DateTimeType, end: DateTimeType, byGrade: DictType(StringType, IntegerType) });
1351
+ const CrewedType = DictType(StringType, CrewedShift);
1352
+ const crewed = record('crewed_shifts', CrewedType, {
1353
+ initial: new Map(),
1354
+ indexes: (index) => ({
1355
+ hands_by_grade: index.entries('byGrade'),
1356
+ by_press: index.on(['press']),
1357
+ in_time: index.interval({ from: 'start', to: 'end' }),
1358
+ presses: index.key(East.function([StringType, CrewedShift], StringType, (_$, _key, shift) => shift.press), { value: East.function([StringType, CrewedShift], StringType, (_$, _key, shift) => shift.press) }),
1359
+ }),
1360
+ });
1361
+ const rows = new SortedMap(undefined, keyOrder);
1362
+ for (let n = 0; n < 30; n++) {
1363
+ const start = OCT_5 + BigInt(n) * 8n * HOUR;
1364
+ rows.set(`C-${String(n).padStart(2, '0')}`, decodeBeast2For(CrewedShift)(encodeBeast2For(CrewedShift)({
1365
+ press: PRESSES[n % 3], start: instant(start), end: instant(start + 8n * HOUR),
1366
+ byGrade: new SortedMap([['lead', 1n], ['hand', BigInt(2 + (n % 3))]], keyOrder),
1367
+ })));
1368
+ }
1369
+ /** The rows as the record's other indexes carry them: lean, the field the entries index files emptied. */
1370
+ const lean = (kept) => new SortedMap([...rows].filter(([key, shift]) => kept(key, shift))
1371
+ .map(([key, shift]) => [key, { ...shift, byGrade: new SortedMap(undefined, keyOrder) }]), keyOrder);
1372
+ it('types a read by what the index carries as its record builds it: the lean row, where its declaration alone says nothing', () => {
1373
+ const inTime = index(crewed.indexes.in_time);
1374
+ const byPress = index(crewed.indexes.by_press);
1375
+ const presses = index(crewed.indexes.presses);
1376
+ const from = at('2026-10-06T00:00:00.000');
1377
+ const to = at('2026-10-07T00:00:00.000');
1378
+ // An interval index, and a plain index with no `value`, carry the lean row beside an entries index
1379
+ const running = East.compile(East.function([inTime.type, DateTimeType, DateTimeType], CrewedType, ($, entries, from, to) => inTime.read(entries).overlapping({ from, to }).collect($)), []);
1380
+ const expected = lean((_key, shift) => compareFor(DateTimeType)(shift.start, to) < 0 && compareFor(DateTimeType)(shift.end, from) > 0);
1381
+ assert.ok(expected.size > 0);
1382
+ assertEast(CrewedType, running(entriesOf(crewed, crewed.indexes.in_time, rows), from, to), expected, 'the shifts running in the day, lean');
1383
+ const onPress = East.compile(East.function([byPress.type, StringType], DictType(StringType, DateTimeType), ($, entries, press) => {
1384
+ const starts = $.let(new Map(), DictType(StringType, DateTimeType));
1385
+ byPress.read(entries).of(press).each($, ($, shift, key) => { $(starts.insert(key, shift.start)); });
1386
+ return starts;
1387
+ }), []);
1388
+ assertEast(DictType(StringType, DateTimeType), onPress(entriesOf(crewed, crewed.indexes.by_press, rows), 'P-1002'), new SortedMap([...rows].filter(([, shift]) => shift.press === 'P-1002').map(([key, shift]) => [key, shift.start]), keyOrder), 'each shift\'s start, read off the lean row');
1389
+ // One with a `value` of its own carries its own
1390
+ const named = East.compile(East.function([presses.type, StringType], DictType(StringType, StringType), ($, entries, press) => presses.read(entries).of(press).collect($)), []);
1391
+ assert.equal(named(entriesOf(crewed, crewed.indexes.presses, rows), 'P-1003').size, 10);
1392
+ // In a function with a spec, the parameter is typed the same way
1393
+ const fn = function_('shifts_running', { inputs: [inTime], args: [DateTimeType, DateTimeType], output: CrewedType }, ($, shiftsInTime, from, to) => shiftsInTime.overlapping({ from, to }).collect($));
1394
+ assert.equal(fn.inputs.length, 1);
1395
+ // What the declaration alone invited — an index with no `value` carries nothing — no longer types, and never built
1396
+ // @ts-expect-error — the read gives the lean row, not Null
1397
+ assert.throws(() => East.function([inTime.type, DateTimeType, DateTimeType], DictType(StringType, NullType), ($, entries, from, to) => inTime.read(entries).overlapping({ from, to }).collect($)));
1398
+ });
1399
+ });
1400
+ describe('the body\'s parameter for an index', () => {
1401
+ it('arrives with its kind\'s readers on it in a function with a spec, and is still the entries', () => {
1402
+ const fn = function_('sheets_on_press', {
1403
+ inputs: [index(jobs.indexes.press_weeks), index(jobs.indexes.by_press)],
1404
+ args: [StringType, DateTimeType, DateTimeType],
1405
+ output: StructType({ sheets: FloatType, jobs: IntegerType }),
1406
+ }, ($, pressWeeks, byPress, press, from, to) => {
1407
+ const sheets = $.let(0.0);
1408
+ pressWeeks.events({ key: press, from, to }).each($, ($, job) => { $.assign(sheets, sheets.add(job.sheets)); });
1409
+ return { sheets, jobs: byPress.prefix({ ik: press }).size() };
1410
+ });
1411
+ assert.deepEqual(fn.inputs.map((read) => read.kind), ['index', 'index']);
1412
+ const run = fn.body.compile([]);
1413
+ const from = at('2026-10-12T00:00:00.000');
1414
+ const to = at('2026-10-19T00:00:00.000');
1415
+ const inWeek = [...jobsIn(ROWS, none, some('P-1002'), from, to).values()];
1416
+ assert.ok(inWeek.length > 0);
1417
+ assert.deepEqual(run(held.press_weeks, held.by_press, 'P-1002', from, to), {
1418
+ sheets: inWeek.reduce((sum, row) => sum + row.sheets, 0),
1419
+ jobs: BigInt([...ROWS.values()].filter((row) => row.press === 'P-1002').length),
1420
+ });
1421
+ });
1422
+ it('arrives with them in a stream task, beside the input its work is split over', () => {
1423
+ const SaleType = StructType({ press: StringType, amount: FloatType });
1424
+ const sales = input_('sales', DictType(StringType, SaleType));
1425
+ const busy = streamTask('sales_on_busy_presses', {
1426
+ inputs: [partition(sales), index(jobs.indexes.by_press)],
1427
+ output: output.dict(StringType, FloatType, { merge: (_$, _press, a, b) => a.add(b) }),
1428
+ }, ($, sales, byPress, emit) => {
1429
+ $.for(sales, ($, sale) => {
1430
+ const count = $.let(0n);
1431
+ byPress.of(sale.press).each($, ($) => { $.assign(count, count.add(1n)); });
1432
+ $.if(East.greater(count, 0n), ($) => { $(emit(sale.press, sale.amount)); });
1433
+ });
1434
+ });
1435
+ assert.equal(busy.inputs.length, 2);
1436
+ });
1437
+ it('is read through e3.index(def).read in a task\'s own function', () => {
1438
+ const byPress = index(jobs.indexes.by_press);
1439
+ const count = task('jobs_on_first_press', [byPress], East.function([byPress.type], IntegerType, ($, entries) => {
1440
+ const count = $.let(0n);
1441
+ byPress.read(entries).of('P-1001').each($, ($) => { $.assign(count, count.add(1n)); });
1442
+ return count;
1443
+ }));
1444
+ assert.equal(count.inputs.length, 1);
1445
+ });
1446
+ });
1447
+ //# sourceMappingURL=index-read.spec.js.map