@nodaro/shared 3.21.0 → 3.23.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.
Files changed (84) hide show
  1. package/dist/index.cjs +2284 -195
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1915 -75
  4. package/dist/index.d.ts +1915 -75
  5. package/dist/index.js +2117 -196
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/add-captions-plan.test.ts +33 -0
  9. package/src/__tests__/caption-plan-parse.test.ts +23 -0
  10. package/src/__tests__/caption-segment-schema.test.ts +30 -0
  11. package/src/__tests__/collections.test.ts +253 -0
  12. package/src/__tests__/dialogue-capabilities.test.ts +157 -0
  13. package/src/__tests__/edit-plan-review.test.ts +70 -0
  14. package/src/__tests__/edl-clocks.test.ts +97 -0
  15. package/src/__tests__/edl.test.ts +34 -0
  16. package/src/__tests__/execution-outcome.test.ts +44 -0
  17. package/src/__tests__/fan-out-meta.test.ts +23 -0
  18. package/src/__tests__/fan-out-rows.test.ts +36 -0
  19. package/src/__tests__/fan-out-url-item.test.ts +44 -0
  20. package/src/__tests__/fixtures/speaker-tracks.fixtures.json +622 -0
  21. package/src/__tests__/input-field-extra-keys.test.ts +34 -0
  22. package/src/__tests__/list-consumers-fan-in.test.ts +40 -0
  23. package/src/__tests__/model-tree.test.ts +7 -0
  24. package/src/__tests__/node-pass-through.test.ts +23 -0
  25. package/src/__tests__/node-runtime-keys.test.ts +1 -0
  26. package/src/__tests__/picker-restrictions.test.ts +36 -0
  27. package/src/__tests__/preview-gate.test.ts +305 -0
  28. package/src/__tests__/render-basis.test.ts +176 -0
  29. package/src/__tests__/render-nodes.test.ts +73 -0
  30. package/src/__tests__/render-output.test.ts +392 -0
  31. package/src/__tests__/run-continuation.test.ts +32 -0
  32. package/src/__tests__/speaker-tracks.test.ts +474 -0
  33. package/src/__tests__/speech-pricing.test.ts +69 -0
  34. package/src/__tests__/telegram-channel.test.ts +91 -0
  35. package/src/__tests__/tts-capabilities.test.ts +81 -4
  36. package/src/__tests__/tts-neighbour-text.test.ts +19 -0
  37. package/src/__tests__/ugc-call-body.test.ts +38 -0
  38. package/src/__tests__/ugc-run-state.test.ts +68 -0
  39. package/src/__tests__/video-character-refs.test.ts +213 -0
  40. package/src/__tests__/video-overlay-layer-plan.test.ts +94 -0
  41. package/src/add-captions-plan.ts +50 -0
  42. package/src/caption-plan.ts +45 -0
  43. package/src/caption-segment-schema.ts +82 -0
  44. package/src/collections.ts +462 -0
  45. package/src/competitors.ts +77 -0
  46. package/src/credit-estimators/index.ts +9 -0
  47. package/src/credit-estimators/speech.ts +51 -0
  48. package/src/dialogue-capabilities.ts +48 -0
  49. package/src/edit-plan-contract.ts +20 -9
  50. package/src/edit-plan-review.ts +40 -1
  51. package/src/edl.ts +27 -1
  52. package/src/execution-outcome.ts +41 -0
  53. package/src/fan-out-meta.ts +23 -0
  54. package/src/fan-out-rows.ts +74 -5
  55. package/src/gemini-omni-voices.ts +59 -0
  56. package/src/handle-aliases.ts +295 -0
  57. package/src/i18n/camera-motions.pt-BR.ts +14 -14
  58. package/src/i18n/transitions.pt-BR.ts +13 -13
  59. package/src/index.ts +179 -1
  60. package/src/model-catalog.ts +122 -13
  61. package/src/model-constants.ts +24 -4
  62. package/src/model-tree.ts +5 -1
  63. package/src/node-execution-state.ts +13 -0
  64. package/src/node-mappable-fields.ts +7 -1
  65. package/src/node-pass-through.ts +37 -0
  66. package/src/node-runtime-keys.ts +14 -0
  67. package/src/picker-restrictions.ts +49 -0
  68. package/src/presentation-types.ts +26 -2
  69. package/src/presentation-utils.ts +25 -7
  70. package/src/preview-gate.ts +279 -0
  71. package/src/producer-types.ts +58 -0
  72. package/src/render-final.ts +20 -0
  73. package/src/render-nodes.ts +92 -0
  74. package/src/render-output.ts +565 -0
  75. package/src/run-continuation.ts +39 -0
  76. package/src/speaker-tracks.ts +638 -0
  77. package/src/telegram-channel.ts +140 -0
  78. package/src/transcribe-preflight.ts +8 -4
  79. package/src/tts-capabilities.ts +19 -5
  80. package/src/tts-neighbour-text.ts +46 -0
  81. package/src/ugc-call-body.ts +86 -0
  82. package/src/ugc-run-state.ts +64 -0
  83. package/src/video-character-refs.ts +233 -0
  84. package/src/video-overlay.ts +78 -21
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The render-node registry (SV18, decided 2026-10-06): every node type that
3
+ * turns an EDL into a finished file, and how each one behaves wherever the
4
+ * platform gives a render its meaning — review and the Preview label, privacy,
5
+ * the latest-batch reader, the owner-only listings, and what its `json` handle
6
+ * carries.
7
+ *
8
+ * ONE registry, read by both engines, the editor, the listings and MCP, so a
9
+ * second render (Speaker View) joins by adding one entry — never by finding
10
+ * every `=== "apply-edl"`. The backend census test
11
+ * (`render-node-census.test.ts`) fails a new `apply-edl` literal at any site
12
+ * that is not pure registration of that node.
13
+ *
14
+ * The key is the node type AND the job name: a render's job is never renamed
15
+ * (by quality or otherwise — only its credit id changes), so the same key
16
+ * answers for `node.type` and for `jobs.job_type`.
17
+ */
18
+ import { applyEdlCreditId } from "./credit-identifiers.js"
19
+ import type { RenderMedium } from "./render-output.js"
20
+
21
+ /** Where a render's player maps the output clock back to the master clock
22
+ * from: the EDL it was given (`input_data.edl`), or the EDL it emitted on its
23
+ * `json` output (a render that rewrites its EDL, e.g. by splitting turns). */
24
+ export type RenderClockSource = "input" | "output-json"
25
+
26
+ /** What a render's `json` output handle carries. Only a `transcript` is handed
27
+ * on as one (Add Captions, the word-timing preflight). */
28
+ export type RenderJsonKind = "transcript" | "edl"
29
+
30
+ export interface RenderNodeDescriptor {
31
+ /** The medium the render's order asks for (its node data, or its job's
32
+ * `input_data`) — before any output exists to say. */
33
+ readonly mediumOf: (data: Readonly<Record<string, unknown>>) => RenderMedium
34
+ /** The credit id a render of this quality and output reserves on. */
35
+ readonly creditId: (quality: unknown, output?: unknown) => string
36
+ readonly clockMapFrom: RenderClockSource
37
+ /** Listed in its owner's own views only, never in a public one (decided
38
+ * 2026-10-06): a Preview is private, and a public final would be exposure
39
+ * nobody decided. */
40
+ readonly ownerOnlyListing: boolean
41
+ /** An `each` wire reads its LATEST batch only, never its accumulated history
42
+ * (TA6, decided 2026-10-04). */
43
+ readonly latestBatch: boolean
44
+ readonly jsonKind: RenderJsonKind
45
+ }
46
+
47
+ type Data = Readonly<Record<string, unknown>>
48
+
49
+ /** Its `output` setting, video when absent. */
50
+ const outputSettingMedium = (data: Data): RenderMedium => (data.output === "audio" ? "audio" : "video")
51
+
52
+ const descriptor = (d: RenderNodeDescriptor): RenderNodeDescriptor => Object.freeze({ ...d })
53
+
54
+ export const RENDER_NODE_TYPES: Readonly<Record<string, RenderNodeDescriptor>> = Object.freeze({
55
+ "apply-edl": descriptor({
56
+ mediumOf: outputSettingMedium,
57
+ creditId: (quality) => applyEdlCreditId(quality),
58
+ clockMapFrom: "input",
59
+ ownerOnlyListing: true,
60
+ latestBatch: true,
61
+ jsonKind: "transcript",
62
+ }),
63
+ })
64
+
65
+ /** Every render node type, in registry order. */
66
+ export const RENDER_NODE_TYPE_IDS: readonly string[] = Object.freeze(Object.keys(RENDER_NODE_TYPES))
67
+
68
+ /** The descriptor of a render node type (or job name); `undefined` for any
69
+ * other value. Own keys only, so `"constructor"` is not a render. */
70
+ export function renderNodeOf(type: unknown): RenderNodeDescriptor | undefined {
71
+ return typeof type === "string" && Object.hasOwn(RENDER_NODE_TYPES, type) ? RENDER_NODE_TYPES[type] : undefined
72
+ }
73
+
74
+ /** Is this node type (or job name) a render? */
75
+ export function isRenderNodeType(type: unknown): type is string {
76
+ return renderNodeOf(type) !== undefined
77
+ }
78
+
79
+ /** Does an `each` wire from this node read its latest batch only? */
80
+ export function rendersLatestBatch(type: unknown): boolean {
81
+ return renderNodeOf(type)?.latestBatch === true
82
+ }
83
+
84
+ /** Is this node a render whose `json` output is a Transcript? */
85
+ export function rendersTranscriptJson(type: unknown): boolean {
86
+ return renderNodeOf(type)?.jsonKind === "transcript"
87
+ }
88
+
89
+ /** The render job types that list in their owner's own views only. */
90
+ export const OWNER_ONLY_LISTING_RENDER_TYPES: readonly string[] = Object.freeze(
91
+ RENDER_NODE_TYPE_IDS.filter((t) => RENDER_NODE_TYPES[t]!.ownerOnlyListing),
92
+ )
@@ -0,0 +1,565 @@
1
+ /**
2
+ * A render node's SAVED output — what a render (Apply EDL) hands downstream
3
+ * when the run does not run it: a node outside a Run from here, a Skip-frozen
4
+ * node, or the editor's own read of the canvas. ONE reader, so the two engines
5
+ * cannot pick different takes again (they did: the server took
6
+ * `generatedVideoUrl` first, the editor the selected result).
7
+ *
8
+ * - A SCALAR edge reads the selected result (`generatedResults[activeResultIndex]`),
9
+ * as the node's medium (`data.output`). That also repairs a pick saved before
10
+ * the results gallery wrote the right field: such a node holds the picked
11
+ * take's index with the newest take still on `generatedVideoUrl`, and the
12
+ * selected result wins (decided 2026-10-04).
13
+ * - An EACH edge reads the render's LATEST batch only (`__listResults`, the
14
+ * rows of its last run once per clip) — never its accumulated history,
15
+ * which holds earlier runs' clips too (TA6, decided 2026-10-04). A render
16
+ * that ran once has no batch; the edge then reads the one result.
17
+ *
18
+ * Every item carries what its render stamped on it — `quality` ("proxy" is a
19
+ * Preview), `clipKey` (the plan clip it was cut from), `planBasis` (the plan
20
+ * value it was cut from) and `renderBasis` (the render's own settings) —
21
+ * copied onto the result by every lane that lands a take.
22
+ */
23
+ import { normalizeEdl } from "./edl.js"
24
+ import { editPlanBasis } from "./edit-plan-review.js"
25
+ import { defaultEdgeOutputMode } from "./producer-types.js"
26
+ import { resolveIndex, selectListItems, type SelectorFields } from "./selector.js"
27
+
28
+ /** The quality an Apply EDL render was made at. "proxy" is a Preview. */
29
+ export type RenderQuality = "proxy" | "final"
30
+
31
+ /** The medium a render hands on. */
32
+ export type RenderMedium = "video" | "audio"
33
+
34
+ /** What a finished render says about itself beside its URL. */
35
+ export interface RenderResultStamp {
36
+ readonly quality?: RenderQuality
37
+ /** The plan clip the render was cut from (`edlSpanKey` of that clip). */
38
+ readonly clipKey?: string
39
+ /** The plan value the render was cut from (`renderReadBasis`): stamped only
40
+ * when that value is the plan's own (`renderPlanBasis`). Absent = unknown. */
41
+ readonly planBasis?: string
42
+ /** The render's own settings (`renderSettingsBasis`): its output, its
43
+ * crossfade and the media it read. */
44
+ readonly renderBasis?: string
45
+ }
46
+
47
+ /** One row of a run's per-item results, row-aligned with them. A row that
48
+ * produced nothing (a hole) carries no take's fields; a render's hole still
49
+ * says what it was sent for (`renderSentRowStamps`): the quality its run
50
+ * renders at and, when the run can name it, its clip (`clipKey`,
51
+ * `renderPlanRowClipKeys`), so a failed row is matched to its clip by key.
52
+ * `{}` is a hole that names none (a run made before every row was stamped, or
53
+ * a node that is not a render). */
54
+ export interface RunResultRowStamp extends RenderResultStamp {
55
+ readonly jobId?: string
56
+ readonly thumbnailUrl?: string
57
+ /** The row never ran: a Stop, or the fail-fast after another row failed,
58
+ * skipped it. It is a hole, never a failure. */
59
+ readonly cancelled?: true
60
+ }
61
+
62
+ /** One saved render result. */
63
+ export interface SavedRenderItem extends RenderResultStamp {
64
+ readonly url: string
65
+ readonly medium: RenderMedium
66
+ readonly jobId?: string
67
+ readonly thumbnailUrl?: string
68
+ }
69
+
70
+ type Data = Readonly<Record<string, unknown>>
71
+
72
+ const MEDIUM_FIELD: Readonly<Record<RenderMedium, string>> = {
73
+ video: "generatedVideoUrl",
74
+ audio: "generatedAudioUrl",
75
+ }
76
+
77
+ const str = (v: unknown): string | undefined => (typeof v === "string" && v.length > 0 ? v : undefined)
78
+
79
+ const BASIS = /^[0-9a-f]{16}$/
80
+ /** A basis as `editPlanBasis` writes it — 16 lowercase hex digits — or nothing. */
81
+ const basisOf = (v: unknown): string | undefined => (typeof v === "string" && BASIS.test(v) ? v : undefined)
82
+
83
+ /** The stamp a finished render's output carries: a known quality, a non-empty
84
+ * clip key and the two bases as 16 hex digits, nothing else (an unknown value
85
+ * is dropped, not trusted). */
86
+ export function renderResultStamp(output: unknown): RenderResultStamp {
87
+ const o = (output && typeof output === "object" ? output : {}) as Record<string, unknown>
88
+ const quality = o.quality === "proxy" || o.quality === "final" ? o.quality : undefined
89
+ const clipKey = str(o.clipKey)
90
+ const planBasis = basisOf(o.planBasis)
91
+ const renderBasis = basisOf(o.renderBasis)
92
+ return {
93
+ ...(quality ? { quality } : {}),
94
+ ...(clipKey ? { clipKey } : {}),
95
+ ...(planBasis ? { planBasis } : {}),
96
+ ...(renderBasis ? { renderBasis } : {}),
97
+ }
98
+ }
99
+
100
+ /** The medium a render node renders: its `output`, video when absent. */
101
+ function mediumOf(data: Data): RenderMedium {
102
+ return data.output === "audio" ? "audio" : "video"
103
+ }
104
+
105
+ interface ResultEntry {
106
+ readonly url?: unknown
107
+ readonly jobId?: unknown
108
+ readonly thumbnailUrl?: unknown
109
+ }
110
+
111
+ function resultsOf(data: Data): readonly ResultEntry[] {
112
+ return Array.isArray(data.generatedResults) ? (data.generatedResults as ResultEntry[]) : []
113
+ }
114
+
115
+ function itemOf(url: string, medium: RenderMedium, entry: ResultEntry | undefined): SavedRenderItem {
116
+ const jobId = str(entry?.jobId)
117
+ const thumbnailUrl = str(entry?.thumbnailUrl)
118
+ return {
119
+ url,
120
+ medium,
121
+ ...(jobId ? { jobId } : {}),
122
+ ...(thumbnailUrl ? { thumbnailUrl } : {}),
123
+ ...(entry ? renderResultStamp(entry) : {}),
124
+ }
125
+ }
126
+
127
+ /** The one result a saved render hands a scalar edge: the selected result (as
128
+ * the node's medium), else the saved field of its medium, else the other
129
+ * medium's field (as that medium). */
130
+ export function savedRenderOutput(data: Data): SavedRenderItem | undefined {
131
+ const medium = mediumOf(data)
132
+ const results = resultsOf(data)
133
+ const index = typeof data.activeResultIndex === "number" ? data.activeResultIndex : 0
134
+ const selected = results[index] ?? results[0]
135
+ const selectedUrl = str(selected?.url)
136
+ if (selectedUrl) return itemOf(selectedUrl, medium, selected)
137
+ // No results kept (a node saved before results were): the saved field of its
138
+ // medium, else the other medium's — which then names the medium itself.
139
+ const own = str(data[MEDIUM_FIELD[medium]])
140
+ if (own) return { url: own, medium }
141
+ const other: RenderMedium = medium === "video" ? "audio" : "video"
142
+ const otherUrl = str(data[MEDIUM_FIELD[other]])
143
+ return otherUrl ? { url: otherUrl, medium: other } : undefined
144
+ }
145
+
146
+ /** The rows of a saved render's LATEST batch, row-aligned (`null` = a row that
147
+ * produced nothing), each with what its render stamped. `undefined` when the
148
+ * render has no batch (it ran once, or never). */
149
+ export function savedRenderBatch(data: Data): ReadonlyArray<SavedRenderItem | null> | undefined {
150
+ const batch = data.__listResults
151
+ if (!Array.isArray(batch) || batch.length === 0) return undefined
152
+ const medium = mediumOf(data)
153
+ const byUrl = new Map<string, ResultEntry>()
154
+ for (const entry of resultsOf(data)) {
155
+ const url = str(entry.url)
156
+ if (url && !byUrl.has(url)) byUrl.set(url, entry)
157
+ }
158
+ return batch.map((row) => {
159
+ const url = str(row)
160
+ return url ? itemOf(url, medium, byUrl.get(url)) : null
161
+ })
162
+ }
163
+
164
+ /** The latest batch as the list an each edge iterates (`""` = a hole). */
165
+ export function savedRenderBatchUrls(data: Data): string[] | undefined {
166
+ const batch = savedRenderBatch(data)
167
+ return batch ? batch.map((item) => item?.url ?? "") : undefined
168
+ }
169
+
170
+ /**
171
+ * A plan clip's identity: the outer span of its kept segments on the master
172
+ * clock, `${min inMs}-${max outMs}` (integer ms, as `normalizeEdl` rounds them).
173
+ * Taken from the PLAN's clip, never from a rendered EDL — Camera Switch can
174
+ * move a clip's outer edges inward. `undefined` when the value is not an EDL
175
+ * with segments.
176
+ */
177
+ export function edlSpanKey(edl: unknown): string | undefined {
178
+ if (!edl || typeof edl !== "object" || Array.isArray(edl)) return undefined
179
+ let segments: ReturnType<typeof normalizeEdl>["segments"]
180
+ try {
181
+ segments = normalizeEdl(edl).segments
182
+ } catch {
183
+ return undefined
184
+ }
185
+ if (segments.length === 0) return undefined
186
+ let min = Infinity
187
+ let max = -Infinity
188
+ for (const s of segments) {
189
+ if (s.inMs < min) min = s.inMs
190
+ if (s.outMs > max) max = s.outMs
191
+ }
192
+ return Number.isFinite(min) && Number.isFinite(max) ? `${min}-${max}` : undefined
193
+ }
194
+
195
+ /** The clip key of row `row` of a clips plan (a list of EDLs, objects or JSON
196
+ * strings). `undefined` for a plan that is one EDL (Tighten), a missing row,
197
+ * or a row that is not an EDL. */
198
+ export function planClipKeyAt(plan: unknown, row: number): string | undefined {
199
+ if (!Array.isArray(plan)) return undefined
200
+ let clip: unknown = plan[row]
201
+ if (typeof clip === "string") {
202
+ if (!clip.trim()) return undefined
203
+ try {
204
+ clip = JSON.parse(clip)
205
+ } catch {
206
+ return undefined
207
+ }
208
+ }
209
+ return edlSpanKey(clip)
210
+ }
211
+
212
+ /** A node or an edge as the plan walk needs it (either engine's graph). */
213
+ export interface RenderGraphNode {
214
+ readonly id: string
215
+ readonly type?: string | null
216
+ }
217
+ export interface RenderGraphEdge {
218
+ readonly source: string
219
+ readonly target: string
220
+ readonly sourceHandle?: string | null
221
+ readonly targetHandle?: string | null
222
+ /** The wire's settings: its `outputMode` and its range / list selector. */
223
+ readonly data?: unknown
224
+ }
225
+
226
+ /** One wire on the way from the plan to the render that picks clips: the render's
227
+ * `edl` wire, or a Camera Switch's. */
228
+ export interface RenderPlanHop {
229
+ /** The consumer's wire — the one whose selector the input resolvers apply. */
230
+ readonly edge: RenderGraphEdge
231
+ /** Whether the wire hands on one clip per row ("each"), as both resolvers
232
+ * decide it: its `outputMode`, else the default of the node behind any
233
+ * teleports, on the handle that node is wired from. */
234
+ readonly each: boolean
235
+ /** The type of the node the wire hands the clips on from, behind any
236
+ * teleports: what a "Selected" (`last`) wire reads is that node's own output. */
237
+ readonly source?: string
238
+ }
239
+
240
+ /** The Edit Plan behind a render and the wires between them, plan side first. */
241
+ export interface RenderPlanPath {
242
+ readonly planId: string
243
+ readonly hops: readonly RenderPlanHop[]
244
+ }
245
+
246
+ const TELEPORT_TYPES: ReadonlySet<string> = new Set(["teleport-send", "teleport-receive"])
247
+ /** Nodes that re-cut the EDL they are given (per clip, row for row) and hand
248
+ * it on: the plan clip behind their output is the clip on their `edl` input. */
249
+ const EDL_PASS_THROUGH_TYPES: ReadonlySet<string> = new Set(["camera-switch"])
250
+
251
+ function outputModeOf(data: unknown): string | undefined {
252
+ const mode = data && typeof data === "object" ? (data as { outputMode?: unknown }).outputMode : undefined
253
+ return typeof mode === "string" ? mode : undefined
254
+ }
255
+
256
+ /**
257
+ * The Edit Plan whose clips a render's `edl` input comes from, and the wires
258
+ * that pick them: up the LAST wire on its `edl` handle (both engines keep the
259
+ * last value), through teleports and Camera Switch. `undefined` when the EDL
260
+ * comes from anything else.
261
+ */
262
+ export function renderPlanPath(
263
+ renderId: string,
264
+ nodes: readonly RenderGraphNode[],
265
+ edges: readonly RenderGraphEdge[],
266
+ ): RenderPlanPath | undefined {
267
+ const byId = new Map(nodes.map((n) => [n.id, n]))
268
+ // The last wire on a node's `edl` handle (the value both engines keep).
269
+ const lastEdlInto = (id: string): RenderGraphEdge | undefined =>
270
+ edges.filter((e) => e.target === id && e.targetHandle === "edl").at(-1)
271
+ // A teleport's one input — the wire both engines' teleport walks follow.
272
+ const teleportInput = (id: string): RenderGraphEdge | undefined => edges.find((e) => e.target === id)
273
+ const visited = new Set<string>()
274
+ const hops: RenderPlanHop[] = []
275
+ let consumer = lastEdlInto(renderId)
276
+ let edge = consumer
277
+ while (edge && consumer) {
278
+ const node = byId.get(edge.source)
279
+ if (!node || visited.has(node.id)) return undefined
280
+ visited.add(node.id)
281
+ if (TELEPORT_TYPES.has(node.type ?? "")) {
282
+ edge = teleportInput(node.id)
283
+ continue
284
+ }
285
+ // The resolvers read the consumer wire's mode and selector, and default the
286
+ // mode from the node behind the teleports on the handle it is wired from.
287
+ const mode = outputModeOf(consumer.data) ?? defaultEdgeOutputMode(node.type, edge.sourceHandle)
288
+ hops.unshift({ edge: consumer, each: mode === "each", ...(node.type ? { source: node.type } : {}) })
289
+ if (node.type === "edit-plan") return { planId: node.id, hops }
290
+ if (!EDL_PASS_THROUGH_TYPES.has(node.type ?? "")) return undefined
291
+ consumer = lastEdlInto(node.id)
292
+ edge = consumer
293
+ }
294
+ return undefined
295
+ }
296
+
297
+ /** Whether every pass-through node on the path (Camera Switch: the target of
298
+ * every hop but the last) ran in this run (`ranIds`) — the same-run rule. */
299
+ function passThroughRan(path: RenderPlanPath, ranIds: ReadonlySet<string>): boolean {
300
+ return path.hops.slice(0, -1).every((hop) => ranIds.has(hop.edge.target))
301
+ }
302
+
303
+ /** The Edit Plan whose clips a render's `edl` input comes from (`renderPlanPath`). */
304
+ export function renderPlanNodeId(
305
+ renderId: string,
306
+ nodes: readonly RenderGraphNode[],
307
+ edges: readonly RenderGraphEdge[],
308
+ ): string | undefined {
309
+ return renderPlanPath(renderId, nodes, edges)?.planId
310
+ }
311
+
312
+ /** A dropped clip's place in a plan list (TA16): `""` or `null`. Clips are
313
+ * objects as well as JSON text, so this is never "not a string". */
314
+ const isHole = (clip: unknown): boolean => clip == null || (typeof clip === "string" && !clip.trim())
315
+
316
+ /** The clips left once the holes are dropped, in order. */
317
+ const keptClips = (clips: readonly unknown[]): readonly unknown[] => clips.filter((clip) => !isHole(clip))
318
+
319
+ /**
320
+ * The clips a wire that hands on ONE value passes, as both input resolvers pick
321
+ * it (decided 2026-10-05): `item` the clip at its index (its range / list
322
+ * selector does not apply), legacy `item:N` the N-th from 0 (else the first),
323
+ * `all` what its selector leaves (one value only when that is one clip), and
324
+ * "Selected" (`last`) the source's own output — an Edit Plan's is its first
325
+ * KEPT clip, the scalar both engines read off a list with holes. A Camera Switch that ran per clip keeps a different clip as its own
326
+ * output in each engine (the server its first, the editor the last to land),
327
+ * so a Selected wire out of it names a clip only when it had one.
328
+ */
329
+ function singlePick(clips: readonly unknown[], hop: RenderPlanHop): readonly unknown[] {
330
+ const data = hop.edge.data as (SelectorFields & { itemIndex?: unknown }) | undefined
331
+ const mode = outputModeOf(hop.edge.data)
332
+ if (mode === "item") {
333
+ const expr = typeof data?.itemIndex === "string" ? data.itemIndex : "1"
334
+ return [clips[resolveIndex(expr, clips.length)] ?? clips[0]]
335
+ }
336
+ if (mode?.startsWith("item:")) return [clips[parseInt(mode.slice(5), 10)] ?? clips[0]]
337
+ if (mode === "all") return selectListItems(clips as string[], data)
338
+ if (hop.source === "edit-plan") return keptClips(clips).slice(0, 1)
339
+ return clips.length === 1 ? clips : []
340
+ }
341
+
342
+ /**
343
+ * The plan value a render iteration reads. `plan` is the plan's output as the
344
+ * engine holds it: a clip set's clips (a list of EDLs, objects or JSON strings,
345
+ * `""` at a dropped clip), or a Tighten plan's one EDL — which every wire hands
346
+ * on as it is. `hops` are the wires from the plan down (`renderPlanPath`). Each
347
+ * "each" wire hands on the clips its selector picks — Camera Switch's row k is
348
+ * row k of ITS selection, the render's row k row k of its own — exactly as both
349
+ * input resolvers select before they index. A wire that hands on one value
350
+ * hands on the clip it picks (`singlePick`), and names one only when exactly
351
+ * one is picked.
352
+ *
353
+ * Holes (a dropped clip, TA16) follow the row space each wire really hands on.
354
+ * A pass-through node (Camera Switch: every hop but the last) runs once per
355
+ * KEPT clip of its selection and both engines store its batch by iteration, so
356
+ * the next wire reads a list without the holes. The last wire, into the
357
+ * render, is not compacted: a render wired straight to the plan is rowed in
358
+ * the plan's own rows, holes included.
359
+ *
360
+ * With a row on an "each" wire, the row's clip; a row past the clips starts
361
+ * over from the first, as the resolvers read it. With no row (a render run
362
+ * once, or Repeat xN with nothing list-driven), the clip only when exactly one
363
+ * KEPT clip is left — the scalar both engines read — and any other plan names
364
+ * no single clip. An empty row names nothing.
365
+ */
366
+ export function renderPlanValue(
367
+ plan: unknown,
368
+ row: number | undefined,
369
+ hops: readonly RenderPlanHop[] = [],
370
+ ): unknown {
371
+ if (!Array.isArray(plan)) return plan === null || typeof plan !== "object" ? undefined : plan
372
+ let clips: readonly unknown[] = plan
373
+ for (const [i, hop] of hops.entries()) {
374
+ if (clips.length === 0) return undefined
375
+ if (hop.each) {
376
+ clips = selectListItems(clips as string[], hop.edge.data as SelectorFields | undefined)
377
+ // Into a pass-through node: it hands on its batch by iteration, one per kept clip.
378
+ if (i < hops.length - 1) clips = keptClips(clips)
379
+ } else {
380
+ clips = singlePick(clips, hop)
381
+ if (clips.length !== 1) return undefined
382
+ }
383
+ }
384
+ if (clips.length === 0) return undefined
385
+ const rowed = row !== undefined && (hops.at(-1)?.each ?? true)
386
+ if (rowed) {
387
+ const clip = clips[row % clips.length]
388
+ return isHole(clip) ? undefined : clip
389
+ }
390
+ const kept = keptClips(clips)
391
+ return kept.length === 1 ? kept[0] : undefined
392
+ }
393
+
394
+ /** The clip a render iteration reads, as a key (`edlSpanKey` of the clip
395
+ * `renderPlanValue` picks). A Tighten plan names no clip. */
396
+ export function renderClipKey(
397
+ plan: unknown,
398
+ row: number | undefined,
399
+ hops: readonly RenderPlanHop[] = [],
400
+ ): string | undefined {
401
+ if (!Array.isArray(plan)) return undefined
402
+ const clip = renderPlanValue(plan, row, hops)
403
+ return clip === undefined ? undefined : planClipKeyAt([clip], 0)
404
+ }
405
+
406
+ /**
407
+ * The clip key a render iteration stamps — the ONE rule both engines call: the
408
+ * Edit Plan behind its `edl` wire (`renderPlanPath`), its clips as the engine
409
+ * holds them (`planClips`), picked by every wire on the way and indexed by the
410
+ * iteration's list row (`renderClipKey`). Pass the row only when a list drives
411
+ * it, never an iteration number.
412
+ */
413
+ export function renderPlanClipKey(
414
+ renderId: string,
415
+ nodes: readonly RenderGraphNode[],
416
+ edges: readonly RenderGraphEdge[],
417
+ planClips: (planNode: RenderGraphNode) => unknown,
418
+ row: number | undefined,
419
+ ): string | undefined {
420
+ const path = renderPlanPath(renderId, nodes, edges)
421
+ const planNode = path ? nodes.find((n) => n.id === path.planId) : undefined
422
+ if (!path || !planNode) return undefined
423
+ return renderClipKey(planClips(planNode), row, path.hops)
424
+ }
425
+
426
+ /**
427
+ * The clip key of EVERY iteration of a render's fan-out, row-aligned with its
428
+ * batch: `rows[k]` is iteration k's list row (`FanOutPlan.rows`), as both
429
+ * engines hand it to `renderPlanClipKey` (never the iteration number). Both
430
+ * engines stamp it on each batch row up front, so a row that FAILED still
431
+ * names its clip (decided 2026-10-06): the batch has one row per run, not one
432
+ * per plan clip, and a reader matches rows to clips by this key, never by
433
+ * position. The plan is read once, as the run held it when the fan-out began.
434
+ */
435
+ export function renderPlanRowClipKeys(
436
+ renderId: string,
437
+ nodes: readonly RenderGraphNode[],
438
+ edges: readonly RenderGraphEdge[],
439
+ planClips: (planNode: RenderGraphNode) => unknown,
440
+ rows: ReadonlyArray<number | undefined>,
441
+ ranIds: ReadonlySet<string>,
442
+ ): Array<string | undefined> {
443
+ const path = renderPlanPath(renderId, nodes, edges)
444
+ const planNode = path ? nodes.find((n) => n.id === path.planId) : undefined
445
+ // The same-run rule (`renderPlanBasis`): behind a pass-through node that did
446
+ // not run in this run the render iterates that node's SAVED batch, which can
447
+ // come from an older review, so the plan as it is now cannot name its rows.
448
+ if (!path || !planNode || !passThroughRan(path, ranIds)) return rows.map(() => undefined)
449
+ const plan = planClips(planNode)
450
+ return rows.map((row) => renderClipKey(plan, row, path.hops))
451
+ }
452
+
453
+ /** The quality a render runs at: its `quality` setting as the run holds it
454
+ * ("proxy" is a Preview; anything else renders a final). */
455
+ export function renderRunQuality(data: Readonly<Record<string, unknown>> | undefined): RenderQuality {
456
+ return data?.quality === "proxy" ? "proxy" : "final"
457
+ }
458
+
459
+ /**
460
+ * What every row of a render's fan-out batch is stamped with before it runs
461
+ * (decided 2026-10-06): the quality the run renders at and the clip the row is
462
+ * sent for (`renderPlanRowClipKeys`, absent when the run cannot name it). Both
463
+ * engines write it on every row; a landed take's own stamp wins over it, so a
464
+ * row that FAILED still says which clip, and at which quality, it was sent for.
465
+ */
466
+ export function renderSentRowStamps(
467
+ quality: RenderQuality,
468
+ clipKeys: ReadonlyArray<string | undefined>,
469
+ ): RunResultRowStamp[] {
470
+ return clipKeys.map((clipKey) => ({ quality, ...(clipKey ? { clipKey } : {}) }))
471
+ }
472
+
473
+ // ─────────────────────────────────────────────────────────────────────────
474
+ // The bases a render is stamped with (A3-1)
475
+ // ─────────────────────────────────────────────────────────────────────────
476
+
477
+ /** `renderReadBasis` of every plan object already hashed (see `editPlanBasis`:
478
+ * plan objects are never mutated in place). Keyed by the object the caller
479
+ * holds, since stripping `meta` makes a new one every time. */
480
+ const readBasisByValue = new WeakMap<object, string>()
481
+
482
+ const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v)
483
+
484
+ /**
485
+ * The fingerprint of the plan value a render read (R2 a, decided 2026-10-06):
486
+ * `editPlanBasis` of the value with its top-level `meta` removed. No renderer
487
+ * reads `meta`, so an edited hook (a clip's `meta.hook`, text only) leaves it
488
+ * unchanged. A clip given as JSON text reads as its object. `undefined` for
489
+ * anything that is not one plan object (a list, a scalar, unparsable text).
490
+ */
491
+ export function renderReadBasis(value: unknown): string | undefined {
492
+ let v = value
493
+ if (typeof v === "string") {
494
+ if (!v.trim()) return undefined
495
+ try {
496
+ v = JSON.parse(v)
497
+ } catch {
498
+ return undefined
499
+ }
500
+ }
501
+ if (!isPlainObject(v)) return undefined
502
+ const cached = readBasisByValue.get(v)
503
+ if (cached !== undefined) return cached
504
+ const { meta: _meta, ...rest } = v
505
+ const basis = editPlanBasis(rest)
506
+ readBasisByValue.set(v, basis)
507
+ return basis
508
+ }
509
+
510
+ /** A render's own settings, as it reads them. */
511
+ export interface RenderSettingsInput {
512
+ /** Any value other than "audio" is a video render. */
513
+ readonly output?: unknown
514
+ /** The default crossfade in ms; missing, negative or non-finite is a hard cut. */
515
+ readonly crossfadeMs?: unknown
516
+ }
517
+
518
+ /**
519
+ * The fingerprint of a render's own settings (R19 a, decided 2026-10-06):
520
+ * `editPlanBasis({crossfadeMs, output, sources})`. `sources` is the EFFECTIVE
521
+ * source list — the URL of each source of the effective EDL the render cuts,
522
+ * in order, with the `sources` wires' overrides applied (`""` for a source with
523
+ * no URL). A change to any of the three changes the cut while the plan value
524
+ * stays equal. The settings are read as the render reads them: whole ms, a
525
+ * hard cut when the crossfade is missing.
526
+ */
527
+ export function renderSettingsBasis(settings: RenderSettingsInput, sources: ReadonlyArray<string | undefined> = []): string {
528
+ const raw = settings.crossfadeMs
529
+ const crossfadeMs = typeof raw === "number" && Number.isFinite(raw) ? Math.max(0, Math.round(raw)) : 0
530
+ return editPlanBasis({
531
+ crossfadeMs,
532
+ output: settings.output === "audio" ? "audio" : "video",
533
+ sources: sources.map((url) => (typeof url === "string" ? url : "")),
534
+ })
535
+ }
536
+
537
+ /**
538
+ * The plan basis a render iteration stamps — the ONE rule both engines call
539
+ * (R1 a, decided 2026-10-06). The plan value the iteration read
540
+ * (`renderPlanValue` of `planOutput` — the plan's output as the run holds it —
541
+ * along `renderPlanPath`), as `renderReadBasis`.
542
+ *
543
+ * THE SAME-RUN RULE. Behind a pass-through node (Camera Switch) the render reads
544
+ * that node's output, which is the plan's current value only when the node ran
545
+ * in the same run as the render; a SAVED output can come from an older plan.
546
+ * So the basis is stamped only when every pass-through node on the path is in
547
+ * `ranIds`, the nodes executed in the render's run, and is `undefined`
548
+ * otherwise — the take then reads as unknown (stale), never as current. A
549
+ * render wired straight to the plan (through teleports at most) reads the
550
+ * plan's output itself and is always stamped.
551
+ */
552
+ export function renderPlanBasis(
553
+ renderId: string,
554
+ nodes: readonly RenderGraphNode[],
555
+ edges: readonly RenderGraphEdge[],
556
+ planOutput: (planNode: RenderGraphNode) => unknown,
557
+ row: number | undefined,
558
+ ranIds: ReadonlySet<string>,
559
+ ): string | undefined {
560
+ const path = renderPlanPath(renderId, nodes, edges)
561
+ const planNode = path ? nodes.find((n) => n.id === path.planId) : undefined
562
+ if (!path || !planNode) return undefined
563
+ if (!passThroughRan(path, ranIds)) return undefined
564
+ return renderReadBasis(renderPlanValue(planOutput(planNode), row, path.hops))
565
+ }