@nodaro/shared 3.27.0 → 3.31.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 (50) hide show
  1. package/dist/index.cjs +1050 -105
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +801 -46
  4. package/dist/index.d.ts +801 -46
  5. package/dist/index.js +950 -106
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/entity-image-handle.test.ts +61 -1
  9. package/src/__tests__/json-kinds.test.ts +10 -0
  10. package/src/__tests__/model-seed-capability.test.ts +34 -0
  11. package/src/__tests__/node-preset-extract.test.ts +8 -0
  12. package/src/__tests__/node-run-routes.test.ts +63 -0
  13. package/src/__tests__/node-runtime-keys.test.ts +61 -0
  14. package/src/__tests__/pitch-tempo-pricing.test.ts +62 -0
  15. package/src/__tests__/presentation-utils.test.ts +14 -0
  16. package/src/__tests__/producer-types.test.ts +15 -0
  17. package/src/__tests__/render-nodes.test.ts +38 -4
  18. package/src/__tests__/seedance-draft.test.ts +74 -0
  19. package/src/__tests__/ugc-clip-saved-list.test.ts +19 -0
  20. package/src/__tests__/ugc-node-wires.test.ts +600 -0
  21. package/src/__tests__/ugc-run-state.test.ts +80 -3
  22. package/src/__tests__/video-depth.test.ts +146 -0
  23. package/src/__tests__/video-mask.test.ts +77 -0
  24. package/src/__tests__/workflow-export-strip.test.ts +14 -0
  25. package/src/credit-estimators/index.ts +10 -0
  26. package/src/credit-estimators/pitch-tempo.ts +68 -0
  27. package/src/credit-identifiers.ts +32 -7
  28. package/src/entity-image-handle.ts +48 -1
  29. package/src/fan-out-rows.ts +2 -0
  30. package/src/index.ts +15 -1
  31. package/src/json-kinds.ts +9 -0
  32. package/src/mask-composite.ts +108 -0
  33. package/src/model-catalog.ts +101 -2
  34. package/src/model-constants.ts +3 -0
  35. package/src/model-tree.ts +2 -0
  36. package/src/node-mappable-fields.ts +2 -0
  37. package/src/node-preset-export.ts +2 -2
  38. package/src/node-preset-extract.ts +6 -4
  39. package/src/node-run-routes.ts +76 -0
  40. package/src/node-runtime-keys.ts +42 -1
  41. package/src/presentation-utils.ts +6 -2
  42. package/src/producer-types.ts +19 -0
  43. package/src/render-nodes.ts +14 -5
  44. package/src/seedance-draft.ts +64 -0
  45. package/src/social-post.ts +13 -0
  46. package/src/ugc-node-wires.ts +623 -0
  47. package/src/ugc-run-state.ts +60 -5
  48. package/src/video-depth.ts +151 -0
  49. package/src/video-mask.ts +96 -0
  50. package/src/workflow-export.ts +3 -1
