rushes 0.2.2 → 0.3.0

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.
@@ -0,0 +1,159 @@
1
+ /** §21.3's standard ratios, as [width, height]. */
2
+ export const STANDARD_RATIOS = [
3
+ [1, 1], [4, 5], [5, 4], [4, 3], [3, 4], [3, 2], [2, 3], [16, 9], [9, 16], [21, 9], [9, 21],
4
+ ];
5
+ /** A format id: the label with ":" as "x", e.g. "9x16", "2.39x1", "10x7". */
6
+ export const FORMAT_ID_RE = /^\d+(?:\.\d+)?x\d+(?:\.\d+)?$/;
7
+ /** The most shapes one cut can have, the primary included (ruling R3). */
8
+ export const MAX_FORMATS = 8;
9
+ /** The order the chips always take (§21.5), so a chip never moves between projects. */
10
+ export const CHIP_ORDER = ["9x16", "4x5", "1x1", "4x3", "16x9"];
11
+ /** The largest side, in pixels, that counts as a picture size (a guard against nonsense, not a codec limit). */
12
+ export const MAX_PICTURE_SIDE = 100000;
13
+ /** A picture size: two whole numbers, each from 1 to MAX_PICTURE_SIDE. */
14
+ export function isPictureSize(width, height) {
15
+ return [width, height].every((n) => Number.isInteger(n) && n >= 1 && n <= MAX_PICTURE_SIDE);
16
+ }
17
+ function gcd(a, b) {
18
+ while (b)
19
+ [a, b] = [b, a % b];
20
+ return a;
21
+ }
22
+ /** 2.388 -> "2.39", 2.4 -> "2.4", 2 -> "2". */
23
+ const decimal = (n) => String(Number(n.toFixed(2)));
24
+ /** R13: the long side over the short, to two decimals: "2.39:1", "1:2.39". */
25
+ const decimalLabel = (r) => (r >= 1 ? `${decimal(r)}:1` : `1:${decimal(1 / r)}`);
26
+ /** 1% as a log ratio: |ln(a/b)| is the same for a landscape picture and its portrait twin. */
27
+ const SNAP = Math.log(1.01) + 1e-12;
28
+ /** The standard ratio nearest `r`, and how far off it is: |ln(r / standard)|, so 16:9 and 9:16 mirror. */
29
+ function nearestStandard(r) {
30
+ let best = null;
31
+ let err = Infinity;
32
+ for (const s of STANDARD_RATIOS) {
33
+ const e = Math.abs(Math.log(r / (s[0] / s[1])));
34
+ if (e < err) {
35
+ err = e;
36
+ best = s;
37
+ }
38
+ }
39
+ return { best, err };
40
+ }
41
+ /**
42
+ * §21.3: the label for a picture `width` × `height` (its shape on screen). The nearest standard
43
+ * ratio within 1%, otherwise the reduced fraction when both terms are 32 or less, otherwise a
44
+ * decimal with the long side over the short (R13): "2.39:1", "1:2.39".
45
+ */
46
+ export function ratioLabel(width, height) {
47
+ if (!isPictureSize(width, height))
48
+ throw new RangeError(`Not a picture size: ${width}×${height}`);
49
+ const r = width / height;
50
+ const { best, err } = nearestStandard(r);
51
+ if (best && err <= SNAP)
52
+ return `${best[0]}:${best[1]}`;
53
+ const g = gcd(width, height);
54
+ if (width / g <= 32 && height / g <= 32)
55
+ return `${width / g}:${height / g}`;
56
+ // The long side over the short, worked out the same way for a picture and its portrait twin.
57
+ return width >= height ? `${decimal(width / height)}:1` : `1:${decimal(height / width)}`;
58
+ }
59
+ export const ratioId = (label) => label.replace(":", "x");
60
+ export const labelOfId = (id) => id.replace("x", ":");
61
+ /** "9:16" -> 0.5625; null for anything that isn't "a:b" with both terms above 0. */
62
+ export function ratioValue(label) {
63
+ const m = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(label.trim());
64
+ if (!m)
65
+ return null;
66
+ const a = Number(m[1]);
67
+ const b = Number(m[2]);
68
+ return a > 0 && b > 0 ? a / b : null;
69
+ }
70
+ const isStandard = (label) => STANDARD_RATIOS.some(([a, b]) => `${a}:${b}` === label);
71
+ /** The longest a label can be (it becomes a format id, which the schema caps at 16 characters). */
72
+ const MAX_LABEL = 16;
73
+ /**
74
+ * §21.4's `label`, which is only a hint (R10). It is used only when the measured ratio isn't a
75
+ * standard one, the hint isn't itself within 1% of a standard ratio (that would be §21.3's job, and
76
+ * a render can't be labelled as a ratio it isn't), and the hint is within 2% of the measured shape.
77
+ * A hint that is used is rewritten into the canonical R13 form ("12:5", "2.40:1" and "2.4:1.0"
78
+ * all become "2.4:1"), so two spellings can never make two ids for one shape. Otherwise the
79
+ * measured label stands, with a note saying why.
80
+ */
81
+ export function settleLabel(width, height, hint) {
82
+ const measured = ratioLabel(width, height);
83
+ const given = hint?.trim() ?? "";
84
+ if (given === "" || given === measured)
85
+ return { label: measured, note: null };
86
+ if (given.length > MAX_LABEL)
87
+ return { label: measured, note: `The label is too long to be a ratio, so Rushes used the measured ${measured}.` };
88
+ const v = ratioValue(given);
89
+ if (v === null)
90
+ return { label: measured, note: `"${given}" isn't a ratio like 2.39:1, so Rushes used the measured ${measured}.` };
91
+ if (isStandard(measured))
92
+ return { label: measured, note: `The file measures ${measured}, a standard ratio, so the label "${given}" wasn't needed.` };
93
+ const standard = nearestStandard(v);
94
+ if (standard.best && standard.err <= SNAP) {
95
+ return { label: measured, note: `"${given}" is a standard ratio, and the file isn't one, so Rushes used the measured ${measured}.` };
96
+ }
97
+ const r = width / height;
98
+ if (Math.abs(Math.log(v / r)) > Math.log(1.02))
99
+ return { label: measured, note: `The file measures ${measured}, too far from "${given}" to use it.` };
100
+ const canonical = decimalLabel(v);
101
+ return { label: canonical, note: canonical === given ? null : `Rushes wrote the label "${given}" as ${canonical}.` };
102
+ }
103
+ /**
104
+ * Final review M1: two picture sizes are one shape when their ratios are within 1% of each other
105
+ * (|ln(a/b)|, so a landscape pair and its portrait twin compare alike), whatever labels they got:
106
+ * 1920×800 ("12:5") and 1920×804 ("2.39:1") are one shape.
107
+ */
108
+ export function sameShape(a, b) {
109
+ return Math.abs(Math.log((a.width / a.height) / (b.width / b.height))) <= SNAP;
110
+ }
111
+ /** §21.5: 9:16, 4:5, 1:1, 4:3, 16:9, then anything else from narrow to wide (width over height). */
112
+ export function chipOrder(list) {
113
+ const rank = (f) => {
114
+ const i = CHIP_ORDER.indexOf(f.id);
115
+ return i === -1 ? CHIP_ORDER.length : i;
116
+ };
117
+ return [...list].sort((a, b) => rank(a) - rank(b) || a.width / a.height - b.width / b.height || a.id.localeCompare(b.id));
118
+ }
119
+ /**
120
+ * A version's shapes: the primary first (§21.2 (2): its ratio is read from its own size), then
121
+ * the formats as stored. While the primary's size is unknown the primary is left out (never
122
+ * guessed), unless `fallback` (the player's measured size, R2) gives it; the listed formats stay.
123
+ */
124
+ export function versionFormats(v, fallback) {
125
+ const stored = v.width !== null && v.height !== null && isPictureSize(v.width, v.height) ? { width: v.width, height: v.height } : null;
126
+ const size = stored ?? (fallback && isPictureSize(fallback.width, fallback.height) ? fallback : null);
127
+ const rest = v.formats.map((f) => ({ id: f.id, label: f.label, file: f.file, width: f.width, height: f.height, duration: f.duration, fps: f.fps, primary: false }));
128
+ if (!size)
129
+ return rest;
130
+ const label = ratioLabel(size.width, size.height);
131
+ return [{ id: ratioId(label), label, file: v.file, width: size.width, height: size.height, duration: v.duration, fps: v.fps, primary: true }, ...rest];
132
+ }
133
+ /** §21.3: "9:16 is 8.4 s; the cut is 8.0 s" when a format's length is more than 0.1 s off the cut's. */
134
+ export function durationWarning(label, formatDuration, cutDuration) {
135
+ if (formatDuration === null || cutDuration === null)
136
+ return null;
137
+ if (Math.abs(formatDuration - cutDuration) <= 0.1 + 1e-9)
138
+ return null;
139
+ return `${label} is ${formatDuration.toFixed(1)} s; the cut is ${cutDuration.toFixed(1)} s`;
140
+ }
141
+ /** §21.2 (5): does `note` show while `current` is on screen? `current` is null on a one-format cut. */
142
+ export function noteShowsOn(note, current) {
143
+ return current === null || note.format === null || note.format === current;
144
+ }
145
+ /**
146
+ * The tag a Picture note carries in export, the CLI and the list (R4): its format's label, "All"
147
+ * on a cut with two or more formats, otherwise null (a one-format cut reads as it always did).
148
+ */
149
+ export function formatTag(note, videos) {
150
+ if (note.stage !== "picture")
151
+ return null;
152
+ // Null-safe: the CLI and agents read data from a 0.2.x server too, whose notes have no `format` and
153
+ // whose versions have no `formats` (review I1).
154
+ if (note.format != null)
155
+ return labelOfId(note.format);
156
+ const version = videos.find((v) => v.id === note.video)?.versions.find((v) => v.id === note.version);
157
+ // Any listed format means two or more shapes, whether or not the primary's size is known.
158
+ return (version?.formats?.length ?? 0) >= 1 ? "All" : null;
159
+ }
@@ -0,0 +1,192 @@
1
+ // §22.4: a cut's short label, and the one-line clipping the Change Log shares. Pure and import-free,
2
+ // because the dashboard bundles this file: nothing here may pull zod or Node in, and no lookbehind
3
+ // (Safari before 16.4 can't parse one). test/core/labels.test.ts checks both, and that every
4
+ // invisible character below is written as an escape.
5
+ /** A version's short label is at most this long (§22.3). */
6
+ export const LABEL_MAX = 48;
7
+ const WORD = /[\p{L}\p{N}]/u;
8
+ const SPACE = /\s/;
9
+ const JOINER = /[_\-/]/;
10
+ // Left at the end of a cut, these read as a broken sentence, so they go before the ellipsis.
11
+ const TRAILING = /[\s,;:.\-–—(_/]+$/u;
12
+ // Code points that belong to the character before them: combining marks, the zero-width joiner
13
+ // (U+200D), variation selectors (U+FE0F), skin-tone modifiers and tag characters.
14
+ const EXTENDS = /^[\p{M}\u200d\ufe0f\u{1F3FB}-\u{1F3FF}\u{E0020}-\u{E007F}]$/u;
15
+ const REGIONAL = /^[\u{1F1E6}-\u{1F1FF}]$/u;
16
+ // A surrogate that has no partner: a paired one is a single code point under the u flag.
17
+ const LONE_SURROGATE = /[\uD800-\uDFFF]/gu;
18
+ // Control characters, including the C1 ones (U+0085), and the line and paragraph separators.
19
+ const BREAKS = /[\p{Cc}\p{Zl}\p{Zp}]+/gu;
20
+ // Format characters (bidi overrides, zero-width spaces, the word joiner, the byte-order mark) go,
21
+ // except the two joiners (U+200C, U+200D) and the tag characters, which emoji sequences need.
22
+ const INVISIBLE = /(?![\u200c\u200d\u{E0000}-\u{E007F}])\p{Cf}/gu;
23
+ // Tag characters mean something only straight after the black flag (U+1F3F4), where they spell a
24
+ // region ("England"). Anywhere else they're invisible text, so they go; a run after the flag stays.
25
+ const TAGS = /(\u{1F3F4})([\u{E0000}-\u{E007F}]*)|[\u{E0000}-\u{E007F}]+/gu;
26
+ // Text made only of these shows nothing: format characters, spaces, and the characters that draw as
27
+ // a blank (the combining grapheme joiner, the Hangul fillers, the Khmer inherent vowels, the braille blank).
28
+ const NOTHING_VISIBLE = /^[\p{Cf}\s\u034f\u115f\u1160\u17b4\u17b5\u2800\u3164\uffa0]*$/u;
29
+ /**
30
+ * One clean line: a lone surrogate becomes U+FFFD, control characters and every run of whitespace
31
+ * become one space, bidi and zero-width characters go, and the ends are trimmed. Text with nothing
32
+ * visible in it comes back empty.
33
+ */
34
+ export function oneLineOf(text) {
35
+ const line = text
36
+ .replace(LONE_SURROGATE, "\uFFFD")
37
+ .replace(BREAKS, " ")
38
+ .replace(INVISIBLE, "")
39
+ .replace(TAGS, (_all, flag, tags) => (flag ? flag + tags : ""))
40
+ .replace(/\s+/g, " ")
41
+ .trim();
42
+ return NOTHING_VISIBLE.test(line) ? "" : line;
43
+ }
44
+ /** Code points grouped into what a reader sees as one character: an emoji sequence, a letter and its accents, a flag. */
45
+ function characters(points) {
46
+ const out = [];
47
+ let joined = false; // the last code point was a zero-width joiner: the next one belongs to it
48
+ let regionals = 0; // regional indicators in the last cluster (a flag is a pair)
49
+ for (const p of points) {
50
+ const last = out.length - 1;
51
+ if (last >= 0 && (joined || EXTENDS.test(p) || (REGIONAL.test(p) && regionals === 1))) {
52
+ out[last] += p;
53
+ regionals = REGIONAL.test(p) ? regionals + 1 : regionals;
54
+ }
55
+ else {
56
+ out.push(p);
57
+ regionals = REGIONAL.test(p) ? 1 : 0;
58
+ }
59
+ joined = p === "\u200d";
60
+ }
61
+ return out;
62
+ }
63
+ function lastIndex(chars, re) {
64
+ for (let i = chars.length - 1; i > 0; i--)
65
+ if (re.test(chars[i]))
66
+ return i;
67
+ return -1;
68
+ }
69
+ /**
70
+ * `text`, at most `max` characters. They're counted as code points, and a cut never falls inside
71
+ * an emoji sequence or between a letter and its accents. The cut falls at the last word boundary
72
+ * that leaves room for "…" (§22.4 (4)). A boundary is a space; in a name with none (a file name),
73
+ * an underscore, a hyphen or a slash. Only a single unbroken word is cut inside it.
74
+ */
75
+ export function clip(text, max) {
76
+ if (text.length <= max)
77
+ return text;
78
+ const points = Array.from(text);
79
+ if (points.length <= max)
80
+ return text;
81
+ // Only the start matters, so a very long note isn't grouped all the way down.
82
+ const chars = characters(points.slice(0, max + 32));
83
+ const head = [];
84
+ let used = 0;
85
+ for (const c of chars) {
86
+ const n = Array.from(c).length;
87
+ if (used + n > max - 1)
88
+ break;
89
+ head.push(c);
90
+ used += n;
91
+ }
92
+ // One character with no room for it (a base under hundreds of marks): keep its base. Marks with
93
+ // no base at all still come back as a bare ellipsis, which callers treat as nothing to show.
94
+ const base = chars.length > 0 ? Array.from(chars[0])[0] : "";
95
+ if (head.length === 0 && max > 1 && base && !EXTENDS.test(base))
96
+ return base + "…";
97
+ let cut = head.length;
98
+ const next = chars[head.length];
99
+ if (next !== undefined && !SPACE.test(next)) {
100
+ let at = lastIndex(head, SPACE);
101
+ if (at <= 0)
102
+ at = lastIndex(head, JOINER);
103
+ if (at > 0)
104
+ cut = at;
105
+ }
106
+ return head.slice(0, cut).join("").replace(TRAILING, "") + "…";
107
+ }
108
+ /** One line, clipped: how every Change Log line is stored (§22.3: 160 characters at most). */
109
+ export function oneLine(text, max) {
110
+ return clip(oneLineOf(text), max);
111
+ }
112
+ // §22.4 (3): a note's first clause ends at the first of these that comes after its first 12 characters.
113
+ const CLAUSE_ENDS = [";", ". ", " — ", " ("];
114
+ const CLAUSE_MIN = 12;
115
+ /** How many UTF-16 units the first `n` code points of `text` take up. */
116
+ function unitsOfFirst(text, n) {
117
+ let units = 0;
118
+ let seen = 0;
119
+ for (const ch of text) {
120
+ if (seen++ >= n)
121
+ break;
122
+ units += ch.length;
123
+ }
124
+ return units;
125
+ }
126
+ // `skipped` is how many code points were stripped from the note's start (a "v6: " or a
127
+ // "(batch b_1): "): the 12 count from the note as written, so "v1: first pass; rough" still ends at
128
+ // "first pass".
129
+ function firstClause(text, skipped) {
130
+ const from = unitsOfFirst(text, Math.max(0, CLAUSE_MIN - skipped));
131
+ let end = text.length;
132
+ for (const sep of CLAUSE_ENDS) {
133
+ const i = text.indexOf(sep, from);
134
+ if (i >= 0 && i < end)
135
+ end = i;
136
+ }
137
+ return text.slice(0, end).trim();
138
+ }
139
+ /** The file's name without its folder or extension, on one line: "renders/lumen_v6.mp4" gives "lumen_v6". */
140
+ function fileStem(file) {
141
+ const name = file.split(/[\\/]/).pop() ?? "";
142
+ const dot = name.lastIndexOf(".");
143
+ return oneLineOf(dot > 0 ? name.slice(0, dot) : name);
144
+ }
145
+ // A leading "v6" is this cut's own id when it's followed by ":", ",", a dash, a full stop and a
146
+ // space, the end, or a "(batch …)": "v6.5 slower" and "v60: x" are not.
147
+ // Built once per version number: a backfill reads thousands of cuts (Task 3 review, minor 7).
148
+ const LEADING_IDS = new Map();
149
+ function leadingId(digits) {
150
+ const n = digits.replace(/^0+/, "") || "0";
151
+ let re = LEADING_IDS.get(n);
152
+ if (!re) {
153
+ if (LEADING_IDS.size >= 2000)
154
+ LEADING_IDS.clear();
155
+ re = buildLeadingId(n);
156
+ LEADING_IDS.set(n, re);
157
+ }
158
+ return re;
159
+ }
160
+ function buildLeadingId(n) {
161
+ return new RegExp(`^v0*${n}(?![\\p{L}\\p{N}])(?:(?:\\s*[:,\\-–—]|\\.(?=\\s|$))[\\s:,.\\-–—]*|\\s*$|\\s+(?=\\(batch\\b))`, "iu");
162
+ }
163
+ // Something to show: not empty, and not a bare ellipsis left by a cut that had nothing before it.
164
+ const usable = (s) => s !== "" && s !== "…";
165
+ /**
166
+ * §22.4: the version's own label when it has one. Otherwise its note's first clause, without a
167
+ * leading "v6:" that repeats the id or a "(batch b_1):". Otherwise the file's name, then the id.
168
+ * Always one line, never over LABEL_MAX characters, never empty.
169
+ */
170
+ export function shortLabel(v) {
171
+ const own = clip(oneLineOf(v.label ?? ""), LABEL_MAX);
172
+ if (usable(own))
173
+ return own;
174
+ const note = oneLineOf(v.note ?? "");
175
+ let text = note;
176
+ const n = /^v(\d+)$/i.exec(v.id)?.[1];
177
+ if (n !== undefined)
178
+ text = text.replace(leadingId(n), "");
179
+ text = text.replace(/^\(batch\b[^)]*\)\s*:?\s*/i, "");
180
+ const skipped = Array.from(note.slice(0, note.length - text.length)).length;
181
+ text = firstClause(text, skipped);
182
+ if (WORD.test(text)) {
183
+ const fromNote = clip(text, LABEL_MAX);
184
+ if (usable(fromNote))
185
+ return fromNote;
186
+ }
187
+ const stem = clip(fileStem(v.file), LABEL_MAX);
188
+ if (usable(stem))
189
+ return stem;
190
+ const id = clip(oneLineOf(v.id), LABEL_MAX);
191
+ return usable(id) ? id : "Untitled";
192
+ }
@@ -0,0 +1,190 @@
1
+ // §22.5–§22.6: the Change Log's engine. Appending with collapsing (R4) and the 5000 cap, the
2
+ // one-time backfill (R6), "Before the log" (R5) and reading a page back. Pure apart from new ids;
3
+ // the server's LogBook owns the file.
4
+ import { newId } from "./ids.js";
5
+ import { oneLineOf } from "./labels.js";
6
+ import { STAGE_WORDS, cutEvent, fileEvent, notesSentEvent } from "./logEvents.js";
7
+ import { LOG_MAX, MERGE_MS, logText } from "./logText.js";
8
+ /** The newest entry this event may merge into: same kind, area and writer, within the window (R4). */
9
+ function mergeTarget(entries, event, by, t) {
10
+ const window = event.windowMs ?? MERGE_MS;
11
+ for (let i = entries.length - 1; i >= 0; i--) {
12
+ const e = entries[i];
13
+ const age = t - Date.parse(e.at);
14
+ // More than a window ahead (written while a clock was ahead): never a target, or it would take
15
+ // in everything until its time came round (I2). Look past it.
16
+ if (age < -window)
17
+ continue;
18
+ if (!(age <= window))
19
+ return -1; // older than the window, and so is everything before it
20
+ if (e.kind === event.kind && e.area === event.area && e.by === by)
21
+ return i;
22
+ }
23
+ return -1;
24
+ }
25
+ /** `wanted` when no line has it yet, otherwise a new id that none has. Ids are short and random, so a long log can draw one twice (I1). */
26
+ function freshId(taken, wanted) {
27
+ let id = wanted ?? newId("l");
28
+ while (taken(id))
29
+ id = newId("l");
30
+ return id;
31
+ }
32
+ // §22.9: a retried request repeats the event it already logged. For a count, that's the same cut
33
+ // (video and version) or the same variant or take (ref) as the line's latest; files and notes have
34
+ // no identity, so two of them are two.
35
+ const sameThing = (e, link) => (link.version !== null || link.ref !== null) && e.video === link.video && e.version === link.version && e.ref === link.ref;
36
+ function mergeInto(e, event, text, subject, count, link) {
37
+ // A repeat is the same words about the same place (minor 4).
38
+ if (event.merge === "once")
39
+ return e.text === text && e.video === link.video && e.version === link.version && e.ref === link.ref && e.tab === link.tab;
40
+ if (event.merge === "replace") {
41
+ if (e.subject !== subject)
42
+ return false;
43
+ e.text = text;
44
+ e.n += 1;
45
+ Object.assign(e, link);
46
+ return true;
47
+ }
48
+ if (sameThing(e, link))
49
+ return true;
50
+ e.n += count;
51
+ e.subject = e.subject === subject ? subject : "";
52
+ e.text = logText(event.many ? event.many(e.n, e.subject, e.text) : text) || text;
53
+ // A line opens a tab only when every event in it came from that one (minor 5).
54
+ Object.assign(e, link, { tab: e.tab === link.tab ? link.tab : null });
55
+ return true;
56
+ }
57
+ /**
58
+ * §22.5: writes `event` into `file` at `at`, merging it into a recent line when R4 says so, and keeps
59
+ * the newest LOG_MAX. Returns the line written or updated. A line with nothing visible in it is
60
+ * refused with an error, and the file is left as it was.
61
+ */
62
+ export function appendEvent(file, event, by, at, id) {
63
+ return place(file, event, by, at, id, (x) => file.entries.some((e) => e.id === x), true);
64
+ }
65
+ // appendEvent's work. `taken` says whether an id is in use; `cap` keeps the newest LOG_MAX as it
66
+ // goes. The backfill passes a Set and caps once at the end, so 30,000 dated items stay linear.
67
+ function place(file, event, by, at, id, taken, cap) {
68
+ const t = at.getTime();
69
+ const iso = at.toISOString();
70
+ const text = logText(event.text);
71
+ if (!text)
72
+ throw new Error("A Change Log line can't be blank");
73
+ // The schema keeps a subject to 200 characters; a lane name has no limit of its own.
74
+ const subject = Array.from(event.subject ?? "").slice(0, 200).join("");
75
+ const count = Math.max(1, Math.floor(event.count ?? 1));
76
+ const link = { video: event.video ?? null, version: event.version ?? null, ref: event.ref ?? null, tab: event.tab ?? null };
77
+ const dated = [...(event.ref ? [event.ref] : []), ...(event.clears ?? [])];
78
+ if (dated.length && file.undated.length) {
79
+ const gone = new Set(dated);
80
+ file.undated = file.undated.filter((r) => !gone.has(r));
81
+ }
82
+ const i = mergeTarget(file.entries, event, by, t);
83
+ if (i >= 0) {
84
+ const e = file.entries[i];
85
+ if (mergeInto(e, event, text, subject, count, link)) {
86
+ if (!(Date.parse(e.at) > t))
87
+ e.at = iso;
88
+ file.entries.splice(i, 1);
89
+ file.entries.push(e);
90
+ return e;
91
+ }
92
+ }
93
+ const entry = { id: freshId(taken, id), at: iso, area: event.area, kind: event.kind, text, ...link, by, n: count, subject };
94
+ file.entries.push(entry);
95
+ const extra = file.entries.length - LOG_MAX;
96
+ if (cap && extra > 0) {
97
+ file.entries.splice(0, extra);
98
+ file.dropped += extra;
99
+ }
100
+ return entry;
101
+ }
102
+ /**
103
+ * §22.6: reads in, once, the history a project already has. Every cut, batch and file dated before
104
+ * `before` (when this server's log began, R6) becomes a line by Rushes, in time order and collapsed
105
+ * as live lines are. The variants and takes already there become `undated` (R5), less any a line in
106
+ * the log already dates. A no-op once done.
107
+ */
108
+ export function backfillLog(file, src, before) {
109
+ if (file.backfilled)
110
+ return;
111
+ const films = src.project.videos.length;
112
+ const dated = [];
113
+ const add = (when, event) => {
114
+ const t = Date.parse(when);
115
+ if (Number.isFinite(t) && t < before)
116
+ dated.push({ t, event });
117
+ };
118
+ for (const video of src.project.videos)
119
+ for (const version of video.versions)
120
+ add(version.addedAt, cutEvent(films, video, version));
121
+ for (const batch of src.batches.batches)
122
+ add(batch.sentAt, notesSentEvent(batch));
123
+ for (const entry of src.project.files)
124
+ add(entry.addedAt, fileEvent(entry));
125
+ dated.sort((a, b) => a.t - b.t);
126
+ const past = { schema: 1, rev: 0, backfilled: true, undated: [], dropped: 0, entries: [] };
127
+ // Ids are drawn against the live lines too, so none is shared (I1).
128
+ const ids = new Set(file.entries.map((e) => e.id));
129
+ const taken = (x) => {
130
+ if (ids.has(x))
131
+ return true;
132
+ ids.add(x); // freshId keeps the first id that isn't taken, so it's now in use
133
+ return false;
134
+ };
135
+ for (const d of dated)
136
+ place(past, d.event, "rushes", new Date(d.t), undefined, taken, false);
137
+ file.entries = [...past.entries, ...file.entries];
138
+ const extra = file.entries.length - LOG_MAX;
139
+ if (extra > 0) {
140
+ file.entries.splice(0, extra);
141
+ file.dropped += extra;
142
+ }
143
+ const live = new Set(file.entries.map((e) => e.ref));
144
+ file.undated = undatedRefs(src.project, src.script).filter((r) => !live.has(r));
145
+ file.backfilled = true;
146
+ }
147
+ /** Every variant ("<lane>/<variant>") and take ("<section>:<take>") the project has. */
148
+ export function undatedRefs(project, script) {
149
+ const refs = [
150
+ ...project.lanes.flatMap((l) => l.variants.map((v) => `${l.id}/${v.id}`)),
151
+ ...script.sections.flatMap((s) => s.takes.map((t) => `${s.id}:${t.id}`)),
152
+ ];
153
+ return refs.slice(0, LOG_MAX);
154
+ }
155
+ /** §22.6's "Before the log": one line per lane, and one for takes, computed now from the refs that still exist. */
156
+ export function undatedLines(refs, ctx) {
157
+ const set = new Set(refs);
158
+ const out = [];
159
+ for (const lane of ctx.project.lanes) {
160
+ const n = lane.variants.filter((v) => set.has(`${lane.id}/${v.id}`)).length;
161
+ if (n === 0)
162
+ continue;
163
+ const noun = lane.stage === "voice" ? (n === 1 ? "read" : "reads") : n === 1 ? "variant" : "variants";
164
+ // A lane that carries its stage's own name (every 0.2.x project's defaults) isn't named twice.
165
+ const word = STAGE_WORDS[lane.stage];
166
+ const name = oneLineOf(lane.name);
167
+ out.push({ area: lane.stage, text: logText(name && name !== word ? `${word}: ${lane.name} (${n} ${noun})` : `${word}: ${n} ${noun}`) });
168
+ }
169
+ const sections = ctx.script.sections.filter((s) => s.takes.some((t) => set.has(`${s.id}:${t.id}`))).length;
170
+ if (sections)
171
+ out.push({ area: "voice", text: `Voiceover: ${sections} section${sections === 1 ? "" : "s"} with takes` });
172
+ return out;
173
+ }
174
+ /** §22.7: the newest `limit` lines (default 30), newest first, matching `area` and `since`. */
175
+ export function logView(file, q, ctx) {
176
+ const asked = Number.isFinite(q.limit) ? Math.floor(q.limit) : 30;
177
+ const limit = Math.min(LOG_MAX, Math.max(1, asked));
178
+ const from = q.since === undefined ? null : Date.parse(q.since);
179
+ const matching = [];
180
+ for (let i = file.entries.length - 1; i >= 0; i--) {
181
+ const e = file.entries[i];
182
+ if (q.area !== undefined && e.area !== q.area)
183
+ continue;
184
+ if (from !== null && !(Date.parse(e.at) > from))
185
+ continue;
186
+ matching.push(e);
187
+ }
188
+ const undated = from !== null ? [] : undatedLines(file.undated, ctx).filter((l) => q.area === undefined || l.area === q.area);
189
+ return { entries: matching.slice(0, limit), earlier: Math.max(0, matching.length - limit), undated, dropped: file.dropped, total: file.entries.length };
190
+ }