@@ -0,0 +1,623 @@
1
+ /**
2
+ * The UGC node wires: every request body the five UGC nodes send and every
3
+ * output they hand on, as ONE pure implementation that both engines (the
4
+ * workflow orchestrator and the editor) call, so the two can never disagree.
5
+ *
6
+ * Content-free. A creator record is read only for `v`, `gender` and
7
+ * `identityImages`, a plan only for `v`, a clip ticket only for `v`, `index`
8
+ * and `durationSec`; every other key is opaque and passes through as it came.
9
+ * Every UGC-private JSON a node emits carries `v: 1`, and a wire with another
10
+ * `v` is refused, never guessed at.
11
+ */
12
+ import type { CaptionPlan } from "./caption-plan.js"
13
+ import { fanOutItemMeta, type ClipNote } from "./fan-out-meta.js"
14
+ import { DEFAULT_TRANSCRIBE_NODE_PROVIDER } from "./model-constants.js"
15
+ import { ugcPickPending } from "./ugc-run-state.js"
16
+
17
+ /** A UGC call that reached a deployment without the UGC routes (the router's 404). */
18
+ export const UGC_NOT_SERVED_MESSAGE = "UGC videos are a Nodaro Cloud feature and are not served on this deployment."
19
+ /** A wire whose `v` this app does not read. */
20
+ export const UGC_VERSION_MESSAGE = "This workflow was made with a newer version of the UGC nodes."
21
+ /** An answer this app cannot run: a tool it does not know, or a shape it cannot read. */
22
+ export const UGC_NEWER_APP_MESSAGE = "This step needs a newer app version."
23
+ /** A creator pick whose options are gone (another run replaced them, or they were never this node's). */
24
+ export const UGC_PICK_GONE_MESSAGE = "These creator options are no longer available. Run UGC Creator again."
25
+ /** UGC Clips with no creator on its creator input (UGC Creator has not run, or waits for a pick). */
26
+ export const UGC_CREATOR_MISSING_MESSAGE = "UGC Creator has no creator yet. Run it, or pick one of its options."
27
+ /** UGC Script's target length in seconds when the node holds none: the node's default (the route requires a length). */
28
+ export const UGC_SCRIPT_DEFAULT_TARGET_SEC = 15
29
+ /** The range of a UGC script's length, in whole seconds: the script route's, and a plan's own. */
30
+ export const UGC_SCRIPT_MIN_TARGET_SEC = 4
31
+ export const UGC_SCRIPT_MAX_TARGET_SEC = 300
32
+
33
+ const MINOR_AGE_MESSAGE = "That age can't be used: UGC creators are adults only."
34
+ const NEEDS_GENDER = "Choose woman or man."
35
+ const NEEDS_PHOTO = "Connect or upload a photo of yourself."
36
+ const NEEDS_CATEGORY = "Run UGC Script first, or pick a product category."
37
+ const NEEDS_SITE = "Add the product name or website."
38
+ /** The opening of the sentence UGC Clips fails with when the plugin refuses the script: "<this> <each error and its fix>". */
39
+ export const UGC_SCRIPT_NEEDS_CHANGES = "The script needs changes:"
40
+ const NEEDS_PLAN_OUT = "Connect the Script (sized) output of UGC Clips."
41
+ const NEEDS_PLAN = "Connect the Script output of UGC Script."
42
+ const NEEDS_TICKET = "Connect the Clips output of UGC Clips."
43
+ const NEEDS_VIDEO = "Connect the joined video."
44
+ const NEEDS_TRANSCRIPT = "Connect the Transcript output of UGC Clips."
45
+
46
+ /**
47
+ * Every fixed sentence a UGC node fails with, by id: the English both engines write on the node.
48
+ * The editor shows each in the person's language by its id. Not listed: the sentence that opens
49
+ * with `UGC_SCRIPT_NEEDS_CHANGES` (the plugin's own words finish it), a route's own message, and
50
+ * "UGC step failed (<status>)".
51
+ */
52
+ export const UGC_NODE_MESSAGES = Object.freeze({
53
+ notServed: UGC_NOT_SERVED_MESSAGE,
54
+ version: UGC_VERSION_MESSAGE,
55
+ newerApp: UGC_NEWER_APP_MESSAGE,
56
+ pickGone: UGC_PICK_GONE_MESSAGE,
57
+ creatorMissing: UGC_CREATOR_MISSING_MESSAGE,
58
+ minorAge: MINOR_AGE_MESSAGE,
59
+ needsGender: NEEDS_GENDER,
60
+ needsPhoto: NEEDS_PHOTO,
61
+ needsCategory: NEEDS_CATEGORY,
62
+ needsSite: NEEDS_SITE,
63
+ needsPlanOut: NEEDS_PLAN_OUT,
64
+ needsPlan: NEEDS_PLAN,
65
+ needsTicket: NEEDS_TICKET,
66
+ needsVideo: NEEDS_VIDEO,
67
+ needsTranscript: NEEDS_TRANSCRIPT,
68
+ } as const)
69
+
70
+ /** The id of a fixed sentence a UGC node fails with (`UGC_NODE_MESSAGES`). */
71
+ export type UgcNodeMessageId = keyof typeof UGC_NODE_MESSAGES
72
+
73
+ /** UGC Script's screenshot inputs, in card order. */
74
+ export const UGC_SCREENSHOT_HANDLES: readonly string[] = [
75
+ "screenshot", "screenshot2", "screenshot3", "screenshot4", "screenshot5", "screenshot6", "screenshot7", "screenshot8",
76
+ ]
77
+
78
+ /** Per UGC type, the output an edge with no source handle reads. */
79
+ export const UGC_PRIMARY_HANDLE: Readonly<Record<string, string>> = {
80
+ "ugc-creator": "creator",
81
+ "ugc-script": "plan",
82
+ "ugc-clips": "clips",
83
+ "ugc-clip": "video-out",
84
+ "ugc-cards": "layerPlan",
85
+ }
86
+
87
+ /** A UGC node's outputs: handle id → the value that handle carries (a JSON string, text or a URL). */
88
+ export type UgcOutputs = Readonly<Record<string, string>>
89
+
90
+ type Obj = Record<string, unknown>
91
+ const isObject = (x: unknown): x is Obj => !!x && typeof x === "object" && !Array.isArray(x)
92
+
93
+ /**
94
+ * The length a saved UGC plan was written to: its own `targetDurationSec`, a whole number of
95
+ * seconds in the script's range. Besides the lines (the opening line, each beat's line, the
96
+ * closing line), one of the two keys of a plan the app reads (the other: whether each beat carries
97
+ * a screenshot, `ugcPlanScreenshotCount`): a script that hands on its saved plan is priced at the
98
+ * plan's length, and shows it, never at the length setting, which may have changed since. Takes
99
+ * the plan or its wire (a JSON string); undefined for anything that is not a plan carrying a length.
100
+ */
101
+ export function ugcPlanLengthSec(plan: unknown): number | undefined {
102
+ const value = savedPlanOf(plan)
103
+ if (!value) return undefined
104
+ const sec = value.targetDurationSec
105
+ return typeof sec === "number" && Number.isInteger(sec) && sec >= UGC_SCRIPT_MIN_TARGET_SEC && sec <= UGC_SCRIPT_MAX_TARGET_SEC ? sec : undefined
106
+ }
107
+
108
+ /**
109
+ * How many of a saved UGC plan's beats carry a screenshot: the screenshot cards the plan was
110
+ * written with. Read beat by beat: a beat carries one when its `screenshot` is an object, as the
111
+ * plan's own screenshots are (whatever it names); a beat that is not an object, or whose screenshot
112
+ * is anything else, carries none — and never makes the rest unreadable. A plan whose beats carry
113
+ * none is a talking-head plan (0). Read, like its length, so a script that hands on its saved plan
114
+ * is priced at the screenshots that plan holds, never at the script's wires, which may have changed
115
+ * since. Takes the plan or its wire (a JSON string); undefined only for a plan with no beats to read
116
+ * and for anything that is not a plan.
117
+ */
118
+ export function ugcPlanScreenshotCount(plan: unknown): number | undefined {
119
+ const value = savedPlanOf(plan)
120
+ if (!value || !Array.isArray(value.beats)) return undefined
121
+ return value.beats.filter((beat) => isObject(beat) && isObject(beat.screenshot)).length
122
+ }
123
+
124
+ /** A saved plan, or its wire (a JSON string), as an object; undefined for anything else. */
125
+ function savedPlanOf(plan: unknown): Obj | undefined {
126
+ let value: unknown = plan
127
+ if (typeof value === "string") {
128
+ try {
129
+ value = JSON.parse(value)
130
+ } catch {
131
+ return undefined
132
+ }
133
+ }
134
+ return isObject(value) ? value : undefined
135
+ }
136
+ /** A string with something in it; an empty or blank field or input counts as absent. */
137
+ const filled = (x: unknown): string | undefined => (typeof x === "string" && x.trim() !== "" ? x : undefined)
138
+
139
+ /**
140
+ * What an edge from a UGC node reads, on both engines: the value of the pip it leaves — an edge
141
+ * with no source handle reads the node's primary output — from the node's outputs by pip. Only a
142
+ * pip the outputs hold as a string ("" included: an empty transcript is a value); an inherited
143
+ * key or a non-string is no value.
144
+ */
145
+ export function ugcPipValue(outputs: unknown, sourceType: string, sourceHandle?: string | null): string | undefined {
146
+ const pip = sourceHandle || (Object.hasOwn(UGC_PRIMARY_HANDLE, sourceType) ? UGC_PRIMARY_HANDLE[sourceType] : undefined)
147
+ if (pip === undefined || !isObject(outputs) || !Object.hasOwn(outputs, pip)) return undefined
148
+ const value = outputs[pip]
149
+ return typeof value === "string" ? value : undefined
150
+ }
151
+
152
+ /**
153
+ * A UGC wire (a JSON string or an object) → its value when it is an object with `v: 1`.
154
+ * Another `v` → the version message. Anything that is not a UGC wire at all (nothing
155
+ * connected, not JSON, no `v`) → `unreadable`, which a node words as the input it needs.
156
+ */
157
+ export function readUgcWire(raw: unknown, unreadable: string = UGC_VERSION_MESSAGE): { value: Record<string, unknown> } | { error: string } {
158
+ let parsed: unknown = raw
159
+ if (typeof raw === "string") {
160
+ try {
161
+ parsed = JSON.parse(raw)
162
+ } catch {
163
+ return { error: unreadable }
164
+ }
165
+ }
166
+ if (!isObject(parsed) || parsed.v === undefined) return { error: unreadable }
167
+ if (parsed.v !== 1) return { error: UGC_VERSION_MESSAGE }
168
+ return { value: parsed }
169
+ }
170
+
171
+ /** The route's `{ error: { code, message } }` (or a framework error's top-level `message`). */
172
+ function routeErrorOf(body: string): { code?: string; message?: string } {
173
+ let parsed: unknown
174
+ try {
175
+ parsed = JSON.parse(body)
176
+ } catch {
177
+ return {}
178
+ }
179
+ if (!isObject(parsed)) return {}
180
+ if (isObject(parsed.error)) {
181
+ const { code, message } = parsed.error
182
+ return { code: typeof code === "string" ? code : undefined, message: filled(message) }
183
+ }
184
+ return { message: filled(parsed.message) }
185
+ }
186
+
187
+ /**
188
+ * A failed UGC call → the sentence the node fails with. A 404 that names no error code is
189
+ * the router's (the route is not registered here) → the Cloud sentence; a route's own 404
190
+ * names a code and keeps its message. `minor_age_refused` → the adults-only sentence. A 4xx
191
+ * or 503 → the route's message. Anything else → "UGC step failed (<status>)".
192
+ */
193
+ export function ugcFailure(status: number, body: string): string {
194
+ const error = routeErrorOf(body)
195
+ if (status === 404 && error.code === undefined) return UGC_NOT_SERVED_MESSAGE
196
+ if (error.code === "minor_age_refused") return MINOR_AGE_MESSAGE
197
+ if ((status === 503 || (status >= 400 && status < 500)) && error.message) return error.message
198
+ return `UGC step failed (${status})`
199
+ }
200
+
201
+ // ── UGC Creator ──────────────────────────────────────────────────────────────
202
+
203
+ /**
204
+ * The pickers whose own set fields shape a sampled creator: the picker types UGC Creator's
205
+ * `pickers` input takes (the route takes no other). One list for the editor's connection rule
206
+ * and both engines' input resolvers.
207
+ */
208
+ export const UGC_CREATOR_PICKER_TYPES: ReadonlySet<string> = new Set(["person", "styling", "setting", "lighting"])
209
+
210
+ /** The UGC Creator node-data keys its request body reads. */
211
+ export interface UgcCreatorFields {
212
+ readonly source?: string
213
+ readonly gender?: string
214
+ readonly photoUrl?: string
215
+ readonly categoryOverride?: string
216
+ readonly seed?: number
217
+ readonly keepResult?: boolean
218
+ readonly result?: Readonly<Record<string, unknown>>
219
+ /** The options a draw left waiting for the pick (run state): read only for `previous`. */
220
+ readonly candidates?: unknown
221
+ }
222
+
223
+ /** The traits of the latest creator the person saw: the first waiting option's, else the last result's (Keep off). */
224
+ function previousTraits(data: UgcCreatorFields): unknown {
225
+ if (ugcPickPending(data)) {
226
+ const first: unknown = (data.candidates as readonly unknown[])[0]
227
+ const record = isObject(first) ? first.record : undefined
228
+ return isObject(record) ? record.traits : undefined
229
+ }
230
+ return !data.keepResult && isObject(data.result) ? data.result.traits : undefined
231
+ }
232
+
233
+ /** The wired pickers that set a field (their own fields, as the resolver read them); undefined when none did. */
234
+ function setPickers(pickers: Record<string, Record<string, unknown>> | undefined): Record<string, Record<string, unknown>> | undefined {
235
+ if (!pickers) return undefined
236
+ const set = Object.entries(pickers).filter(([, fields]) => isObject(fields) && Object.keys(fields).length > 0)
237
+ return set.length > 0 ? Object.fromEntries(set) : undefined
238
+ }
239
+
240
+ /**
241
+ * The `/v1/ugc/creator` body. A photo: the wired photo, else the node's own. A sampled
242
+ * creator: the product category (the node's override, else the wired one), the pickers that
243
+ * set a field, the node's seed, and the traits of the latest creator the person saw as
244
+ * `previous`, so the next one differs: the first option waiting for the pick, else — on a
245
+ * re-run that does not keep the result — the last creator's. Refuses before any call.
246
+ */
247
+ export function ugcCreatorBody(input: {
248
+ data: UgcCreatorFields
249
+ photoUrl?: string
250
+ category?: string
251
+ pickers?: Record<string, Record<string, unknown>>
252
+ }): { body: Record<string, unknown> } | { error: string } {
253
+ const { data } = input
254
+ const gender = data.gender
255
+ if (gender !== "woman" && gender !== "man") return { error: NEEDS_GENDER }
256
+ if (data.source === "photo") {
257
+ const imageUrl = filled(input.photoUrl) ?? filled(data.photoUrl)
258
+ if (!imageUrl) return { error: NEEDS_PHOTO }
259
+ return { body: { source: { kind: "photo", imageUrl, gender } } }
260
+ }
261
+ const productCategory = filled(data.categoryOverride) ?? filled(input.category)
262
+ if (!productCategory) return { error: NEEDS_CATEGORY }
263
+ const pickers = setPickers(input.pickers)
264
+ const traits = previousTraits(data)
265
+ return {
266
+ body: {
267
+ ...(typeof data.seed === "number" ? { seed: data.seed } : {}),
268
+ source: {
269
+ kind: "sampled",
270
+ gender,
271
+ productCategory,
272
+ ...(pickers ? { pickers } : {}),
273
+ ...(isObject(traits) ? { previous: traits } : {}),
274
+ },
275
+ },
276
+ }
277
+ }
278
+
279
+ /**
280
+ * The creator the node hands on: the record (`creator`, v1) and its first image (`image`).
281
+ * `identityImages` are the images of the candidate the node hands on — the picked one where
282
+ * a person picked. The record copies the listed fields only, so `candidates`, `fallback`,
283
+ * `pick` and `image` never reach the `creator` wire.
284
+ */
285
+ export function ugcCreatorOutputs(answer: Record<string, unknown>, identityImages: readonly string[]): { outputs: UgcOutputs; imageUrl: string; record: Record<string, unknown> } {
286
+ const record: Record<string, unknown> = {
287
+ v: 1,
288
+ kind: answer.kind,
289
+ gender: answer.gender,
290
+ identityImages: [...identityImages],
291
+ traits: answer.traits ?? null,
292
+ seed: answer.seed ?? null,
293
+ promptsVersion: answer.promptsVersion,
294
+ productCategory: answer.productCategory ?? null,
295
+ }
296
+ const imageUrl = identityImages[0] ?? ""
297
+ return { outputs: { creator: JSON.stringify(record), ...(imageUrl ? { image: imageUrl } : {}) }, imageUrl, record }
298
+ }
299
+
300
+ /** One builder call as the app runs it: `tool` and `args`, nothing else (a candidate's other keys, its model included, are never read). */
301
+ export interface UgcCreatorCall { readonly tool: string; readonly args: Readonly<Record<string, unknown>> }
302
+
303
+ /** What a creator answer asks the node to render. */
304
+ export interface UgcCreatorCandidateCalls {
305
+ /** Every candidate's image call, the primary first. One call (`image`) for an answer from before candidates; none for a photo. */
306
+ readonly calls: readonly UgcCreatorCall[]
307
+ /** The round's one moderation fallback: it runs once, and only when every candidate the run rendered was blocked. */
308
+ readonly fallback: UgcCreatorCall | null
309
+ /** "user": a person picks among `calls` where one can be asked; "primary": `calls[0]` alone; null: nothing to render (a photo). */
310
+ readonly pick: "user" | "primary" | null
311
+ }
312
+
313
+ const callOf = (raw: unknown): UgcCreatorCall | undefined => {
314
+ if (!raw || typeof raw !== "object") return undefined
315
+ const { tool, args } = raw as { tool?: unknown; args?: unknown }
316
+ if (typeof tool !== "string" || !args || typeof args !== "object" || Array.isArray(args)) return undefined
317
+ return { tool, args: args as Readonly<Record<string, unknown>> }
318
+ }
319
+ const fallbackOf = (image: unknown): unknown => (image && typeof image === "object" ? (image as { fallback?: unknown }).fallback : undefined)
320
+
321
+ /**
322
+ * A `/v1/ugc/creator` answer's image calls. Content-free: reads `image` (`tool`, `args`,
323
+ * `fallback`), `candidates[].tool|args`, `fallback` and `pick.how` — never a candidate's
324
+ * model. An answer without `candidates` (an older builder) renders `image` alone, as before.
325
+ */
326
+ export function ugcCreatorCandidates(answer: Readonly<Record<string, unknown>>): UgcCreatorCandidateCalls | { readonly error: string } {
327
+ const listed = answer.candidates
328
+ const noList = listed === undefined || listed === null || (Array.isArray(listed) && listed.length === 0)
329
+ const noImage = answer.image === undefined || answer.image === null
330
+ if (noList && noImage) return { calls: [], fallback: null, pick: null }
331
+ if (noList) {
332
+ const image = callOf(answer.image)
333
+ if (!image) return { error: UGC_NEWER_APP_MESSAGE }
334
+ return { calls: [image], fallback: callOf(fallbackOf(answer.image)) ?? null, pick: "primary" }
335
+ }
336
+ if (!Array.isArray(listed)) return { error: UGC_NEWER_APP_MESSAGE }
337
+ const calls = listed.map(callOf)
338
+ if (calls.some((c) => c === undefined)) return { error: UGC_NEWER_APP_MESSAGE }
339
+ const how = (answer.pick as { how?: unknown } | null | undefined)?.how
340
+ return {
341
+ calls: calls as UgcCreatorCall[],
342
+ fallback: callOf(answer.fallback) ?? callOf(fallbackOf(answer.image)) ?? null,
343
+ pick: how === "user" && calls.length > 1 ? "user" : "primary",
344
+ }
345
+ }
346
+
347
+ /** The calls a run renders: every candidate where a person is there to pick, else the primary alone. */
348
+ export function ugcCreatorCallsToRender(c: UgcCreatorCandidateCalls, opts: { readonly personPicks: boolean }): readonly UgcCreatorCall[] {
349
+ return opts.personPicks && c.pick === "user" ? c.calls : c.calls.slice(0, 1)
350
+ }
351
+
352
+ /** One rendered candidate that passed its checks, kept on the node until the person picks (run state, never a wire). */
353
+ export interface UgcCreatorCandidate { readonly imageUrl: string; readonly record: Readonly<Record<string, unknown>> }
354
+
355
+ export function ugcCreatorCandidate(answer: Readonly<Record<string, unknown>>, images: readonly string[]): UgcCreatorCandidate {
356
+ const out = ugcCreatorOutputs(answer as Record<string, unknown>, images)
357
+ return { imageUrl: out.imageUrl, record: out.record }
358
+ }
359
+
360
+ /** A UGC Creator run output that waits for the person's pick: two or more options (`ugcCandidates`). */
361
+ export function ugcAwaitsPick(output: unknown): boolean {
362
+ const candidates = isObject(output) ? output.ugcCandidates : undefined
363
+ return Array.isArray(candidates) && candidates.length >= 2
364
+ }
365
+
366
+ /** The person's pick, read back from node data (untrusted): a stale index, a foreign list or another version is refused. */
367
+ export function ugcCreatorPick(candidates: unknown, index: number):
368
+ { readonly result: Readonly<Record<string, unknown>>; readonly outputs: UgcOutputs; readonly imageUrl: string } | { readonly error: string } {
369
+ const entry: unknown = Array.isArray(candidates) && Number.isInteger(index) && index >= 0 ? candidates[index] : undefined
370
+ const imageUrl = (entry as { imageUrl?: unknown } | undefined)?.imageUrl
371
+ const record = (entry as { record?: unknown } | undefined)?.record
372
+ if (typeof imageUrl !== "string" || !record || typeof record !== "object" || Array.isArray(record)) return { error: UGC_PICK_GONE_MESSAGE }
373
+ const r = record as Record<string, unknown>
374
+ if (r.v !== 1) return { error: UGC_VERSION_MESSAGE }
375
+ if (!Array.isArray(r.identityImages) || r.identityImages[0] !== imageUrl) return { error: UGC_PICK_GONE_MESSAGE }
376
+ return { result: r, outputs: { creator: JSON.stringify(r), image: imageUrl }, imageUrl }
377
+ }
378
+
379
+ // ── UGC Script ───────────────────────────────────────────────────────────────
380
+
381
+ /**
382
+ * The `/v1/ugc/script` body: the product name or website (required), the screenshot slots
383
+ * in card order with the empty ones dropped, the product image when set, the target length
384
+ * (`UGC_SCRIPT_DEFAULT_TARGET_SEC` when the node holds no number), and English until a
385
+ * language can be chosen.
386
+ */
387
+ export function ugcScriptBody(input: {
388
+ site?: string
389
+ screenshots: ReadonlyArray<string | undefined>
390
+ productImage?: string
391
+ targetDurationSec?: number
392
+ }): { body: Record<string, unknown> } | { error: string } {
393
+ const site = filled(input.site)?.trim()
394
+ if (!site) return { error: NEEDS_SITE }
395
+ const productImage = filled(input.productImage)
396
+ return {
397
+ body: {
398
+ site,
399
+ screenshots: input.screenshots.filter((s): s is string => filled(s) !== undefined),
400
+ ...(productImage ? { productImage } : {}),
401
+ targetDurationSec: typeof input.targetDurationSec === "number" ? input.targetDurationSec : UGC_SCRIPT_DEFAULT_TARGET_SEC,
402
+ language: "en",
403
+ },
404
+ }
405
+ }
406
+
407
+ /** A finished UGC Script job → `plan` (the plan, v1) and `category` (text). */
408
+ export function ugcScriptOutputs(outputData: Record<string, unknown>): UgcOutputs {
409
+ const plan = outputData.plan
410
+ const category = filled(outputData.productCategory)
411
+ return {
412
+ ...(isObject(plan) ? { plan: JSON.stringify({ v: 1, ...plan }) } : {}),
413
+ ...(category ? { category } : {}),
414
+ }
415
+ }
416
+
417
+ /** UGC Script's last result, as the node holds it. */
418
+ export type UgcScriptResult = {
419
+ plan: Record<string, unknown>
420
+ productCategory: string
421
+ warnings: unknown[]
422
+ notes: string[]
423
+ rounds: number
424
+ }
425
+
426
+ /** A finished UGC Script job → the node's `result`, written the same by both engines; none without a plan. */
427
+ export function ugcScriptResult(outputData: Readonly<Record<string, unknown>>): UgcScriptResult | undefined {
428
+ const { plan, productCategory, warnings, notes, rounds } = outputData
429
+ if (!isObject(plan)) return undefined
430
+ return {
431
+ plan,
432
+ productCategory: filled(productCategory) ?? "",
433
+ warnings: Array.isArray(warnings) ? [...warnings] : [],
434
+ notes: Array.isArray(notes) ? notes.filter((n): n is string => typeof n === "string") : [],
435
+ rounds: typeof rounds === "number" && Number.isFinite(rounds) ? rounds : 0,
436
+ }
437
+ }
438
+
439
+ // ── Kept results ─────────────────────────────────────────────────────────────
440
+
441
+ /**
442
+ * What a UGC Creator or UGC Script with Keep on hands on instead of running: the outputs of
443
+ * the result it holds. Null — the node runs — when Keep is off, when the result holds nothing
444
+ * to hand on (a creator without its image, a script without its plan), and for a creator whose
445
+ * options wait for a pick, whatever Keep says. The creator record goes on unread; whoever reads
446
+ * it refuses another version.
447
+ */
448
+ export function ugcKeptOutputs(type: "ugc-creator" | "ugc-script", data: Readonly<Record<string, unknown>>): UgcOutputs | null {
449
+ if (type === "ugc-creator" && ugcPickPending(data)) return null
450
+ const result = data.keepResult === true ? data.result : undefined
451
+ if (!isObject(result)) return null
452
+ if (type === "ugc-creator") {
453
+ const image = Array.isArray(result.identityImages) ? filled(result.identityImages[0]) : undefined
454
+ return image ? { creator: JSON.stringify(result), image } : null
455
+ }
456
+ if (type === "ugc-script") return isObject(result.plan) ? ugcScriptOutputs(result) : null
457
+ return null
458
+ }
459
+
460
+ // ── UGC Clips ────────────────────────────────────────────────────────────────
461
+
462
+ /** The `/v1/ugc/clips` canvas body: the plan, the creator's gender, traits and images, and the picked voice. */
463
+ export function ugcClipsBody(input: { planWire: unknown; creatorWire: unknown; voiceId?: string }): { body: Record<string, unknown> } | { error: string } {
464
+ const plan = readUgcWire(input.planWire, NEEDS_PLAN)
465
+ if ("error" in plan) return plan
466
+ const creator = readUgcWire(input.creatorWire, UGC_CREATOR_MISSING_MESSAGE)
467
+ if ("error" in creator) return creator
468
+ const voiceId = filled(input.voiceId)
469
+ return {
470
+ body: {
471
+ plan: plan.value,
472
+ gender: creator.value.gender,
473
+ traits: creator.value.traits ?? null,
474
+ identityImages: creator.value.identityImages,
475
+ surface: "canvas",
476
+ ...(voiceId ? { voiceId } : {}),
477
+ },
478
+ }
479
+ }
480
+
481
+ /**
482
+ * The `/v1/ugc/clips` answer → the tickets (one per clip, as JSON strings), `clips` (the
483
+ * first), `plan-out` (`{ v: 1, plan, transcribeArgs }` for UGC Cards), `transcript`, and
484
+ * whether the plan has cards. An answer with errors → "The script needs changes: …" with each
485
+ * error and its fix; an answer without the parts UGC Cards needs fails here, before any clip
486
+ * is paid for.
487
+ */
488
+ export function ugcClipsOutputs(answer: Record<string, unknown>): { outputs: UgcOutputs; tickets: string[]; hasCards: boolean } | { error: string } {
489
+ const errors = Array.isArray(answer.errors) ? answer.errors : []
490
+ if (errors.length > 0) {
491
+ const said = errors.flatMap((e) => (isObject(e) ? [filled(e.message), filled(e.fix)] : [])).filter((s): s is string => s !== undefined)
492
+ return { error: said.length > 0 ? `${UGC_SCRIPT_NEEDS_CHANGES} ${said.join(" ")}` : UGC_NEWER_APP_MESSAGE }
493
+ }
494
+ const { tickets, sizedPlan, transcript, speechCheckCall } = answer
495
+ if (!Array.isArray(tickets) || tickets.length === 0 || !tickets.every(isObject) || !isObject(sizedPlan) || typeof transcript !== "string") {
496
+ return { error: UGC_NEWER_APP_MESSAGE }
497
+ }
498
+ const wires = tickets.map((t) => JSON.stringify(t))
499
+ // The speech check's arguments ride to UGC Cards' transcription unread (an answer without them: none).
500
+ const transcribeArgs = isObject(speechCheckCall) && isObject(speechCheckCall.args) ? speechCheckCall.args : {}
501
+ return {
502
+ outputs: { clips: wires[0]!, "plan-out": JSON.stringify({ v: 1, plan: sizedPlan, transcribeArgs }), transcript },
503
+ tickets: wires,
504
+ hasCards: answer.hasCards === true,
505
+ }
506
+ }
507
+
508
+ // ── UGC Clip ─────────────────────────────────────────────────────────────────
509
+
510
+ /**
511
+ * The `/v1/ugc/clip` body for one ticket: the ticket, `nonce` = how many times this clip was
512
+ * re-rendered (`rerender["<clip number>"]`, else 0) and `runKey` when one is given.
513
+ */
514
+ export function ugcClipBody(input: { ticketWire: unknown; rerender?: Readonly<Record<string, number>>; runKey?: string }):
515
+ { body: Record<string, unknown>; clipNumber: number; durationSec: number } | { error: string } {
516
+ const read = readUgcWire(input.ticketWire, NEEDS_TICKET)
517
+ if ("error" in read) return read
518
+ const ticket = read.value
519
+ const { index, durationSec } = ticket
520
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return { error: NEEDS_TICKET }
521
+ if (typeof durationSec !== "number" || !Number.isFinite(durationSec) || durationSec <= 0) return { error: NEEDS_TICKET }
522
+ const clipNumber = index + 1
523
+ const count = input.rerender?.[String(clipNumber)]
524
+ const nonce = typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : 0
525
+ const runKey = filled(input.runKey)
526
+ return { body: { ticket, nonce, ...(runKey ? { runKey } : {}) }, clipNumber, durationSec }
527
+ }
528
+
529
+ /**
530
+ * A finished UGC Clip job (`{ videoUrl, durationSec, clipWarnings, … }`) → `video-out`, the
531
+ * clip's real length (null when unknown) and its warnings ([] when it has none).
532
+ */
533
+ export function ugcClipOutputs(outputData: Record<string, unknown>): { outputs: UgcOutputs; videoUrl: string; durationSec: number | null; clipWarnings: string[] } {
534
+ const videoUrl = filled(outputData.videoUrl) ?? ""
535
+ const meta = fanOutItemMeta(outputData)
536
+ return { outputs: videoUrl ? { "video-out": videoUrl } : {}, videoUrl, durationSec: meta.durationSec, clipWarnings: [...meta.warnings] }
537
+ }
538
+
539
+ /**
540
+ * What a list read (a Bundle edge, a fold) takes from a UGC Clip's saved data, on both engines:
541
+ * its last fanned-out batch — one take per clip, in clip order — when its last run was one; else
542
+ * exactly the take it shows (its active result, else its video). Never the earlier takes it keeps:
543
+ * a video of one clip (one ticket, so no fan-out) would join every take. A single run clears the
544
+ * batch (the editor's job patch), so a batch held is always the last run's. Undefined when it holds
545
+ * no take at all.
546
+ */
547
+ export function ugcClipSavedList(data: unknown): string[] | undefined {
548
+ if (!isObject(data)) return undefined
549
+ const batch = Array.isArray(data.__listResults) ? data.__listResults.filter((u): u is string => typeof u === "string" && u !== "") : []
550
+ if (batch.length > 0) return batch
551
+ const results = Array.isArray(data.generatedResults) ? data.generatedResults : []
552
+ const index = typeof data.activeResultIndex === "number" && Number.isInteger(data.activeResultIndex) ? data.activeResultIndex : 0
553
+ const active = results[index]
554
+ const url = (isObject(active) ? filled(active.url) : undefined) ?? filled(data.generatedVideoUrl)
555
+ return url ? [url] : undefined
556
+ }
557
+
558
+ // ── UGC Cards ────────────────────────────────────────────────────────────────
559
+
560
+ /**
561
+ * UGC Cards' two timing jobs on the joined video, and the plan they time. The plan input must
562
+ * be UGC Clips' `{ v: 1, plan, transcribeArgs }`; anything else is refused before either job.
563
+ * The transcription spreads `transcribeArgs` unread, then sets the node's own fields last, so
564
+ * the wire can add a language but never change the provider or the word timings.
565
+ */
566
+ export function ugcCardsJobs(input: { planOutWire: unknown; videoUrl?: string; transcript?: string }): {
567
+ alignment: { path: "/v1/forced-alignment"; body: Record<string, unknown> }
568
+ transcribe: { path: "/v1/transcribe"; body: Record<string, unknown> }
569
+ plan: Record<string, unknown>
570
+ } | { error: string } {
571
+ const read = readUgcWire(input.planOutWire, NEEDS_PLAN_OUT)
572
+ if ("error" in read) return read
573
+ const { plan, transcribeArgs } = read.value
574
+ if (!isObject(plan) || !isObject(transcribeArgs)) return { error: NEEDS_PLAN_OUT }
575
+ const videoUrl = filled(input.videoUrl)
576
+ if (!videoUrl) return { error: NEEDS_VIDEO }
577
+ // An empty transcript is what UGC Clips said, not a missing input: it goes on as it came.
578
+ const transcript = input.transcript
579
+ if (typeof transcript !== "string") return { error: NEEDS_TRANSCRIPT }
580
+ return {
581
+ alignment: { path: "/v1/forced-alignment", body: { audioUrl: videoUrl, transcript } },
582
+ transcribe: { path: "/v1/transcribe", body: { ...transcribeArgs, audioUrl: videoUrl, provider: DEFAULT_TRANSCRIBE_NODE_PROVIDER, wordTimestamps: true } },
583
+ plan,
584
+ }
585
+ }
586
+
587
+ /**
588
+ * The `/v1/ugc/cards` canvas body: the plan, the video, whichever timing came back as a list,
589
+ * the timing jobs that failed, and the clips' notes.
590
+ */
591
+ export function ugcCardsBody(input: {
592
+ plan: Record<string, unknown>
593
+ videoUrl: string
594
+ alignment?: unknown
595
+ words?: unknown
596
+ failed: ReadonlyArray<"alignment" | "words">
597
+ clipNotes: ReadonlyArray<ClipNote>
598
+ }): Record<string, unknown> {
599
+ return {
600
+ surface: "canvas",
601
+ plan: input.plan,
602
+ videoUrl: input.videoUrl,
603
+ ...(Array.isArray(input.alignment) ? { alignment: input.alignment } : {}),
604
+ ...(Array.isArray(input.words) ? { words: input.words } : {}),
605
+ failed: [...input.failed],
606
+ clipNotes: [...input.clipNotes],
607
+ }
608
+ }
609
+
610
+ /** The caption plan when nothing could be timed: Add Captions renders no captions from it. */
611
+ const EMPTY_CAPTION_PLAN: CaptionPlan = { v: 1, hookText: "", hookEndMs: 0, bodyEndMs: 0, captions: [] }
612
+
613
+ /** The `/v1/ugc/cards` answer → `layerPlan`, `captionPlan` (v1; the empty plan when untimed) and `report` (one line per sentence). */
614
+ export function ugcCardsOutputs(answer: Record<string, unknown>): UgcOutputs {
615
+ const timing = answer.captionTiming
616
+ const report = answer.report
617
+ const lines = isObject(report) && Array.isArray(report.lines) ? report.lines.filter((l): l is string => typeof l === "string") : []
618
+ return {
619
+ layerPlan: JSON.stringify(Array.isArray(answer.layerPlan) ? answer.layerPlan : []),
620
+ captionPlan: JSON.stringify(isObject(timing) ? { v: 1, ...timing } : EMPTY_CAPTION_PLAN),
621
+ report: lines.join("\n"),
622
+ }
623
+ }