@nodaro/shared 3.62.0 → 3.63.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 (212) hide show
  1. package/dist/{chunk-6CSXMWL4.cjs → chunk-2PU3AGGS.cjs} +27 -4
  2. package/dist/chunk-2PU3AGGS.cjs.map +1 -0
  3. package/dist/{chunk-CC4V2B7S.js → chunk-34QLPTSA.js} +3 -3
  4. package/dist/{chunk-CC4V2B7S.js.map → chunk-34QLPTSA.js.map} +1 -1
  5. package/dist/{chunk-G4U3HW6W.js → chunk-3K24DWOH.js} +3 -3
  6. package/dist/{chunk-G4U3HW6W.js.map → chunk-3K24DWOH.js.map} +1 -1
  7. package/dist/{chunk-GSFB537T.js → chunk-4DVWXEB6.js} +23 -4
  8. package/dist/chunk-4DVWXEB6.js.map +1 -0
  9. package/dist/{chunk-ZES6EZC4.js → chunk-4MMZD63H.js} +3 -3
  10. package/dist/{chunk-ZES6EZC4.js.map → chunk-4MMZD63H.js.map} +1 -1
  11. package/dist/{chunk-N7OUQK7E.cjs → chunk-63H4C56Q.cjs} +8 -8
  12. package/dist/{chunk-N7OUQK7E.cjs.map → chunk-63H4C56Q.cjs.map} +1 -1
  13. package/dist/{chunk-2D5LQFV4.cjs → chunk-6BZC2ZHC.cjs} +9 -9
  14. package/dist/{chunk-2D5LQFV4.cjs.map → chunk-6BZC2ZHC.cjs.map} +1 -1
  15. package/dist/{chunk-3OYO3XCC.js → chunk-6M563QE6.js} +71 -9
  16. package/dist/chunk-6M563QE6.js.map +1 -0
  17. package/dist/{chunk-IDTKF5EX.cjs → chunk-6TGB7ECA.cjs} +7 -7
  18. package/dist/{chunk-IDTKF5EX.cjs.map → chunk-6TGB7ECA.cjs.map} +1 -1
  19. package/dist/{chunk-2HZGDZZN.cjs → chunk-6XUG4L7X.cjs} +6 -6
  20. package/dist/{chunk-2HZGDZZN.cjs.map → chunk-6XUG4L7X.cjs.map} +1 -1
  21. package/dist/{chunk-CIPPPT7E.cjs → chunk-77WU3V3J.cjs} +6 -6
  22. package/dist/{chunk-CIPPPT7E.cjs.map → chunk-77WU3V3J.cjs.map} +1 -1
  23. package/dist/{chunk-C7POAYFE.js → chunk-AE3AAJ4O.js} +3 -3
  24. package/dist/{chunk-C7POAYFE.js.map → chunk-AE3AAJ4O.js.map} +1 -1
  25. package/dist/{chunk-NGKKNSK6.js → chunk-BMJVKYVB.js} +36 -15
  26. package/dist/chunk-BMJVKYVB.js.map +1 -0
  27. package/dist/{chunk-YCXRSWCQ.js → chunk-CZ5IQB3L.js} +3 -3
  28. package/dist/{chunk-YCXRSWCQ.js.map → chunk-CZ5IQB3L.js.map} +1 -1
  29. package/dist/{chunk-E2HZTGYX.js → chunk-EPXGG27L.js} +7 -7
  30. package/dist/chunk-EPXGG27L.js.map +1 -0
  31. package/dist/{chunk-3M4BNKFJ.cjs → chunk-F6WGGYQW.cjs} +167 -3
  32. package/dist/chunk-F6WGGYQW.cjs.map +1 -0
  33. package/dist/{chunk-7FCTCWHD.js → chunk-FXGNRYQQ.js} +3 -3
  34. package/dist/{chunk-7FCTCWHD.js.map → chunk-FXGNRYQQ.js.map} +1 -1
  35. package/dist/{chunk-QWYFHQYK.cjs → chunk-GMBDLNLD.cjs} +86 -62
  36. package/dist/chunk-GMBDLNLD.cjs.map +1 -0
  37. package/dist/{chunk-KJSRPHJ2.cjs → chunk-GSKLPI3J.cjs} +100 -46
  38. package/dist/chunk-GSKLPI3J.cjs.map +1 -0
  39. package/dist/{chunk-S5TMRJMX.js → chunk-HBXF6RUU.js} +4 -4
  40. package/dist/{chunk-S5TMRJMX.js.map → chunk-HBXF6RUU.js.map} +1 -1
  41. package/dist/{chunk-S24ZBUB4.js → chunk-HWQ2SYNA.js} +6 -32
  42. package/dist/chunk-HWQ2SYNA.js.map +1 -0
  43. package/dist/{chunk-JJNNM23P.js → chunk-IY3Y462W.js} +3 -3
  44. package/dist/{chunk-JJNNM23P.js.map → chunk-IY3Y462W.js.map} +1 -1
  45. package/dist/{chunk-JZGZ26YB.js → chunk-KCZHQH2O.js} +4 -4
  46. package/dist/{chunk-JZGZ26YB.js.map → chunk-KCZHQH2O.js.map} +1 -1
  47. package/dist/{chunk-FVII3KHN.js → chunk-KMGCHV6O.js} +163 -4
  48. package/dist/chunk-KMGCHV6O.js.map +1 -0
  49. package/dist/{chunk-4ZEFP2FQ.cjs → chunk-L2TVY6XN.cjs} +4 -4
  50. package/dist/{chunk-4ZEFP2FQ.cjs.map → chunk-L2TVY6XN.cjs.map} +1 -1
  51. package/dist/{chunk-TRVWMKNE.cjs → chunk-LH72PQO2.cjs} +204 -52
  52. package/dist/chunk-LH72PQO2.cjs.map +1 -0
  53. package/dist/{chunk-HRY7KGAE.cjs → chunk-LMAQUR55.cjs} +6 -6
  54. package/dist/{chunk-HRY7KGAE.cjs.map → chunk-LMAQUR55.cjs.map} +1 -1
  55. package/dist/{chunk-MYJQELFN.cjs → chunk-M5OCFGHF.cjs} +254 -7
  56. package/dist/chunk-M5OCFGHF.cjs.map +1 -0
  57. package/dist/{chunk-I2RQB7VG.js → chunk-MD4XHED4.js} +3 -3
  58. package/dist/{chunk-I2RQB7VG.js.map → chunk-MD4XHED4.js.map} +1 -1
  59. package/dist/{chunk-6G7NN4S4.js → chunk-NIAFR5EE.js} +2 -2
  60. package/dist/chunk-NIAFR5EE.js.map +1 -0
  61. package/dist/{chunk-CF4S4N5X.js → chunk-O2QOBA6Q.js} +2 -2
  62. package/dist/{chunk-CF4S4N5X.js.map → chunk-O2QOBA6Q.js.map} +1 -1
  63. package/dist/{chunk-4GGLKRYI.cjs → chunk-O6TBB4IF.cjs} +2 -2
  64. package/dist/{chunk-4GGLKRYI.cjs.map → chunk-O6TBB4IF.cjs.map} +1 -1
  65. package/dist/{chunk-UDDVDQMF.js → chunk-OV3JTKBY.js} +166 -25
  66. package/dist/chunk-OV3JTKBY.js.map +1 -0
  67. package/dist/{chunk-5YYN5X57.js → chunk-PSKZKLDG.js} +252 -8
  68. package/dist/chunk-PSKZKLDG.js.map +1 -0
  69. package/dist/{chunk-IWWVPR3W.cjs → chunk-TM5JYSJF.cjs} +95 -19
  70. package/dist/chunk-TM5JYSJF.cjs.map +1 -0
  71. package/dist/{chunk-G3KVK7OU.cjs → chunk-V5EEQR2U.cjs} +21 -21
  72. package/dist/{chunk-G3KVK7OU.cjs.map → chunk-V5EEQR2U.cjs.map} +1 -1
  73. package/dist/{chunk-AOJ6B7K4.cjs → chunk-WZVIBAKN.cjs} +12 -12
  74. package/dist/chunk-WZVIBAKN.cjs.map +1 -0
  75. package/dist/{chunk-5M43XMRB.cjs → chunk-X5BAFW3Q.cjs} +8 -8
  76. package/dist/{chunk-5M43XMRB.cjs.map → chunk-X5BAFW3Q.cjs.map} +1 -1
  77. package/dist/{chunk-SYWR5G3T.js → chunk-XBTYGQ6Z.js} +51 -7
  78. package/dist/chunk-XBTYGQ6Z.js.map +1 -0
  79. package/dist/{chunk-AFYTX4AI.cjs → chunk-XGGZWA4A.cjs} +107 -50
  80. package/dist/chunk-XGGZWA4A.cjs.map +1 -0
  81. package/dist/{chunk-VACPZPUA.cjs → chunk-XGVJGNZW.cjs} +5 -5
  82. package/dist/{chunk-VACPZPUA.cjs.map → chunk-XGVJGNZW.cjs.map} +1 -1
  83. package/dist/{chunk-2W745U4A.cjs → chunk-Y35JQPT6.cjs} +42 -70
  84. package/dist/chunk-Y35JQPT6.cjs.map +1 -0
  85. package/dist/{chunk-KYMHFVAZ.cjs → chunk-Y4GCJJPF.cjs} +2 -2
  86. package/dist/chunk-Y4GCJJPF.cjs.map +1 -0
  87. package/dist/{chunk-PTD6EDUU.js → chunk-YUER7TJG.js} +3 -3
  88. package/dist/{chunk-PTD6EDUU.js.map → chunk-YUER7TJG.js.map} +1 -1
  89. package/dist/{chunk-Y6X7UJSD.js → chunk-YX6TFX7H.js} +66 -14
  90. package/dist/chunk-YX6TFX7H.js.map +1 -0
  91. package/dist/{chunk-TWF2OSH4.cjs → chunk-ZPE2ZTJ4.cjs} +4 -4
  92. package/dist/{chunk-TWF2OSH4.cjs.map → chunk-ZPE2ZTJ4.cjs.map} +1 -1
  93. package/dist/entries/apps.cjs +42 -42
  94. package/dist/entries/apps.js +7 -7
  95. package/dist/entries/credits.cjs +237 -169
  96. package/dist/entries/credits.d.cts +163 -16
  97. package/dist/entries/credits.d.ts +163 -16
  98. package/dist/entries/credits.js +10 -10
  99. package/dist/entries/llm-models.cjs +77 -57
  100. package/dist/entries/llm-models.d.cts +85 -6
  101. package/dist/entries/llm-models.d.ts +85 -6
  102. package/dist/entries/llm-models.js +2 -2
  103. package/dist/entries/media.cjs +63 -63
  104. package/dist/entries/media.d.cts +8 -0
  105. package/dist/entries/media.d.ts +8 -0
  106. package/dist/entries/media.js +1 -1
  107. package/dist/entries/model-catalog.cjs +121 -105
  108. package/dist/entries/model-catalog.d.cts +48 -18
  109. package/dist/entries/model-catalog.d.ts +48 -18
  110. package/dist/entries/model-catalog.js +4 -4
  111. package/dist/entries/models.cjs +418 -322
  112. package/dist/entries/models.d.cts +71 -5
  113. package/dist/entries/models.d.ts +71 -5
  114. package/dist/entries/models.js +5 -5
  115. package/dist/entries/nodes.cjs +216 -208
  116. package/dist/entries/nodes.d.cts +22 -6
  117. package/dist/entries/nodes.d.ts +22 -6
  118. package/dist/entries/nodes.js +8 -8
  119. package/dist/entries/pipeline.cjs +152 -152
  120. package/dist/entries/pipeline.d.cts +3 -3
  121. package/dist/entries/pipeline.d.ts +3 -3
  122. package/dist/entries/pipeline.js +3 -3
  123. package/dist/entries/runtime-config.cjs +29 -29
  124. package/dist/entries/runtime-config.d.cts +10 -7
  125. package/dist/entries/runtime-config.d.ts +10 -7
  126. package/dist/entries/runtime-config.js +1 -1
  127. package/dist/entries/social.cjs +177 -177
  128. package/dist/entries/social.js +2 -2
  129. package/dist/entries/types.d.cts +8 -0
  130. package/dist/entries/types.d.ts +8 -0
  131. package/dist/entries/ugc.cjs +71 -71
  132. package/dist/entries/ugc.js +4 -4
  133. package/dist/entries/video.cjs +154 -150
  134. package/dist/entries/video.d.cts +11 -2
  135. package/dist/entries/video.d.ts +11 -2
  136. package/dist/entries/video.js +6 -6
  137. package/dist/entries/workflow.d.cts +1 -1
  138. package/dist/entries/workflow.d.ts +1 -1
  139. package/dist/index.cjs +1727 -1515
  140. package/dist/index.d.cts +8 -8
  141. package/dist/index.d.ts +8 -8
  142. package/dist/index.js +23 -23
  143. package/dist/{model-catalog-CCEcv08q.d.cts → model-catalog-C_Eo35tL.d.cts} +30 -0
  144. package/dist/{model-catalog-CCEcv08q.d.ts → model-catalog-C_Eo35tL.d.ts} +30 -0
  145. package/dist/{model-constants-Cf3zaITt.d.cts → model-constants-Bg4ccSQb.d.ts} +138 -25
  146. package/dist/{model-constants-B88p6XR0.d.ts → model-constants-DWcxOmaY.d.cts} +138 -25
  147. package/package.json +1 -1
  148. package/src/__tests__/credit-identifiers.test.ts +29 -0
  149. package/src/__tests__/extend-providers.test.ts +106 -26
  150. package/src/__tests__/gvp-supported-providers.test.ts +27 -2
  151. package/src/__tests__/lip-sync-audio-rate.test.ts +74 -0
  152. package/src/__tests__/lip-sync-levers.test.ts +31 -0
  153. package/src/__tests__/llm-models.test.ts +132 -3
  154. package/src/__tests__/llm-price-key.test.ts +152 -1
  155. package/src/__tests__/nemotron-transcribe-pricing.test.ts +61 -0
  156. package/src/__tests__/normalize-node-params.test.ts +25 -0
  157. package/src/__tests__/pixverse-v6-max-catalog.test.ts +271 -0
  158. package/src/__tests__/prompt-length-limits.test.ts +4 -0
  159. package/src/__tests__/seedance-task-type.test.ts +13 -3
  160. package/src/__tests__/transcribe-capabilities.test.ts +39 -2
  161. package/src/__tests__/transcribe-preflight.test.ts +50 -1
  162. package/src/__tests__/video-audio-capability.test.ts +35 -6
  163. package/src/__tests__/video-resolution-billed-as-named.test.ts +30 -0
  164. package/src/__tests__/video-upscale-params.test.ts +62 -0
  165. package/src/catalog-projection.ts +8 -0
  166. package/src/credit-estimators/index.ts +10 -0
  167. package/src/credit-estimators/nemotron-transcribe.ts +87 -0
  168. package/src/credit-identifiers.ts +109 -35
  169. package/src/entries/credits.ts +12 -1
  170. package/src/entries/llm-models.ts +6 -0
  171. package/src/entries/model-catalog.ts +9 -0
  172. package/src/entries/models.ts +35 -0
  173. package/src/entries/nodes.ts +2 -0
  174. package/src/entries/video.ts +1 -1
  175. package/src/freecut-protocol.ts +8 -0
  176. package/src/lip-sync-levers.ts +56 -0
  177. package/src/lip-sync-pricing.ts +91 -1
  178. package/src/llm-models.ts +249 -4
  179. package/src/model-catalog.ts +250 -4
  180. package/src/model-constants.ts +277 -30
  181. package/src/model-tree.ts +2 -1
  182. package/src/nodaro-video-upscale.ts +48 -0
  183. package/src/node-default-mappings.ts +3 -0
  184. package/src/normalize-node-params.ts +49 -1
  185. package/src/runtime-config/contract.ts +10 -7
  186. package/src/seedance-draft.ts +2 -1
  187. package/src/transcribe-preflight.ts +58 -7
  188. package/src/video-duration.ts +9 -0
  189. package/src/video-ui-defaults.ts +5 -3
  190. package/src/video-upscale-params.ts +67 -0
  191. package/dist/chunk-2W745U4A.cjs.map +0 -1
  192. package/dist/chunk-3M4BNKFJ.cjs.map +0 -1
  193. package/dist/chunk-3OYO3XCC.js.map +0 -1
  194. package/dist/chunk-5YYN5X57.js.map +0 -1
  195. package/dist/chunk-6CSXMWL4.cjs.map +0 -1
  196. package/dist/chunk-6G7NN4S4.js.map +0 -1
  197. package/dist/chunk-AFYTX4AI.cjs.map +0 -1
  198. package/dist/chunk-AOJ6B7K4.cjs.map +0 -1
  199. package/dist/chunk-E2HZTGYX.js.map +0 -1
  200. package/dist/chunk-FVII3KHN.js.map +0 -1
  201. package/dist/chunk-GSFB537T.js.map +0 -1
  202. package/dist/chunk-IWWVPR3W.cjs.map +0 -1
  203. package/dist/chunk-KJSRPHJ2.cjs.map +0 -1
  204. package/dist/chunk-KYMHFVAZ.cjs.map +0 -1
  205. package/dist/chunk-MYJQELFN.cjs.map +0 -1
  206. package/dist/chunk-NGKKNSK6.js.map +0 -1
  207. package/dist/chunk-QWYFHQYK.cjs.map +0 -1
  208. package/dist/chunk-S24ZBUB4.js.map +0 -1
  209. package/dist/chunk-SYWR5G3T.js.map +0 -1
  210. package/dist/chunk-TRVWMKNE.cjs.map +0 -1
  211. package/dist/chunk-UDDVDQMF.js.map +0 -1
  212. package/dist/chunk-Y6X7UJSD.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/video-character-refs.ts","../src/video-overlay-geometry.ts","../src/video-overlay-layout-ids.ts","../src/video-overlay-validate.ts","../src/video-overlay-layouts.ts","../src/video-analysis.ts","../src/video-output-canvas.ts","../src/video-frame-fit.ts"],"names":["VIDEO_REF_LIMITS_BY_PROVIDER","used","isVideoOverlayOutputAspect","ASPECT_RATIO_DIMENSIONS","VIDEO_OVERLAY_MAX_TIME_SEC","VIDEO_OVERLAY_BOUNDS","OVERLAY_ANCHORS","isFit","VIDEO_OVERLAY_FITS","VIDEO_OVERLAY_VOLUME_BOUNDS","asLayer","VIDEO_OVERLAY_BOX_FIELDS","VIDEO_OVERLAY_MAX_LAYERS","isVideoOverlayVideoLayer","VIDEO_OVERLAY_MAX_VIDEO_LAYERS","isVideoOverlayPresetId","nonEmpty","storedLayout","evenFloor","even","videoOverlayRenderOrder","isVideoOverlayCorner","expandVideoOverlayLayer","z","getModel"],"mappings":";;;;;;;;;AAqDO,IAAM,gCAAgC,IAAA,CAAK,GAAA;AAAA,EAChD,CAAA;AAAA,EACA,GAAG,MAAA,CAAO,MAAA,CAAOA,8CAA4B,CAAA,CAAE,IAAI,CAAC,CAAA,KAAM,CAAA,EAAG,UAAA,IAAc,CAAC;AAC9E;AAGO,IAAM,gCAAA,GAAmC;AAGzC,IAAM,+BAAA,GAAkC;AACxC,IAAM,wBAAA,GAA2B;AAIjC,IAAM,qCAAA,GAAwC;AAC9C,IAAM,iCAAA,GAAoC;AAG1C,SAAS,qBAAqB,QAAA,EAAsC;AACzE,EAAA,OAAO,QAAA,GAAYA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AY,mBAAmB,WAAA,EAAa,YAAA,EAAc,YAAY,CAAA,GAAI,MAAA;AAE7F,EAAA,MAAM,MAAA,GAAS,MAAA,GACX,EAAE,KAAA,EAAO,MAAA,CAAO,CAAC,CAAA,EAAG,MAAA,EAAQ,MAAA,CAAO,CAAC,CAAA,EAAE,GACtC,sBAAA;AAAA,IACE,IAAA,GAAO,KAAK,KAAA,GAAQ,WAAA;AAAA,IACpB,IAAA,GAAO,KAAK,MAAA,GAAS,YAAA;AAAA,IACrB;AAAA,GACF;AAEJ,EAAA,MAAM,YAAY,MAAA,CAAO,KAAA,KAAU,eAAe,MAAA,CAAO,MAAA,KAAW,gBAAgB,CAAC,IAAA;AACrF,EAAA,IAAI,WAAW,OAAO,IAAA;AAEtB,EAAA,OAAO;AAAA,IACL,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS,EAAC;AAAA,IACvB,MAAA,EAAQ,SAAS,YAAA,GAAe;AAAA,GAClC;AACF;AAQO,SAAS,qBAAqB,IAAA,EAIF;AACjC,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,sBAAA;AACpC,EAAA,MAAM,MAAA,GAAS,SAAA,KAAc,MAAA,GACxB,IAAA,CAAK,QAAA,GAAW,2BAA2B,IAAA,CAAK,QAAQ,CAAA,IAAK,OAAA,GAAU,OAAA,GACxE,SAAA;AACJ,EAAA,IAAI,MAAA,KAAW,WAAA,IAAe,CAAC,IAAA,CAAK,yBAAyB,OAAO,OAAA;AACpE,EAAA,OAAO,MAAA;AACT","file":"chunk-Y35JQPT6.cjs","sourcesContent":["import { VIDEO_REF_LIMITS_BY_PROVIDER } from \"./model-constants.js\"\nimport type { ConnectedReference } from \"./types.js\"\nimport type { GeminiOmniVoicePresetId } from \"./gemini-omni-voices.js\"\n\n/**\n * Character references — the dedicated IDENTITY input of a video model, as\n * opposed to a loose reference image.\n *\n * Gemini Omni treats `image_urls` as \"reference images for characters, scenes,\n * styles, or storyboard guidance\": a portrait sent there steers the clip but\n * the face drifts. Its separate `character_ids` input is the one that keeps a\n * real person's face, and it takes ids minted from a portrait by a create\n * call. The PUBLIC shape below is provider-neutral — a portrait and a\n * description — and the provider layer mints (and caches) whatever ids its\n * upstream needs. Nothing upstream-shaped ever appears in the API.\n *\n * WHICH models take them is data, never a name list: a positive `characters`\n * cap on `VIDEO_REF_LIMITS_BY_PROVIDER`.\n */\nexport interface VideoCharacterVoice {\n /** The base voice — one of `GEMINI_OMNI_VOICE_PRESETS`. */\n preset: GeminiOmniVoicePresetId\n /** Free-text timbre / pace / emotion for the persona. Optional. */\n description?: string\n /** One example line the persona says (≤ 120 chars). Optional. */\n exampleLine?: string\n}\n\nexport interface VideoCharacterReference {\n /** Portrait of the person (public URL). Index 0 of the upstream image set. */\n imageUrl: string\n /** Optional full-body image; costs a second input unit. */\n bodyImageUrl?: string\n /**\n * More views of the same person, after the portrait and body image. Read by\n * models whose subject takes several images (Kling 4.0: 2-4 per subject, the\n * portrait first); ignored elsewhere. At most\n * {@link VIDEO_CHARACTER_EXTRA_IMAGES_MAX}.\n */\n extraImageUrls?: string[]\n /** Who this is: appearance, identity, style, clothing. Required by the upstream. */\n description: string\n /** Optional display name. */\n name?: string\n /**\n * Pin a voice persona to this character so it keeps ONE voice across clips\n * (the model otherwise improvises a voice per generation). Only models with a\n * positive `voices` cap take it.\n */\n voice?: VideoCharacterVoice\n}\n\n/** Zod `.max()` ceiling for the wire field — the widest cap any provider declares. */\nexport const VIDEO_CHARACTER_REFS_WIRE_MAX = Math.max(\n 0,\n ...Object.values(VIDEO_REF_LIMITS_BY_PROVIDER).map((l) => l?.characters ?? 0),\n)\n\n/** Most `extraImageUrls` a character reference may carry (Kling 4.0's subject takes 4 images: the portrait + 3). */\nexport const VIDEO_CHARACTER_EXTRA_IMAGES_MAX = 3\n\n/** Longest `description` / `name` a client may send (route Zod reads these). */\nexport const VIDEO_CHARACTER_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_NAME_MAX = 100\n/** Longest voice `description` / `exampleLine` a client may send. The upstream\n * allows far more description (20000); we cap the PUBLIC field at the same\n * ceiling as a character description so policy text and prompts stay bounded. */\nexport const VIDEO_CHARACTER_VOICE_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_VOICE_EXAMPLE_MAX = 120\n\n/** How many character references the provider takes; 0 = none (or unknown). */\nexport function videoCharacterRefCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.characters ?? 0) : 0\n}\n\n/** How many DISTINCT voice personas the provider takes per request; 0 = none. */\nexport function videoCharacterVoiceCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.voices ?? 0) : 0\n}\n\n/**\n * Identity of a voice persona — what makes two voices \"the same voice\". The\n * persona is minted per (preset, description, example line) AND the character's\n * name (the label it is created under), so the name is part of the identity:\n * this count must equal the number of personas the provider will actually mint,\n * or the cap would be checked against a different number than what ships.\n */\nexport function videoCharacterVoiceKey(ref: Pick<VideoCharacterReference, \"voice\" | \"name\">): string | null {\n const voice = ref.voice\n if (!voice) return null\n return JSON.stringify([voice.preset, voice.description?.trim() ?? \"\", voice.exampleLine?.trim() ?? \"\", ref.name?.trim() ?? \"\"])\n}\n\n/** How many distinct voice personas a set of references asks for. */\nexport function videoCharacterDistinctVoices(\n characterReferences: readonly Pick<VideoCharacterReference, \"voice\" | \"name\">[] | undefined,\n): number {\n const keys = new Set<string>()\n for (const c of characterReferences ?? []) {\n const key = videoCharacterVoiceKey(c)\n if (key) keys.add(key)\n }\n return keys.size\n}\n\n/** Every provider that declares a character-reference cap, in declaration order. */\nexport function videoCharacterRefProviders(): string[] {\n return Object.entries(VIDEO_REF_LIMITS_BY_PROVIDER)\n .filter(([, l]) => (l?.characters ?? 0) > 0)\n .map(([id]) => id)\n}\n\n/**\n * Input units a set of character references draws from the provider's shared\n * input budget: 1 per character, 2 when a body image is supplied (the upstream\n * counts a dual-image character as two slots).\n */\nexport function videoCharacterRefUnits(\n characterReferences: readonly Pick<VideoCharacterReference, \"bodyImageUrl\">[] | undefined,\n): number {\n let units = 0\n for (const c of characterReferences ?? []) units += c.bodyImageUrl ? 2 : 1\n return units\n}\n\nexport interface VideoCharacterRefProblem {\n code:\n | \"character_references_unsupported\"\n | \"character_references_over_limit\"\n | \"character_references_with_start_frame\"\n | \"character_references_with_end_frame\"\n | \"character_references_quota\"\n | \"character_voice_unsupported\"\n | \"character_voices_over_limit\"\n message: string\n}\n\n/**\n * Voice-persona rule: the provider must take voices at all, and the DISTINCT\n * voices must fit its cap (Gemini Omni: 3 `audio_ids` per task). Two characters\n * with an identical voice AND name count once. `cap` overrides the provider's declared cap\n * (tests; a future model with a different limit declares it as data instead).\n */\nexport function videoCharacterVoiceProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n cap?: number\n}): VideoCharacterRefProblem | null {\n const distinct = videoCharacterDistinctVoices(args.characterReferences)\n if (distinct === 0) return null\n const cap = args.cap ?? videoCharacterVoiceCap(args.provider)\n if (cap === 0) {\n return {\n code: \"character_voice_unsupported\",\n message:\n `A character voice is not supported by ${args.provider ?? \"the selected model\"}. ` +\n \"Drop the voice, or pick a model that takes characterReferences.\",\n }\n }\n if (distinct > cap) {\n return {\n code: \"character_voices_over_limit\",\n message: `${args.provider} accepts at most ${cap} distinct character voices per video; got ${distinct}. Give some characters the same voice, or drop some.`,\n }\n }\n return null\n}\n\n/**\n * The one validation both video routes (and the provider backstop) run. Returns\n * the first problem as a friendly 400 body, or null when the request is fine.\n *\n * The shared budget: for a model that declares `characters`, its `images` cap\n * IS the total input budget (images + 2×videos + character units ≤ images cap —\n * 7 for Gemini Omni). Callers pass the ASSEMBLED image count, after any\n * `connectedReferences` expansion, so the budget is measured on what ships.\n */\nexport function videoCharacterRefProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n /** Reference images that will ship (assembled, flat). */\n imageCount: number\n /** Source / reference videos that will ship. */\n videoCount: number\n /** True when the request carries a start frame (`imageUrl`). */\n hasStartFrame: boolean\n /** True when the request carries an end frame (`endFrameUrl`). */\n hasEndFrame?: boolean\n /** Reference audio clips that will ship (counted by a `materials` budget). */\n audioCount?: number\n}): VideoCharacterRefProblem | null {\n const { provider, characterReferences } = args\n if (!characterReferences || characterReferences.length === 0) return null\n\n const cap = videoCharacterRefCap(provider)\n if (cap === 0) {\n return {\n code: \"character_references_unsupported\",\n message:\n `characterReferences is not supported by ${provider ?? \"the selected model\"}. ` +\n `Models that take them: ${videoCharacterRefProviders().join(\", \")}. ` +\n \"Otherwise send the portrait as a reference image instead.\",\n }\n }\n if (characterReferences.length > cap) {\n return {\n code: \"character_references_over_limit\",\n message: `${provider} accepts at most ${cap} character references; got ${characterReferences.length}.`,\n }\n }\n // A provider that counts every material against ONE budget (Kling 4.0: 15\n // images + videos + subjects + voices) takes characters beside a start frame\n // (the frame joins the reference images) — the Gemini Omni unit rules below\n // do not apply to it. Where audio rides on the characters as their voices\n // (`audioBindsToCharacters`, Kling 4.0 Flash), a clip takes no seat.\n const limits = VIDEO_REF_LIMITS_BY_PROVIDER[provider as string]\n const materials = limits?.materials\n if (materials !== undefined) {\n const audioSeats = limits?.audioBindsToCharacters ? 0 : (args.audioCount ?? 0)\n const used =\n args.imageCount + (args.hasStartFrame ? 1 : 0) + args.videoCount + characterReferences.length + audioSeats\n if (used > materials) {\n return {\n code: \"character_references_quota\",\n message:\n `${provider} takes at most ${materials} materials in all — reference images (a start frame counts as one), ` +\n `reference videos, characters${limits?.audioBindsToCharacters ? \"\" : \" and voices\"}. This request uses ${used}. Remove some.`,\n }\n }\n return videoCharacterVoiceProblem({ provider, characterReferences })\n }\n // A NODARO limit, not an upstream exclusivity: Gemini Omni's start frame is\n // sent as the first entry of `image_urls` (never as `first_frame_url`), so\n // the upstream would take it beside `character_ids`. We reject the pair\n // because the frame / identity roles are not yet bound in the prompt\n // (and the frame would need to be budgeted against the shared input quota).\n if (args.hasStartFrame) {\n return {\n code: \"character_references_with_start_frame\",\n message:\n `${provider} does not yet support combining characterReferences with a start frame (imageUrl) — ` +\n \"the frame and the characters would compete for the same input slots without a defined role. \" +\n \"Drop the start frame (the character's portrait carries the face), or drop characterReferences.\",\n }\n }\n // Gemini Omni has no end-frame input; without this the frame would be dropped\n // silently once characters make a frame-less request look \"referenced\".\n if (args.hasEndFrame) {\n return {\n code: \"character_references_with_end_frame\",\n message:\n `${provider} does not use an end frame (endFrameUrl) together with characterReferences. ` +\n \"Drop the end frame, or drop characterReferences.\",\n }\n }\n const budget = VIDEO_REF_LIMITS_BY_PROVIDER[provider as string]?.images ?? 7\n const used = args.imageCount + args.videoCount * 2 + videoCharacterRefUnits(characterReferences)\n if (used > budget) {\n return {\n code: \"character_references_quota\",\n message:\n `${provider} takes at most ${budget} input units: reference images count 1, each reference video 2, ` +\n `each character 1 (2 with a body image). This request uses ${used}. Remove some reference images or characters.`,\n }\n }\n return videoCharacterVoiceProblem({ provider, characterReferences })\n}\n\n/**\n * One provider-neutral character reference per wired Character node, for a\n * model that takes wired characters as NAMED SUBJECTS (catalog feature\n * `character-subjects`, Kling 4.0). Input: the wired-character entries both\n * engines already expand (`expandWiredCharacterRefs` server-side, the editor's\n * twin) — the canonical portrait and every variant, grouped here by character.\n * The portrait leads; up to {@link VIDEO_CHARACTER_EXTRA_IMAGES_MAX} more views\n * follow in expansion order. The name is the character's own; the description\n * its canonical description, else its description. A character with a single\n * image still yields a reference — the provider decides (Kling keeps it a\n * reference image).\n */\nexport function characterReferencesFromWired(refs: readonly ConnectedReference[]): VideoCharacterReference[] {\n const bySlug = new Map<string, { name: string; description?: string; urls: string[] }>()\n for (const r of refs) {\n if (r.source !== \"wired-character\" || !r.characterSlug || !r.url) continue\n let entry = bySlug.get(r.characterSlug)\n if (!entry) {\n entry = { name: r.defaultName.split(\" / \")[0]!.trim() || r.characterSlug, urls: [] }\n bySlug.set(r.characterSlug, entry)\n }\n const description = (r.characterCanonicalDescription ?? r.description)?.trim()\n if (!entry.description && description) entry.description = description\n if (entry.urls.includes(r.url)) continue\n // The canonical portrait leads whatever order the variants arrived in.\n if (!r.variantSlug) entry.urls.unshift(r.url)\n else entry.urls.push(r.url)\n }\n return [...bySlug.values()].map((c) => ({\n imageUrl: c.urls[0]!,\n ...(c.urls.length > 1 ? { extraImageUrls: c.urls.slice(1, 1 + VIDEO_CHARACTER_EXTRA_IMAGES_MAX) } : {}),\n description: (c.description ?? c.name).slice(0, VIDEO_CHARACTER_DESCRIPTION_MAX),\n name: c.name.slice(0, VIDEO_CHARACTER_NAME_MAX),\n }))\n}\n","/**\n * Video Overlay — placement: the output canvas and where a layer's box lands\n * on it. `resolveVideoOverlayGeometry` is the one placement function the\n * canvas preview and the ffmpeg worker both call. A sibling of\n * `video-overlay.ts`, which it imports from; nothing there imports this file.\n * Wire contract only — no I/O.\n */\nimport type { OverlayAnchor } from \"./image-overlay-layers.js\"\nimport { ASPECT_RATIO_DIMENSIONS } from \"./model-constants.js\"\nimport { isVideoOverlayOutputAspect, type VideoOverlayLayer } from \"./video-overlay.js\"\n\nexport interface VideoOverlayRect {\n readonly left: number\n readonly top: number\n readonly width: number\n readonly height: number\n}\nexport interface VideoOverlayCanvas {\n readonly w: number\n readonly h: number\n}\nexport interface VideoOverlayGeometry {\n readonly box: VideoOverlayRect\n readonly drawn: VideoOverlayRect\n}\n\nconst evenFloor = (n: number): number => Math.max(2, Math.floor(n / 2) * 2)\n\n/**\n * The output canvas: `ASPECT_RATIO_DIMENSIONS[outputAspect]` when a target\n * aspect is set; otherwise the base's DISPLAY size (rotation already applied by\n * the caller's probe) with the sample aspect ratio resolved and both sides\n * rounded down to even — `trunc(iw*sar/2)*2 × trunc(ih/2)*2`, what the ffmpeg\n * base chain produces. null when neither is known.\n */\nexport function videoOverlayCanvas(\n display: { readonly width: number; readonly height: number; readonly sar?: number } | null | undefined,\n outputAspect?: string | null,\n): VideoOverlayCanvas | null {\n if (isVideoOverlayOutputAspect(outputAspect)) {\n const d = ASPECT_RATIO_DIMENSIONS[outputAspect]!\n return { w: d.width, h: d.height }\n }\n if (!display || !(display.width > 0) || !(display.height > 0)) return null\n const sar = typeof display.sar === \"number\" && Number.isFinite(display.sar) && display.sar > 0 ? display.sar : 1\n return { w: evenFloor(display.width * sar), h: evenFloor(display.height) }\n}\n\nfunction anchorFactors(anchor: OverlayAnchor): readonly [number, number] {\n const h = anchor.endsWith(\"left\") ? 0 : anchor.endsWith(\"right\") ? 1 : 0.5\n const v = anchor.startsWith(\"top\") ? 0 : anchor.startsWith(\"bottom\") ? 1 : 0.5\n return [h, v]\n}\n\n/**\n * Spec §3.4. `width%` → px of the canvas width; height follows the image's\n * aspect unless `height%` is set; nine anchors; x/y are additive offsets in %\n * of the canvas. An aspect-following box taller than the canvas is fitted\n * inside it (both sides scaled, aspect kept) — so `drawn` never exceeds the\n * canvas, which is what bounds the sharp pre-fit at one canvas of RGBA. `fit`:\n * contain → the image scaled inside the box, centred; cover → the box itself.\n * The only post-processing is rounding `drawn` DOWN to even, floored at 2 × 2.\n * Differences from Image Overlay's copies (on purpose): no 8192 edge shrink,\n * the canvas clamp, the even rounding.\n */\nexport function resolveVideoOverlayGeometry(\n canvas: VideoOverlayCanvas,\n layer: Pick<VideoOverlayLayer, \"anchor\" | \"x\" | \"y\" | \"width\" | \"height\" | \"fit\">,\n imageAspect: number,\n): VideoOverlayGeometry {\n const aspect = Number.isFinite(imageAspect) && imageAspect > 0 ? imageAspect : 1\n let bw = Math.max(1, Math.round((layer.width / 100) * canvas.w))\n let bh = layer.height !== undefined ? Math.max(1, Math.round((layer.height / 100) * canvas.h)) : Math.max(1, Math.round(bw / aspect))\n if (layer.height === undefined && bh > canvas.h) {\n bw = Math.max(1, Math.round(bw * (canvas.h / bh)))\n bh = canvas.h\n }\n const [ax, ay] = anchorFactors(layer.anchor)\n const left = Math.round(ax * (canvas.w - bw) + (layer.x / 100) * canvas.w)\n const top = Math.round(ay * (canvas.h - bh) + (layer.y / 100) * canvas.h)\n let dw: number\n let dh: number\n if (layer.fit === \"cover\") {\n dw = bw\n dh = bh\n } else if (bw / bh > aspect) {\n dh = bh\n dw = bh * aspect\n } else {\n dw = bw\n dh = bw / aspect\n }\n const width = evenFloor(dw)\n const height = evenFloor(dh)\n return {\n box: { left, top, width: bw, height: bh },\n drawn: { left: left + Math.floor((bw - width) / 2), top: top + Math.floor((bh - height) / 2), width, height },\n }\n}\n","/**\n * Video Overlay layouts — the ids, and what each one needs. A layout is a\n * named shortcut that writes the boxes (`expandVideoOverlayLayout` in\n * `video-overlay-layouts.ts`); like a placement preset, it is a TAG and the\n * boxes are the truth, except for the two stacks, whose boxes depend on the\n * sources' shapes and are resolved where those are known.\n *\n * Dependency-free on purpose: the validator in `video-overlay-validate.ts`\n * reads these, and `video-overlay-layouts.ts` imports the contract in\n * `video-overlay.ts`, so they cannot live in either without a cycle. Wire contract only — no I/O.\n */\n\n/**\n * - `video-bottom` / `video-top`: the base whole, full width, against that edge.\n * - `stack-whole`: the base directly above the first video layer, both whole,\n * the same width, the pair centred.\n * - `stack-filled`: the base fills the top half, the first video layer the\n * bottom half, both cropped (`cover`).\n * - `pip`: the base fills the frame, the first video layer sits in a corner.\n */\nexport const VIDEO_OVERLAY_LAYOUT_IDS = [\"video-bottom\", \"video-top\", \"stack-whole\", \"stack-filled\", \"pip\"] as const\nexport type VideoOverlayLayoutId = (typeof VIDEO_OVERLAY_LAYOUT_IDS)[number]\n\nexport function isVideoOverlayLayoutId(v: unknown): v is VideoOverlayLayoutId {\n return typeof v === \"string\" && (VIDEO_OVERLAY_LAYOUT_IDS as readonly string[]).includes(v)\n}\n\n/** Layouts placed against the output canvas's edges or halves: every one but `pip`. */\nconst NEEDS_ASPECT: ReadonlySet<VideoOverlayLayoutId> = new Set([\"video-bottom\", \"video-top\", \"stack-whole\", \"stack-filled\"])\n/** Layouts that place the first video layer. */\nconst NEEDS_VIDEO_LAYER: ReadonlySet<VideoOverlayLayoutId> = new Set([\"stack-whole\", \"stack-filled\", \"pip\"])\n/** Layouts that place the base themselves, so take no `baseBox`. */\nconst PLACES_BASE: ReadonlySet<VideoOverlayLayoutId> = new Set([\"stack-whole\", \"stack-filled\"])\n\n/** True when the layout is refused without an `outputAspect` (`layout_needs_aspect`). */\nexport function videoOverlayLayoutNeedsAspect(id: VideoOverlayLayoutId): boolean {\n return NEEDS_ASPECT.has(id)\n}\n\n/** True when the layout is refused without a video layer (`layout_needs_video_layer`). */\nexport function videoOverlayLayoutNeedsVideoLayer(id: VideoOverlayLayoutId): boolean {\n return NEEDS_VIDEO_LAYER.has(id)\n}\n\n/** True when the layout places the base itself and is refused with a `baseBox` (`layout_conflicts_base_box`): the two stacks. */\nexport function videoOverlayLayoutPlacesBase(id: VideoOverlayLayoutId): boolean {\n return PLACES_BASE.has(id)\n}\n","/**\n * Video Overlay — the request validator: what a schema cannot express, run at\n * every engine entry. It returns a CODE, never English: `formatVideoOverlayError`\n * renders the route / worker text, the canvas renders the code through its\n * dictionaries. A sibling of `video-overlay.ts`, which it imports from; nothing\n * there imports this file.\n * Wire contract only — no prompt content, no I/O.\n */\nimport { OVERLAY_ANCHORS } from \"./image-overlay-layers.js\"\nimport {\n VIDEO_OVERLAY_BOUNDS, VIDEO_OVERLAY_BOX_FIELDS, VIDEO_OVERLAY_FITS, VIDEO_OVERLAY_MAX_LAYERS, VIDEO_OVERLAY_MAX_TIME_SEC,\n VIDEO_OVERLAY_MAX_VIDEO_LAYERS, VIDEO_OVERLAY_VOLUME_BOUNDS, isVideoOverlayOutputAspect, isVideoOverlayPresetId,\n type VideoOverlayBoxInput, type VideoOverlayErrorCode, type VideoOverlayLayerInput,\n} from \"./video-overlay.js\"\nimport { asLayer, isFit, nonEmpty, storedLayout } from \"./video-overlay-input.js\"\nimport { isVideoOverlayVideoLayer } from \"./video-overlay-video-layers.js\"\nimport {\n VIDEO_OVERLAY_LAYOUT_IDS, isVideoOverlayLayoutId, videoOverlayLayoutNeedsAspect, videoOverlayLayoutNeedsVideoLayer, videoOverlayLayoutPlacesBase,\n type VideoOverlayLayoutId,\n} from \"./video-overlay-layout-ids.js\"\n\nexport interface VideoOverlayIssue {\n readonly ok: false\n readonly code: VideoOverlayErrorCode\n /** 0-based index into the validated `layers[]`. */\n readonly layer?: number\n readonly slot?: number\n readonly planLayer?: number\n readonly params: Readonly<Record<string, string | number>>\n}\nexport type VideoOverlayValidation = { readonly ok: true } | VideoOverlayIssue\n\nexport interface VideoOverlayValidationInput {\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n readonly outputAspect?: string | null\n readonly baseFit?: string | null\n readonly backgroundColor?: string | null\n readonly baseBox?: VideoOverlayBoxInput | null\n readonly layout?: string | null\n /** From `assembleVideoOverlayRequest`: the wired layer plan was unreadable. */\n readonly planError?: \"invalid_layer_plan\"\n}\n\nconst inTimeRange = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isFinite(v) && v >= 0 && v <= VIDEO_OVERLAY_MAX_TIME_SEC\n\ntype BoundedField = keyof typeof VIDEO_OVERLAY_BOUNDS\nconst BOUNDED_FIELDS = Object.keys(VIDEO_OVERLAY_BOUNDS) as BoundedField[]\n\n/**\n * The first present (non-null) box / look field outside its domain, with the\n * domain as a symbolic `allowed` string; null when every present field is in\n * range. Only PRESENT fields are checked, so the verdict is the same before and\n * after the expansion (it fills in-range defaults only). This is what keeps a\n * JSON-written layer (MCP `update_workflow_json`, copilot, templates) from\n * reaching the geometry with an unbounded box — `drawn ≤ canvas` (§3.4) holds\n * only for boxes inside these bounds.\n */\nfunction outOfBounds(l: VideoOverlayLayerInput): { field: string; allowed: string } | null {\n for (const f of BOUNDED_FIELDS) {\n const v = l[f]\n if (v === undefined || v === null) continue\n const [min, max] = VIDEO_OVERLAY_BOUNDS[f]\n const integer = f === \"zIndex\"\n if (typeof v !== \"number\" || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isInteger(v))) {\n return { field: f, allowed: `${integer ? \"integers \" : \"\"}${min}..${max}` }\n }\n }\n if (l.anchor != null && !(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) {\n return { field: \"anchor\", allowed: OVERLAY_ANCHORS.join(\", \") }\n }\n if (l.fit != null && !isFit(l.fit)) return { field: \"fit\", allowed: VIDEO_OVERLAY_FITS.join(\", \") }\n if (l.animate != null && typeof l.animate !== \"boolean\") return { field: \"animate\", allowed: \"true, false\" }\n return null\n}\n\n/**\n * A present `sound` that is not `{ volume }` with the volume inside\n * `VIDEO_OVERLAY_VOLUME_BOUNDS`. Kept out of `outOfBounds`: a bad volume is\n * refused, but it does not stop the stage from drawing the layer.\n */\nfunction soundOutOfBounds(sound: unknown): { field: string; allowed: string } | null {\n if (sound === undefined || sound === null) return null\n const [min, max] = VIDEO_OVERLAY_VOLUME_BOUNDS\n const v = typeof sound === \"object\" && !Array.isArray(sound) ? (sound as { volume?: unknown }).volume : undefined\n return typeof v === \"number\" && Number.isFinite(v) && v >= min && v <= max ? null : { field: \"sound.volume\", allowed: `${min}..${max}` }\n}\n\n/** A present base box under the layer rule: anchor and width (a non-object reads as an empty box), every present box field in range. */\nfunction baseBoxIssue(raw: unknown): VideoOverlayIssue | null {\n const own = asLayer(raw) ?? {}\n const box = Object.fromEntries(VIDEO_OVERLAY_BOX_FIELDS.map((f) => [f, own[f]])) as VideoOverlayLayerInput\n if (box.anchor == null || box.width == null) return { ok: false, code: \"incomplete_box\", params: { field: \"baseBox\" } }\n const bad = outOfBounds(box)\n return bad ? { ok: false, code: \"field_out_of_bounds\", params: { ...bad, field: `baseBox.${bad.field}` } } : null\n}\n\n/**\n * Can `resolveVideoOverlayGeometry` place this layer? True when its box is what\n * the validator's box checks require: `anchor` one of the nine anchors, `width`\n * a finite number, and every present box / look field in range\n * (`VIDEO_OVERLAY_BOUNDS`, enums). A partial box saved from workflow JSON\n * (`{ imageUrl, start, width }`, `anchor: null`) is stored as written — the\n * expansion leaves it for the validator's `incomplete_box` — so any reader\n * that DRAWS a stored layer (the canvas stage) must skip one that fails this;\n * the geometry would throw on it.\n */\nexport function hasDrawableVideoOverlayBox(layer: unknown): boolean {\n const l = asLayer(layer)\n if (!l) return false\n if (!(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) return false\n if (typeof l.width !== \"number\" || !Number.isFinite(l.width)) return false\n return outOfBounds(l) === null\n}\n\n/**\n * Spec §3.5 — what a schema cannot express, and what the DAG path skips. Run\n * at every engine entry: the route (`.superRefine`, before the expansion), the\n * canvas single-node run, payload-builder and the worker (after it) — the\n * verdict is the same on either side of the expansion (no code reads an\n * expanded field). Also refuses a PRESENT box / look field outside\n * `VIDEO_OVERLAY_BOUNDS` or its enum / type (`field_out_of_bounds`, spec §4.4's\n * \"out-of-bounds box/opacity/zIndex\" row — on the DAG path this validator is\n * the only check). A layer carries an image or a video, never both\n * (`layer_two_sources`), at most `VIDEO_OVERLAY_MAX_VIDEO_LAYERS` are videos,\n * and only a video layer has `sound`. A non-object `layers[]` entry reads as\n * an empty layer. A `layout` (`\"\"` reads as absent) must be known, a stack\n * takes no `baseBox` (`layout_conflicts_base_box`: it places the base\n * itself); a `baseBox` follows the layer rule (`incomplete_box`,\n * `field_out_of_bounds` as `baseBox.<field>`) and needs an `outputAspect`; a\n * layout gets what it needs (an aspect, a video layer) — checked before\n * `base_box_needs_aspect`, so writing a layout's base box does not change the\n * verdict. The FIRST failure, as a code.\n */\nexport function validateVideoOverlayRequest(body: VideoOverlayValidationInput): VideoOverlayValidation {\n if (body.planError) return { ok: false, code: \"invalid_layer_plan\", params: {} }\n const layers = Array.isArray(body.layers) ? body.layers : []\n if (layers.length === 0) return { ok: false, code: \"no_layers\", params: {} }\n if (layers.length > VIDEO_OVERLAY_MAX_LAYERS) {\n return { ok: false, code: \"too_many_layers\", params: { max: VIDEO_OVERLAY_MAX_LAYERS, count: layers.length } }\n }\n const videoCount = layers.filter(isVideoOverlayVideoLayer).length\n if (videoCount > VIDEO_OVERLAY_MAX_VIDEO_LAYERS) {\n return { ok: false, code: \"too_many_video_layers\", params: { max: VIDEO_OVERLAY_MAX_VIDEO_LAYERS, count: videoCount } }\n }\n for (let i = 0; i < layers.length; i++) {\n const l: VideoOverlayLayerInput = asLayer(layers[i]) ?? {}\n const at = (code: VideoOverlayErrorCode, params: Record<string, string | number> = {}): VideoOverlayIssue => ({\n ok: false,\n code,\n layer: i,\n ...(typeof l.slot === \"number\" ? { slot: l.slot } : {}),\n ...(typeof l.planLayer === \"number\" ? { planLayer: l.planLayer } : {}),\n params,\n })\n const boxFields = VIDEO_OVERLAY_BOX_FIELDS.filter((f) => l[f] !== undefined && l[f] !== null)\n if (!isVideoOverlayPresetId(l.preset) && boxFields.length > 0 && (l.anchor == null || l.width == null)) return at(\"incomplete_box\")\n const bad = outOfBounds(l) ?? soundOutOfBounds(l.sound)\n if (bad) return at(\"field_out_of_bounds\", bad)\n const hasVideo = nonEmpty(l.videoUrl)\n if (nonEmpty(l.imageUrl) && hasVideo) return at(\"layer_two_sources\")\n if (!nonEmpty(l.imageUrl) && !hasVideo) return at(\"layer_without_image\")\n if (l.sound != null && !hasVideo) return at(\"sound_without_video\")\n if (!inTimeRange(l.start)) return at(\"time_out_of_range\", { field: \"start\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (l.end !== undefined && l.end !== null) {\n if (!inTimeRange(l.end)) return at(\"time_out_of_range\", { field: \"end\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (!(l.end > l.start)) return at(\"end_before_start\", { start: l.start, end: l.end })\n }\n }\n const hasAspect = isVideoOverlayOutputAspect(body.outputAspect)\n if (!hasAspect && (body.baseFit != null || body.backgroundColor != null)) {\n return { ok: false, code: \"fit_without_aspect\", params: {} }\n }\n const stored = storedLayout(body.layout)\n if (stored !== undefined && !isVideoOverlayLayoutId(stored)) {\n return { ok: false, code: \"field_out_of_bounds\", params: { field: \"layout\", allowed: VIDEO_OVERLAY_LAYOUT_IDS.join(\", \") } }\n }\n const layout = stored as VideoOverlayLayoutId | undefined\n if (layout && body.baseBox != null && videoOverlayLayoutPlacesBase(layout)) return { ok: false, code: \"layout_conflicts_base_box\", params: { layout } }\n const boxIssue = body.baseBox != null ? baseBoxIssue(body.baseBox) : null\n if (boxIssue) return boxIssue\n if (layout && !hasAspect && videoOverlayLayoutNeedsAspect(layout)) return { ok: false, code: \"layout_needs_aspect\", params: { layout } }\n if (layout && videoOverlayLayoutNeedsVideoLayer(layout) && !layers.some(isVideoOverlayVideoLayer)) {\n return { ok: false, code: \"layout_needs_video_layer\", params: { layout } }\n }\n if (body.baseBox != null && !hasAspect) return { ok: false, code: \"base_box_needs_aspect\", params: {} }\n return { ok: true }\n}\n\nconst MESSAGES: { readonly [C in VideoOverlayErrorCode]: (p: Readonly<Record<string, string | number>>) => string } = {\n no_layers: () => \"At least 1 layer is required\",\n too_many_layers: (p) => `At most ${p.max} layers (got ${p.count})`,\n incomplete_box: (p) => (p.field ? `${p.field} needs an anchor and a width` : \"anchor and width are required without a preset\"),\n layer_without_image: () => \"no image or video — connect one to the layer's handle or set imageUrl or videoUrl\",\n time_out_of_range: (p) => `${p.field} must be between 0 and ${p.max} s`,\n end_before_start: (p) => `end (${p.end} s) must be after start (${p.start} s)`,\n fit_without_aspect: () => \"baseFit and backgroundColor need an outputAspect\",\n field_out_of_bounds: (p) => `${p.field} is out of range (allowed: ${p.allowed})`,\n invalid_layer_plan: () => \"the layer plan must be a list of layers\",\n layer_two_sources: () => \"has both an image and a video — keep one (imageUrl or videoUrl)\",\n too_many_video_layers: (p) => `At most ${p.max} video layers (got ${p.count})`,\n sound_without_video: () => \"sound is only for a video layer — remove it or set videoUrl\",\n base_box_needs_aspect: () => \"baseBox needs an outputAspect\",\n layout_needs_aspect: (p) => `layout ${p.layout} needs an outputAspect`,\n layout_needs_video_layer: (p) => `layout ${p.layout} needs a video layer — set videoUrl on a layer or connect a video to a layer's handle`,\n layout_conflicts_base_box: () => \"A stack layout places the base itself — remove baseBox or choose Custom\",\n}\n\nconst PLAN_LAYER_WITHOUT_IMAGE = \"no image or video — set imageUrl or videoUrl on this layer in the plan.\"\n\n/** `Plan layer <n>` for a layer-plan entry, `Layer <slot>` when the layer came from the canvas, else `layers[<index>]`; \"\" for a request-wide failure. */\nexport function videoOverlayLayerLabel(ref: { readonly layer?: number; readonly slot?: number; readonly planLayer?: number }): string {\n if (typeof ref.planLayer === \"number\") return `Plan layer ${ref.planLayer}`\n return typeof ref.slot === \"number\" ? `Layer ${ref.slot}` : typeof ref.layer === \"number\" ? `layers[${ref.layer}]` : \"\"\n}\n\n/** The ONE English rendering of a verdict — the route's 400 text and the worker's error message. */\nexport function formatVideoOverlayError(issue: VideoOverlayIssue): string {\n const label = videoOverlayLayerLabel(issue)\n // A plan layer has no handle to connect — its source can only come from its own imageUrl or videoUrl.\n const text = issue.code === \"layer_without_image\" && typeof issue.planLayer === \"number\" ? PLAN_LAYER_WITHOUT_IMAGE : MESSAGES[issue.code](issue.params)\n return label ? `${label}: ${text}` : text\n}\n","/**\n * Video Overlay layouts and the placed base — the request-level normaliser\n * (`expandVideoOverlayLayout`) and the geometry the canvas preview and the\n * ffmpeg worker both call, so the preview and the render cannot disagree.\n * A sibling of `video-overlay.ts`: it imports from there, nothing there imports\n * from here, and the layout ids live in the dependency-free\n * `video-overlay-layout-ids.ts`.\n *\n * - `video-bottom` / `video-top` write a base box; an explicit one wins.\n * - `pip` writes the first video layer's box in its corner.\n * - The two stacks write no box: their rects depend on the sources' shapes,\n * known only after probing, so the worker and the preview call\n * `resolveVideoOverlayStackRects` with them. A stack places the base\n * itself, so the validator refuses one with a `baseBox` (`layout_conflicts_base_box`).\n * `pip` and the two stacks turn the first video layer's fade off;\n * `video-bottom` / `video-top` touch no layer. \"First video layer\" is the\n * lowest one (`firstVideoLayerIndex`); image layers are left where they are.\n * A probed video's aspect goes through `clampVideoOverlayAspect` before any of\n * this geometry, and a video's rect through `evenVideoOverlayRect` after it —\n * in the worker and the preview alike.\n * Wire contract only — no I/O.\n */\nimport {\n VIDEO_OVERLAY_BOX_FIELDS,\n expandVideoOverlayLayer,\n isVideoOverlayCorner,\n videoOverlayRenderOrder,\n type VideoOverlayBox,\n type VideoOverlayBoxInput,\n type VideoOverlayCorner,\n type VideoOverlayFit,\n type VideoOverlayLayer,\n type VideoOverlayLayerInput,\n type VideoOverlayOrderable,\n} from \"./video-overlay.js\"\nimport { resolveVideoOverlayGeometry, type VideoOverlayCanvas, type VideoOverlayRect } from \"./video-overlay-geometry.js\"\nimport { validateVideoOverlayRequest } from \"./video-overlay-validate.js\"\nimport { isVideoOverlayVideoLayer } from \"./video-overlay-video-layers.js\"\n\n/** Picture in picture: the inset's width and its margin from the corner, % of the output canvas (Speaker View's inset). */\nexport const VIDEO_OVERLAY_PIP_WIDTH = 30\nexport const VIDEO_OVERLAY_PIP_INSET = 4\n\n/** What a layout reads and writes — a request, an assembled request, or node data. */\nexport interface VideoOverlayLayoutFields {\n readonly layout?: string | null\n readonly baseBox?: VideoOverlayBoxInput | null\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n}\n\n/** The base box each edge layout writes: the base whole, full width, flush on that edge. */\nconst EDGE_BASE_BOXES: { readonly [L in \"video-bottom\" | \"video-top\"]: VideoOverlayBox } = {\n \"video-bottom\": { anchor: \"bottom\", x: 0, y: 0, width: 100, fit: \"contain\" },\n \"video-top\": { anchor: \"top\", x: 0, y: 0, width: 100, fit: \"contain\" },\n}\n\n/** A base box's trailing defaults, as a layer's (`expandVideoOverlayLayer`). */\nconst BOX_DEFAULTS = { x: 0, y: 0, fit: \"contain\" } as const\n\n/**\n * The narrowest and widest aspect a probed video is placed at. A video's\n * shape is only known from its probe, and nothing bounds a probe, so a stack\n * of a 1:1000 sliver could otherwise place a rect off the canvas. Inside these\n * bounds every stack, base and layer rect stays on it.\n */\nexport const VIDEO_OVERLAY_ASPECT_BOUNDS = [1 / 8, 8] as const\n\n/** Rounded down to even, floored at 2; the epsilon absorbs float error at an exact even size (960.0000 read as 959.9999). */\nconst evenFloor = (n: number): number => Math.max(2, Math.floor(n / 2 + 1e-9) * 2)\nconst usableAspect = (a: number): number => (Number.isFinite(a) && a > 0 ? a : 1)\n\n/**\n * A probed video's display aspect (width ÷ height), held inside\n * `VIDEO_OVERLAY_ASPECT_BOUNDS`; one that is not a positive finite number\n * reads as square, as in the layer geometry. The worker and the preview pass\n * every video's aspect (the base's and each video layer's) through this before\n * any placement, so they place the same rects.\n */\nexport function clampVideoOverlayAspect(aspect: number): number {\n const [min, max] = VIDEO_OVERLAY_ASPECT_BOUNDS\n return Number.isFinite(aspect) && aspect > 0 ? Math.min(max, Math.max(min, aspect)) : 1\n}\n\n/** Rounded down to an even integer, negatives included (−61 → −62). */\nconst floorEven = (n: number): number => Math.floor(n / 2) * 2\n\n/**\n * A video's rect as the render draws it: left and top rounded DOWN to even,\n * and the size down to even. ffmpeg's overlay on yuv420 clears the low bit of\n * an odd x or y (a base placed at top 371 is drawn at 370), so this is where\n * the picture lands anyway; the worker hands the graph these numbers and the\n * preview draws them, so the two agree to the pixel. A stack's two rects move\n * by the same pixel (its heights are even), so its join stays exact. Applied\n * to the base's rect and to video layers only — an image layer's geometry is\n * unchanged. By reference when the rect is already even.\n */\nexport function evenVideoOverlayRect(rect: VideoOverlayRect): VideoOverlayRect {\n const even = { left: floorEven(rect.left), top: floorEven(rect.top), width: evenFloor(rect.width), height: evenFloor(rect.height) }\n return sameShallow(even, rect) ? rect : even\n}\n\nfunction sameShallow(a: object, b: object): boolean {\n const ka = Object.keys(a)\n return ka.length === Object.keys(b).length && ka.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k])\n}\n\n/** The lowest video layer by `videoOverlayRenderOrder`, as its index in `layers`; -1 when there is none. */\nexport function firstVideoLayerIndex(\n layers: ReadonlyArray<(VideoOverlayOrderable & { readonly videoUrl?: string | null }) | null | undefined> | null | undefined,\n): number {\n if (!Array.isArray(layers)) return -1\n return videoOverlayRenderOrder(layers).find((i) => isVideoOverlayVideoLayer(layers[i])) ?? -1\n}\n\n/**\n * An explicit base box with `anchor` and `width` gets the layer's trailing\n * defaults (x 0, y 0, fit contain) and loses its `null` fields; anything else\n * (a partial box, a non-object) is returned untouched for the validator. By\n * reference when nothing changes.\n */\nfunction expandBaseBox(raw: VideoOverlayBoxInput): VideoOverlayBoxInput {\n if (typeof raw !== \"object\" || Array.isArray(raw) || raw.anchor == null || raw.width == null) return raw\n const out: Record<string, unknown> = { ...BOX_DEFAULTS }\n for (const [k, v] of Object.entries(raw)) if (v != null) out[k] = v\n return sameShallow(out, raw) ? raw : (out as VideoOverlayBoxInput)\n}\n\nfunction pipBox(corner: VideoOverlayCorner): VideoOverlayBox {\n const sx = corner.endsWith(\"left\") ? 1 : -1\n const sy = corner.startsWith(\"top\") ? 1 : -1\n return { anchor: corner, x: sx * VIDEO_OVERLAY_PIP_INSET, y: sy * VIDEO_OVERLAY_PIP_INSET, width: VIDEO_OVERLAY_PIP_WIDTH, fit: \"contain\" }\n}\n\n/**\n * The validator's per-layer verdict on this layer alone (a one-layer request\n * meets no request-level check). A layout never repairs a layer it refuses — a\n * bad or partial box, a non-boolean `animate`, two sources, a bad time or\n * volume — so the verdict is the same before and after the expansion, as\n * `expandBaseBox` leaves a partial base box for the validator.\n */\nconst acceptedAlone = (layer: VideoOverlayLayerInput): boolean => validateVideoOverlayRequest({ layers: [layer] }).ok\n\n/**\n * The first video layer under `pip` or a stack, the layouts that place it:\n * `pip` replaces its box (as a preset click does: height and tag go), and each\n * of them turns its fade off. A layer the validator would refuse is returned\n * untouched.\n */\nfunction placeFirstVideoLayer(layout: string, layer: VideoOverlayLayerInput): VideoOverlayLayerInput {\n if (!acceptedAlone(layer)) return layer\n if (layout !== \"pip\") return layer.animate === false ? layer : { ...layer, animate: false }\n const rest: Record<string, unknown> = { ...layer }\n for (const f of VIDEO_OVERLAY_BOX_FIELDS) delete rest[f]\n delete rest.preset\n const corner = isVideoOverlayCorner(layer.corner) ? layer.corner : \"bottom-right\"\n const next = expandVideoOverlayLayer({ ...rest, ...pipBox(corner), animate: false } as VideoOverlayLayerInput)\n return sameShallow(next, layer) ? layer : next\n}\n\n/**\n * The request-level normaliser: what a `layout` writes, and an explicit base\n * box's defaults. Called at the write boundaries and by the worker after the\n * validator. An explicit `baseBox` wins over `video-bottom` / `video-top`;\n * `pip` places the first video layer; the stacks write no box. An unknown\n * layout writes nothing (the validator refuses it), and neither does any\n * layout to a first video layer the validator refuses, so the verdict is the\n * same before and after. Never mutates; the request BY REFERENCE when nothing\n * changes; idempotent.\n */\nexport function expandVideoOverlayLayout<T extends VideoOverlayLayoutFields>(req: T): T & { readonly baseBox?: VideoOverlayBox } {\n const { layout } = req\n const baseBox =\n req.baseBox != null ? expandBaseBox(req.baseBox) : layout === \"video-bottom\" || layout === \"video-top\" ? EDGE_BASE_BOXES[layout] : req.baseBox\n let layers = req.layers\n const first = layout === \"pip\" || layout === \"stack-whole\" || layout === \"stack-filled\" ? firstVideoLayerIndex(req.layers) : -1\n if (first >= 0 && Array.isArray(req.layers)) {\n const layer = req.layers[first] as VideoOverlayLayerInput\n const placed = placeFirstVideoLayer(layout as string, layer)\n if (placed !== layer) layers = req.layers.map((l, i) => (i === first ? placed : l))\n }\n if (baseBox === req.baseBox && layers === req.layers) return req as T & { readonly baseBox?: VideoOverlayBox }\n // Only the changed fields: an unset one never becomes an `undefined` key.\n return {\n ...req,\n ...(baseBox !== req.baseBox ? { baseBox } : {}),\n ...(layers !== req.layers ? { layers } : {}),\n } as T & { readonly baseBox?: VideoOverlayBox }\n}\n\n/**\n * The two stacked rects, `top` for the base and `bottom` for the first video\n * layer, in output pixels.\n * - `stack-whole`: both whole, the same even width, touching, the pair centred\n * with equal spare room above and below (±1 px). They shrink together only\n * when both together are taller than the canvas. The join is pixel-exact.\n * - `stack-filled`: the top half (rounded down to even) and the rest, full\n * width; the aspects are not read — both are cropped (`cover`).\n * An aspect that is not a positive finite number reads as square.\n */\nexport function resolveVideoOverlayStackRects(\n layout: \"stack-whole\" | \"stack-filled\",\n canvas: VideoOverlayCanvas,\n topAspect: number,\n bottomAspect: number,\n): { top: VideoOverlayRect; bottom: VideoOverlayRect } {\n if (layout === \"stack-filled\") {\n const half = evenFloor(canvas.h / 2)\n return {\n top: { left: 0, top: 0, width: canvas.w, height: half },\n bottom: { left: 0, top: half, width: canvas.w, height: canvas.h - half },\n }\n }\n const a = usableAspect(topAspect)\n const b = usableAspect(bottomAspect)\n const total = canvas.w / a + canvas.w / b\n const width = evenFloor(total > canvas.h ? (canvas.w * canvas.h) / total : canvas.w)\n const th = evenFloor(width / a)\n const bh = evenFloor(width / b)\n const top = Math.floor((canvas.h - th - bh) / 2)\n const left = Math.floor((canvas.w - width) / 2)\n return {\n top: { left, top, width, height: th },\n bottom: { left, top: top + th, width, height: bh },\n }\n}\n\n/** A picture placed on the output canvas: its even rect and how it fills it (contain = scaled to the rect, cover = cropped to it). */\nexport interface VideoOverlayPlacedRect {\n readonly drawn: VideoOverlayRect\n readonly fit: VideoOverlayFit\n}\n\n/** A video layer to place. */\nexport interface PlacedVideoOverlayVideoInput {\n /** 0-based index in the request's layers[] (what `firstVideo` names). */\n readonly index: number\n readonly layer: Pick<VideoOverlayLayer, \"anchor\" | \"x\" | \"y\" | \"width\" | \"height\" | \"fit\">\n /** Its display aspect (width ÷ height, rotation and sample aspect resolved); held inside the bounds here. */\n readonly aspect: number\n}\n\nexport interface VideoOverlayVideoPlacement {\n /** Present when the base is placed (a stack or a base box); absent = the base as before (its own size, or `outputAspect` with `baseFit`). */\n readonly basePlacement?: VideoOverlayPlacedRect\n /** Each video layer's even drawn rect and fit, by request index. */\n readonly layers: ReadonlyMap<number, VideoOverlayPlacedRect>\n}\n\n/**\n * Where the base and every video layer draw, on the output canvas — the ONE\n * placement the worker renders with and the canvas preview draws with. Every\n * aspect goes through `clampVideoOverlayAspect` and every rect through\n * `evenVideoOverlayRect` here, so neither caller can skip them.\n * - A stack (`stack-whole` / `stack-filled`): both rects from\n * `resolveVideoOverlayStackRects` with the base's and the first video\n * layer's aspects; that layer's stored box is not read. `stack-filled` draws\n * both `cover`, `stack-whole` both `contain`, whatever fit is stored.\n * - Otherwise a base box (written by `video-bottom` / `video-top`, or explicit)\n * places the base with `resolveVideoOverlayBaseRect` at its own fit.\n * - Every other video layer: its box, `resolveVideoOverlayGeometry`, at its\n * aspect (`pip` has already written its box).\n * An image layer is not placed here: its geometry is unchanged. The caller\n * passes a stack's first video layer among `videos` (the worker refuses a\n * stack whose first video layer it does not keep). Pure.\n */\nexport function placeVideoOverlayVideos(input: {\n readonly canvas: VideoOverlayCanvas\n readonly layout?: string | null\n readonly baseBox?: VideoOverlayBox\n readonly baseAspect: number\n /** `firstVideoLayerIndex` of the request's layers: what a stack places under the base. */\n readonly firstVideo: number\n readonly videos: ReadonlyArray<PlacedVideoOverlayVideoInput>\n}): VideoOverlayVideoPlacement {\n const { canvas, layout } = input\n const baseAspect = clampVideoOverlayAspect(input.baseAspect)\n const layers = new Map<number, VideoOverlayPlacedRect>()\n let basePlacement: VideoOverlayPlacedRect | undefined\n if (layout === \"stack-whole\" || layout === \"stack-filled\") {\n const first = input.videos.find((v) => v.index === input.firstVideo)\n if (!first) throw new Error(`placeVideoOverlayVideos: the stacked layer ${input.firstVideo} was not kept`)\n const rects = resolveVideoOverlayStackRects(layout, canvas, baseAspect, clampVideoOverlayAspect(first.aspect))\n const fit: VideoOverlayFit = layout === \"stack-filled\" ? \"cover\" : \"contain\"\n basePlacement = { drawn: evenVideoOverlayRect(rects.top), fit }\n layers.set(first.index, { drawn: evenVideoOverlayRect(rects.bottom), fit })\n } else if (input.baseBox) {\n basePlacement = { drawn: evenVideoOverlayRect(resolveVideoOverlayBaseRect(canvas, input.baseBox, baseAspect)), fit: input.baseBox.fit }\n }\n for (const v of input.videos) {\n if (layers.has(v.index)) continue\n const { drawn } = resolveVideoOverlayGeometry(canvas, v.layer, clampVideoOverlayAspect(v.aspect))\n layers.set(v.index, { drawn: evenVideoOverlayRect(drawn), fit: v.layer.fit })\n }\n return { ...(basePlacement ? { basePlacement } : {}), layers }\n}\n\n/**\n * Where a placed base draws, in output pixels. Its SIZE is the layer\n * geometry's drawn size (`resolveVideoOverlayGeometry`: the same clamp and even\n * rounding as an image layer); it is then placed by that drawn size against the\n * anchor, plus the x / y offsets — so a contained base sits flush on its\n * anchored edge rather than centred in a box rounded to other numbers (a 16:9\n * base at the bottom of 1080x1920 draws at y 1314–1920, with no strip under it).\n */\nexport function resolveVideoOverlayBaseRect(canvas: VideoOverlayCanvas, box: VideoOverlayBox, baseAspect: number): VideoOverlayRect {\n const { drawn } = resolveVideoOverlayGeometry(canvas, box, baseAspect)\n const ax = box.anchor.endsWith(\"left\") ? 0 : box.anchor.endsWith(\"right\") ? 1 : 0.5\n const ay = box.anchor.startsWith(\"top\") ? 0 : box.anchor.startsWith(\"bottom\") ? 1 : 0.5\n return {\n left: Math.round(ax * (canvas.w - drawn.width) + (box.x / 100) * canvas.w),\n top: Math.round(ay * (canvas.h - drawn.height) + (box.y / 100) * canvas.h),\n width: drawn.width,\n height: drawn.height,\n }\n}\n","/**\n * Video-analysis node — shared data contract.\n *\n * Single source of truth for the video-analysis node: the backend worker, the\n * frontend, and a future generator all import from here. Two schema layers:\n * - `windowAnalysisSchema` — what the LLM emits per analysis window\n * (strict-JSON footer). `scenes` has NO min (a quiet window returning zero\n * scenes is a VALID result). Model-emitted `oversized`/`slotRefs` are\n * STRIPPED here — they are validator-computed later (z.object drops unknown\n * keys by default).\n * - `videoAnalysisResultSchema` — the merged, validator-computed result across\n * all windows; requires >=1 scene overall.\n *\n * Entity slots are referenced in scene `visual` text via `{slot:<id>}` tokens\n * (`SLOT_TOKEN_RE`) — a grammar distinct from `NODE_REF_PATTERN` and the\n * `{image:N}` reference tokens. Unresolved tokens UNWRAP to their literal id\n * text, never delete (spec invariant), so a downstream prompt never carries a\n * dangling `{slot:…}` placeholder.\n */\nimport { z } from \"zod\"\n\nexport const VIDEO_ANALYSIS_MAX_SCENE_SEC = 8\n\n/**\n * Camera VIEWPOINT — where the camera is relative to the subject. The axis\n * `shotType` does not carry, and the one the analyzer had been improvising.\n *\n * Two failures this fixes, both from real jobs:\n *\n * 1. `shotType` is framing SIZE (Wide … Extreme Close-Up), so a true angle had\n * nowhere to go and landed in the MOVEMENT field instead:\n * `\"camera\": \"low angle static\"`. That loses the angle to anything reading\n * `camera` and pollutes the movement vocabulary.\n * 2. The relational viewpoints — `Over-the-Shoulder`, `POV` — were conventions\n * inside the `shotType` list, competing with the sizes for one slot. So an\n * over-the-shoulder MEDIUM had to pick one and threw the other away. They\n * belong here, leaving `shotType` free to state the size: an OTS medium is\n * `shotType: \"Medium\"` + `angle: \"over-the-shoulder\"`, which is strictly more\n * than either field could carry alone.\n *\n * A closed enum rather than free text precisely because improvisation is the\n * failure being fixed. Absent means EYE-LEVEL — the overwhelming default, so\n * omitting it costs nothing on most shots (the same \"absence is the default\"\n * shape as `transitionOut` and appearance variations).\n *\n * `from-behind` and `over-the-shoulder` also carry real meaning downstream: a\n * face is not visible in either, which is what auto-cast needs to know before\n * choosing one as an identity reference.\n */\nexport const VIDEO_ANALYSIS_SHOT_ANGLES = [\n // Vertical placement and roll — the classical \"angles\".\n \"eye-level\", \"low\", \"high\", \"overhead\", \"worms-eye\", \"dutch\",\n // Relational viewpoints — where the camera sits with respect to the subject.\n \"over-the-shoulder\", \"pov\", \"profile\", \"from-behind\",\n] as const\nexport type VideoAnalysisShotAngle = (typeof VIDEO_ANALYSIS_SHOT_ANGLES)[number]\n\n/** Viewpoints in which the subject's FACE is not visible — so a frame shot this\n * way is a poor identity reference however good its framing otherwise is. */\nexport const VIDEO_ANALYSIS_FACELESS_ANGLES: ReadonlySet<string> = new Set([\"over-the-shoulder\", \"from-behind\"])\n\n/**\n * Effects applied to the PICTURE of a shot. An array — a shot can be grainy and\n * vignetted at once — and absent when the image is clean, which is most shots.\n *\n * Scoped deliberately to things done to the IMAGE, and NOT to compositing that\n * asserts what is in the shot (picture-in-picture, split screen). That line\n * matters: a real job invented `{slot:creator} overlay talking to camera` across\n * nine scenes for a man who is never seen, so a field for \"there is an inset of a\n * person here\" would hand that fabrication a legitimate home. An effect is\n * verifiable in the pixels; a claim about who is inset is not.\n *\n * `dissolve` and `fade` are NOT here either — they are edits BETWEEN shots and\n * belong to `transitionOut`.\n */\nexport const VIDEO_ANALYSIS_VISUAL_EFFECTS = [\n \"blur\", \"pixelate\", \"glitch\", \"grain\", \"vignette\", \"flash\", \"distortion\", \"double-exposure\",\n] as const\nexport type VideoAnalysisVisualEffect = (typeof VIDEO_ANALYSIS_VISUAL_EFFECTS)[number]\n\n/**\n * Visible edit INTO the next shot.\n *\n * `dissolve` (a cross-fade from one image to the other) is distinct from `fade`\n * (through black or white). Collapsing both onto `fade` — as this enum did — makes\n * a recreation render the wrong edit, and the two look nothing alike.\n *\n * ABSENT means NOTHING ASSERTED (since v2): the analyser emits a value only\n * when it can see the device; an unknown or uncertain edit is left out so the\n * video model chooses. `cut` is itself an assertion (an instant change between\n * two clearly different shots), never a default.\n */\nexport const VIDEO_ANALYSIS_TRANSITIONS = [\n \"cut\", \"fade\", \"dissolve\", \"wipe\", \"whip\",\n // v2 (2026-08-30, recast shot craft rev 1.5 Appendix F): the common edits a\n // creator actually cuts with. `white-flash` / `digital-glitch` are spelled\n // out because `flash` / `glitch` already name in-shot EFFECTS (the axis test\n // below) — a device is the edit BETWEEN two shots, an effect is on one shot.\n \"zoom\", \"slide\", \"white-flash\", \"digital-glitch\", \"morph\", \"match\", \"jump\",\n] as const\nexport type VideoAnalysisTransition = (typeof VIDEO_ANALYSIS_TRANSITIONS)[number]\n\n/**\n * What burned-in text IS (2026-08-28, recast shot craft). Decides render-vs-omit\n * downstream: a `subtitle` is a transcription of the piece's own speech — a\n * recreation re-speaks it and must not render it — while a `title`, `caption`,\n * `lower-third` or `logo` is picture content. Absent when a scene carries no\n * text. A new KEY on the scene: strip-mode readers drop it harmlessly.\n */\nexport const VIDEO_ANALYSIS_TEXT_KINDS = [\"title\", \"caption\", \"lower-third\", \"subtitle\", \"logo\", \"other\"] as const\nexport type VideoAnalysisTextKind = (typeof VIDEO_ANALYSIS_TEXT_KINDS)[number]\n\n/** How the CLIP opens (clip-level, not per scene — a window's first scene is\n * not the clip's). Absent ⇒ a hard open. Only `fade` today. */\nexport const VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN = [\"fade\"] as const\nexport type VideoAnalysisClipTransitionIn = (typeof VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN)[number]\n\n/**\n * Time manipulation — slow motion, ramps, timelapse, freeze, reverse.\n *\n * Previously unrepresentable anywhere in the schema, so a recreation rendered\n * every shot at normal speed no matter what the footage did. It is a first-class\n * lever in every video model and a real editing decision in most action footage.\n *\n * `\"normal\"` is deliberately NOT a member: absence is normal speed, so there is\n * exactly one way to say \"nothing unusual here\" and the field costs nothing on\n * the majority of shots.\n */\nexport const VIDEO_ANALYSIS_SPEED_EFFECTS = [\"slow-motion\", \"ramp-in\", \"ramp-out\", \"timelapse\", \"freeze\", \"reverse\"] as const\n\n/** CHRONICLE TIME (2026-08-17): the STORY clock, per scene, as read from the\n * pictures — light, sky, practicals. \"ambiguous\" is the honest answer for a\n * windowless interior; guessing day is exactly the kind of tidy inference\n * the analysis doctrine forbids. */\nexport const VIDEO_ANALYSIS_TIMES_OF_DAY = [\"dawn\", \"day\", \"dusk\", \"night\", \"ambiguous\"] as const\n\n/** STORY JUMP since the PREVIOUS scene in the list: how much narrative time\n * passed across the cut, judged from evidence (wardrobe change, aged\n * subjects, season, a title card), not from the cut itself. Time outranks\n * location for continuity judgements (same person, new place, continuous\n * time ⇒ same outfit; same place, years later ⇒ anything may differ), which\n * is why this is a structured field and not prose. \"unclear\" is the honest\n * default; the FIRST scene of a clip is \"continuous\" by convention. */\nexport const VIDEO_ANALYSIS_STORY_JUMPS = [\"continuous\", \"same-day\", \"another-day\", \"years-later\", \"unclear\"] as const\nexport type VideoAnalysisSpeedEffect = (typeof VIDEO_ANALYSIS_SPEED_EFFECTS)[number]\n\n/**\n * The CLIP-LEVEL look — one source of truth for the properties that belong to\n * the whole piece rather than any one shot.\n *\n * Colour grade, camera format and lens character were previously only ever prose\n * inside each scene's `visual`, which meant a 43-scene analysis re-decided the\n * grade forty-three independent times with nothing holding them consistent. That\n * is the same drift problem entity slots solve for people: state it once, apply it\n * everywhere. A recreation reads this alongside every scene.\n *\n * Every field optional — an analyzer that cannot read the format should say\n * nothing rather than guess, and a per-scene deviation still belongs in that\n * scene's `visual` prose.\n */\nexport const clipLookSchema = z.object({\n /**\n * The rendering MEDIUM — \"live-action photoreal\", \"2D anime\", \"stop-motion\n * claymation\", \"3D render\", \"oil painting\", \"pixel art\".\n *\n * The most consequential field in this object, and orthogonal to every other\n * one: two shots with identical grade, lens, lighting and framing still look\n * nothing alike when one is live action and the other is an oil painting. Get\n * this wrong and a recreation renders the whole piece in the wrong medium,\n * which no amount of correct grade or lighting can rescue.\n *\n * Mirrors the product's Style picker, whose catalog defines exactly this axis\n * and states its independence from lighting, colour-look, atmosphere and lens.\n * A clip that genuinely changes medium partway (live action with an animated\n * insert) states the deviation in that scene's `visual`, as with `lighting`.\n */\n style: z.string().optional(),\n /**\n * The Style picker CATALOG ID the prose in `style` corresponds to — the\n * analyzer's PICK (\"pixar-3d\" beside \"3D stylized animation\"), not a second\n * description of it.\n *\n * Worth strictly more than the prose it accompanies: an id addresses the\n * catalog, so a recreation renders the same medium the product's own Style\n * picker would render, instead of re-interpreting a sentence. Absent when the\n * analyzer read a medium it could not place in the catalog — `style` then\n * carries the whole answer, as it always did.\n *\n * A free `string` here on purpose. The PRODUCER validates it against the\n * catalog (the analyzer plugin's wire schema is an enum generated from\n * `STYLES`, so an invented id never leaves it), while this package must not\n * carry the catalog itself. A closed enum here would only add a second copy\n * of the vocabulary to drift out of date — and, worse, would REJECT a\n * catalog entry newer than the installed `@nodaro/shared`, which is exactly\n * the analysis a consumer most wants to read.\n */\n styleId: z.string().optional(),\n /** Colour grade / palette — \"muted teal-and-orange, crushed blacks\". */\n grade: z.string().optional(),\n /** Camera or film FORMAT and stock — \"anamorphic digital\", \"16mm film grain\". */\n format: z.string().optional(),\n /** Lens character — \"wide-angle, shallow depth of field throughout\". */\n lens: z.string().optional(),\n /** Overall lighting style — \"hard single-source daylight, deep shadow\". */\n lighting: z.string().optional(),\n /** What KIND of piece this is — \"cinematic trailer\", \"talking-head vlog\". */\n genre: z.string().optional(),\n /**\n * The visual INFLUENCE the piece clearly evokes — a cinematographer, director,\n * photographer or named aesthetic (\"shot like Deakins\", \"Wes Anderson\n * symmetry\", \"80s Kodachrome editorial\").\n *\n * The highest-leverage field here by a distance: a couple of words transfer a\n * whole aesthetic that would otherwise take a paragraph of grade, lens and\n * lighting prose to approximate — which is exactly why the product already\n * exposes it as a curated picker (\"Photographer / Artist\") whose catalog ships\n * `in the style of …` prompt hints. The analyzer had no way to read it back.\n *\n * Deliberately conservative: OMIT unless the footage genuinely evokes a\n * well-known, nameable style. A confident misattribution is worse than silence,\n * because it drags an entire wrong aesthetic into every regenerated shot — so\n * describing the look in `grade`/`lighting` always beats guessing a name.\n */\n influence: z.string().optional(),\n})\nexport type ClipLook = z.infer<typeof clipLookSchema>\nexport const VIDEO_ANALYSIS_ENTITY_SOURCES = [\"wired-character\", \"wired-object\", \"wired-location\", \"wired-creature\"] as const\nexport type VideoAnalysisEntitySource = (typeof VIDEO_ANALYSIS_ENTITY_SOURCES)[number]\n/** Matches {slot:<id>} tokens. Distinct from NODE_REF_PATTERN / {image:N} grammars. */\nexport const SLOT_TOKEN_RE = /\\{slot:([a-z0-9-]+)\\}/g\n\n/**\n * Appearance variations (cast-variations spec, 2026-07-24): a slot's canonical\n * `description` IS its default look; `variations` enumerates NON-default looks\n * only (dream vs reality, flashback, disguise…). `\"default\"` is a reserved\n * variationId — used in scene bindings / ledger keys / routing for unbound\n * scenes, never inside `variations[]`. The closed slug vocabulary is\n * doctrine-enforced (the schema pins only the id charset, like `role`);\n * `alt-1`/`alt-2` are the escape hatches.\n */\nexport const VIDEO_ANALYSIS_VARIATION_SLUGS = [\"dream\", \"flashback\", \"disguise\", \"costume\", \"transformation\", \"era\", \"alt-1\", \"alt-2\"] as const\n/** Max NON-default looks per slot. The window layer REJECTS past the cap (schema-forced retry); the cross-window merge FOLDS at the cap. */\nexport const VIDEO_ANALYSIS_MAX_VARIATIONS = 4\nexport const VIDEO_ANALYSIS_DEFAULT_VARIATION = \"default\"\n\nexport const slotVariationSchema = z.object({\n variationId: z.string().min(1).regex(/^[a-z0-9-]+$/)\n .refine((id) => id !== VIDEO_ANALYSIS_DEFAULT_VARIATION, { message: `\"${VIDEO_ANALYSIS_DEFAULT_VARIATION}\" is reserved for the slot's canonical look` }),\n label: z.string().min(1),\n /** Full STANDALONE casting-sheet look restating the slot's invariant identity\n * core (face, build, age) — the manifest substitutes it wholesale, so a\n * wardrobe-only delta would silently delete identity from the prompt. */\n description: z.string().min(1),\n /** Per-variation identity reference (auto-cast frame or user sheet). In the\n * schema from day one: every strip-mode round-trip must carry it. */\n refImageUrl: z.string().url().optional(),\n})\nexport type SlotVariation = z.infer<typeof slotVariationSchema>\n\nexport const entitySlotSchema = z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n label: z.string().min(1),\n source: z.enum(VIDEO_ANALYSIS_ENTITY_SOURCES),\n role: z.string().min(1),\n description: z.string().min(1),\n /** Auto-cast visual reference — a hosted frame from the analyzed footage\n * where this entity is clearly visible. Optional/additive: producers may\n * omit it; consumers use it as an identity reference for recreation. */\n refImageUrl: z.string().url().optional(),\n /**\n * Why `refImageUrl` is ABSENT, when the analyzer's vision pass actively\n * refused every candidate frame rather than merely failing to produce one.\n *\n * Present only alongside a missing `refImageUrl`, and only for a real refusal\n * — never for a technical failure, so its presence always carries meaning. The\n * important case reads like \"the shots bound to this slot show someone else —\n * cast as X, but on screen: Y\", which is the analyzer telling you the casting\n * description and the footage disagree. A consumer should treat that as a\n * reason to review the slot before spending on regeneration, since a wrong\n * identity propagates into every regenerated shot.\n */\n refRejectedReason: z.string().optional(),\n /** NON-default looks only; present only when at least one exists. */\n variations: z.array(slotVariationSchema).max(VIDEO_ANALYSIS_MAX_VARIATIONS).optional(),\n /**\n * WHOSE THIS OBJECT IS (2026-09-17). An object slot that is worn, held,\n * carried, driven or ridden by a cast person or creature names that slot\n * here, with the relation as a short passive phrase ending in \"by\" (\"worn\n * by\", \"held by\", \"driven by\"). The link says the object slot IS the one on\n * that person — not a second one: a recast that saw \"Man in Blue Silk\n * Shirt\" AND \"Blue Silk Shirt\" as unrelated slots rendered two shirts.\n * Object slots only; a free-standing prop, the product on a table, a place\n * or a person never carries it. Optional/additive: producers may omit it.\n */\n owner: z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n relation: z.string().min(1),\n }).optional(),\n})\nexport type EntitySlot = z.infer<typeof entitySlotSchema>\nexport type EntitySlotOwner = NonNullable<EntitySlot[\"owner\"]>\n\n/**\n * The sound LAYER vocabulary — what kind of thing this layer is.\n *\n * `ambience` is deliberately its own member rather than a flavour of `sfx`:\n * they are different layers of a real mix and they are recreated by different\n * means — ambience is the continuous bed a scene sits in (room tone, distant\n * traffic, wind), an sfx is a discrete hit (a door slam, a gunshot). Folded\n * together, a scene's bed and its one-off noises arrive indistinguishable and\n * anything recreating the mix has to guess which it was told.\n *\n * Exported so a consumer keying its own document by these modes imports the\n * vocabulary instead of restating it — the same reason every other closed\n * vocabulary in this file is a const.\n */\nexport const VIDEO_ANALYSIS_AUDIO_MODES = [\"speech\", \"music\", \"sfx\", \"ambience\"] as const\nexport type VideoAnalysisAudioMode = (typeof VIDEO_ANALYSIS_AUDIO_MODES)[number]\n\n/**\n * One concurrent sound layer in a scene. Real footage stacks sound (music bed\n * under dialogue over ambient room tone), so a scene carries an ARRAY of these\n * — an empty array means genuine silence. `content`: speech = verbatim words;\n * music/sfx/ambience = gen-ready description. `voice` is speech-only\n * voice-casting.\n */\nconst audioLayerSchema = z.object({\n mode: z.enum(VIDEO_ANALYSIS_AUDIO_MODES),\n content: z.string().min(1),\n voice: z.string().optional(),\n /**\n * SPEECH ONLY — `slotId` of the on-screen speaker saying these words.\n *\n * `voice` casts a voice (\"male, proud triumphant shouting\"); this says WHO it\n * belongs to, so a recreation can route the line to the right character\n * instead of guessing. Usually one person speaks per scene and the guess is\n * right, which is exactly why the cases with two speakers over one cut fail\n * silently without this field.\n *\n * Optional by design and deliberately NOT refined against `mode` here: the\n * window schema is the enforced decode grammar, and rejecting a whole roll\n * because the model tagged a music layer would be a hair-trigger failure. A\n * speaker on a non-speech layer, or one naming a slot that no longer exists,\n * is stripped structurally by `dropUnknownSpeakers` — the same\n * unwrap/drop/sweep philosophy the slot-token and binding channels use.\n *\n * An unseen narrator gets NO speaker: a voice with no body is never a slot\n * (doctrine §5), so attribution here would resurrect the phantom-entity\n * defect that `stripOrphanSlots` exists to kill.\n */\n speakerSlot: z.string().optional(),\n /**\n * SPEECH ONLY — WHO says these words, by NAME.\n *\n * The second of two ways to name a speaker, and the one for documents that\n * have no slots: `speakerSlot` addresses an `EntitySlot` of THIS analysis by\n * id, while `speaker` is the plain cast name a production keys its own cast\n * by (\"Jack Mercer\"). A layer may legitimately carry both — the id for the\n * analysis it came from, the name for the document it is going into — and a\n * consumer that understands only one reads the one it understands.\n *\n * Optional, and not refined against `mode`, for the same reason\n * `speakerSlot` is not: the window schema is the enforced decode grammar and\n * must not throw away a whole roll over one mis-tagged field.\n *\n * NOT swept by `dropUnknownSpeakers`. That function is the SLOT channel's\n * sanitizer — it judges an id against the surviving slot list, and a name has\n * no id space to be unknown in. The asymmetry is deliberate and pinned by\n * test; whoever owns the name's vocabulary sanitizes the name.\n *\n * The residual that leaves: a layer can keep a `speaker` naming someone\n * `stripOrphanSlots` already pruned as a phantom, where the same claim spelled\n * `speakerSlot` would have been dropped — the invented-narrator defect, in the\n * one spelling the sweep cannot see. LATENT today, since nothing in this\n * repo emits `speaker`; the day the analyzer does, that sweep is what has to\n * grow, not this field.\n */\n speaker: z.string().optional(),\n})\nexport type AudioLayer = z.infer<typeof audioLayerSchema>\n\nconst windowSceneBase = z.object({\n startSec: z.number().min(0),\n endSec: z.number().min(0),\n label: z.string().min(1),\n shotType: z.string().min(1),\n camera: z.string(),\n /** Camera VIEWPOINT. Absent ⇒ eye-level. Keeps `camera` to pure MOVEMENT and\n * frees `shotType` to state the SIZE even on an over-the-shoulder or POV. */\n angle: z.enum(VIDEO_ANALYSIS_SHOT_ANGLES).optional(),\n /** Time manipulation. Absent ⇒ normal speed. */\n speed: z.enum(VIDEO_ANALYSIS_SPEED_EFFECTS).optional(),\n /** CHRONICLE TIME (2026-08-17) — see the consts' docstrings. Both optional:\n * absent on every pre-2.6.0 analysis, and legitimately absent when the\n * analyser cannot read the clock. Enum + optional keeps the window decode\n * grammar congruence-safe (no ints, no maxItems). */\n timeOfDay: z.enum(VIDEO_ANALYSIS_TIMES_OF_DAY).optional(),\n storyJump: z.enum(VIDEO_ANALYSIS_STORY_JUMPS).optional(),\n visual: z.string().min(1),\n /**\n * Text burned into the PICTURE of this shot — titles, captions, lower-thirds,\n * subtitles — verbatim, in its original script. Absent when the frame carries\n * none.\n *\n * Doctrine already asks for on-screen text inside `visual` prose, but a\n * recreation needs to know discretely whether to RENDER text at all, and\n * `translateOnScreenTextToEnglish` had no structured field to land in. It is\n * also the signal the auto-cast frame judge reads: picture text belonging to an\n * earlier scene's speech means the shot is replayed footage under a voice-over.\n */\n onScreenText: z.string().optional(),\n /** What the on-screen text IS. Meaningful only when `onScreenText` is non-empty. */\n onScreenTextKind: z.enum(VIDEO_ANALYSIS_TEXT_KINDS).optional(),\n /** Effects on this shot's PICTURE. Absent ⇒ a clean image. */\n effects: z.array(z.enum(VIDEO_ANALYSIS_VISUAL_EFFECTS)).optional(),\n transitionOut: z.enum(VIDEO_ANALYSIS_TRANSITIONS).optional(),\n // Round 4 (2026-08-30, recast shot craft rev 1.5 Appendix F.8): the edit into\n // the next scene in the analyser's OWN WORDS — a few words of what it saw\n // (\"fast blurred pan left\", \"fade to black\", \"zoom-blur warp into the tunnel\")\n // — or absent when the take continues through the change or no edit is seen\n // (nothing asserted: the video model decides from story and refs). The closed\n // `transitionOut` vocabulary above is LEGACY from here on: kept so stored\n // blueprints still parse, never emitted again. Readers take\n // `transition ?? transitionOut`.\n transition: z.string().trim().min(1).max(120).optional(),\n // Array of concurrent layers (music + speech + sfx together); [] = silence.\n audio: z.array(audioLayerSchema),\n /** slotId → variationId for slots wearing a NON-default look in this scene\n * (only slots referenced in the scene; absent key ⇒ the default look).\n * Rides windowSceneBase so BOTH the window layer and analyzedSceneSchema\n * inherit it — the out-of-band binding channel (no in-text markers, D6). */\n slotVariations: z.record(z.string(), z.string()).optional(),\n})\n// .strip() (default) drops model-emitted oversized/slotRefs — validator-computed only.\nconst windowSceneSchema = windowSceneBase.refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type WindowScene = z.infer<typeof windowSceneSchema>\n\n/** What the MODEL emits per window (strict-JSON footer schema). scenes has NO min. */\nexport const windowAnalysisSchema = z.object({\n language: z.string().optional(),\n /** The clip-level look as read from THIS window. Merge folds the windows\n * field-by-field (first non-empty wins), like `language`. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(windowSceneSchema),\n})\nexport type WindowAnalysis = z.infer<typeof windowAnalysisSchema>\n\nexport const analyzedSceneSchema = windowSceneBase.extend({\n sceneNumber: z.number().int().min(1),\n visualResolved: z.string().min(1),\n oversized: z.boolean().optional(),\n slotRefs: z.array(z.string()),\n}).refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type AnalyzedScene = z.infer<typeof analyzedSceneSchema>\n\nexport const videoAnalysisResultSchema = z.object({\n meta: z.object({\n durationSec: z.number().positive(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n aspectRatio: z.string(),\n title: z.string().optional(),\n language: z.string().optional(),\n }),\n /** Clip-level look, merged across windows. Deliberately a sibling of `meta`\n * rather than a member: `meta` is probed fact (ffprobe dimensions, probed\n * duration), while this is the model's reading of the photography. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(analyzedSceneSchema).min(1),\n /** CAST VARIATIONS (§4 cap handling): looks the analyzer's merge FOLDED into\n * the default at VIDEO_ANALYSIS_MAX_VARIATIONS — recorded, never silent. In\n * the wire schema so strip-mode consumers (the recast client's validated\n * blueprint view) keep it: the §6 \"folded into default look\" note is the\n * user's only pre-pay defense against a wrong split. */\n variationFolds: z.array(z.object({\n slotId: z.string(),\n variationId: z.string(),\n label: z.string(),\n })).optional(),\n /**\n * Analyzer diagnostics for THIS result — things the analysis noticed about\n * itself that a reader should know before spending on regeneration.\n *\n * Added because there was previously no channel for them at all: the merge\n * layer has always produced a warnings list and the auto-cast pass has always\n * had findings, and every one of them died in a `console.warn` inside a worker\n * the user cannot see. So a run could quietly drop a duplicated line, fold a\n * cast look, or conclude a character is not the person their own description\n * names, and the result looked indistinguishable from a clean one.\n *\n * Prose, not codes, and deliberately so — these are read by a human deciding\n * whether to re-run, not branched on. Absent when there is nothing to report.\n */\n warnings: z.array(z.string()).optional(),\n})\nexport type VideoAnalysisResult = z.infer<typeof videoAnalysisResultSchema>\n\nexport function deriveSlotRefs(visual: string): string[] {\n const out: string[] = []\n for (const m of visual.matchAll(SLOT_TOKEN_RE)) if (!out.includes(m[1])) out.push(m[1])\n return out\n}\n\nexport function rewriteSlotTokens(visual: string, renames: Record<string, string>): string {\n return visual.replace(SLOT_TOKEN_RE, (whole, id: string) => (renames[id] ? `{slot:${renames[id]}}` : whole))\n}\n\n/** Unresolved tokens unwrap to their literal id text — never deleted (spec invariant). */\nexport function unwrapUnresolvedTokens(text: string, validIds: Set<string>): { text: string; unresolved: string[] } {\n const unresolved: string[] = []\n const out = text.replace(SLOT_TOKEN_RE, (whole, id: string) => {\n if (validIds.has(id)) return whole\n if (!unresolved.includes(id)) unresolved.push(id)\n return id\n })\n return { text: out, unresolved }\n}\n\n/**\n * Rewrite a scene's `slotVariations` after cross-window slot/variation\n * unification: slot keys map through `slotRenames`, then each variation value\n * maps through `variationRenames[<new slotId>]`. Absent renames pass through.\n */\nexport function rewriteSceneBindings(\n sv: Record<string, string> | undefined,\n slotRenames: Record<string, string>,\n variationRenames?: Record<string, Record<string, string>>,\n): Record<string, string> | undefined {\n if (!sv) return undefined\n const out: Record<string, string> = {}\n for (const [slotId, variationId] of Object.entries(sv)) {\n const newSlot = slotRenames[slotId] ?? slotId\n out[newSlot] = variationRenames?.[newSlot]?.[variationId] ?? variationId\n }\n return out\n}\n\n/**\n * Drop bindings whose (slotId, variationId) no longer exists after a merge —\n * the unwrap-rule mirror: never persist a dangling binding, and report what\n * was dropped so the caller can warn. `\"default\"` is always valid for a known\n * slot. `kept` is undefined when nothing survives (no `{}` materialization).\n */\nexport function dropUnknownBindings(\n sv: Record<string, string> | undefined,\n validBySlot: Map<string, Set<string>>,\n): { kept?: Record<string, string>; dropped: Array<{ slotId: string; variationId: string }> } {\n if (!sv) return { dropped: [] }\n const kept: Record<string, string> = {}\n const dropped: Array<{ slotId: string; variationId: string }> = []\n for (const [slotId, variationId] of Object.entries(sv)) {\n const valid = validBySlot.get(slotId)\n if (valid && (variationId === VIDEO_ANALYSIS_DEFAULT_VARIATION || valid.has(variationId))) kept[slotId] = variationId\n else dropped.push({ slotId, variationId })\n }\n return { kept: Object.keys(kept).length > 0 ? kept : undefined, dropped }\n}\n\n/**\n * Rewrite speech attribution after cross-window slot unification — the\n * `rewriteSceneBindings` counterpart for the `audio` channel. Slot unification\n * renames a loser id to its survivor and rewrites `{slot:…}` tokens and\n * variation bindings; an un-rewritten `speakerSlot` would be left pointing at an\n * id that no longer exists. Copy-on-write: returns the input array untouched\n * when no layer names a renamed slot.\n */\nexport function rewriteSpeakerSlots(audio: AudioLayer[], slotRenames: Record<string, string>): AudioLayer[] {\n if (!audio.some((a) => a.speakerSlot !== undefined && slotRenames[a.speakerSlot])) return audio\n return audio.map((a) => {\n const to = a.speakerSlot !== undefined ? slotRenames[a.speakerSlot] : undefined\n return to ? { ...a, speakerSlot: to } : a\n })\n}\n\n/**\n * Strip attribution that no scene can honour — the `dropUnknownBindings` mirror\n * for the `audio` channel. Two cases, both model sloppiness rather than errors\n * worth failing a roll over:\n * - a `speakerSlot` on any non-`speech` layer (nobody is speaking)\n * - a `speakerSlot` naming a slot that is not in the final list\n *\n * MUST run AFTER the orphan-slot sweep, and attribution must NEVER count as a\n * slot reference for that sweep: a slot reachable only as a speaker is a voice\n * with no body — precisely the invented-narrator entity doctrine §5 forbids. The\n * two passes compose to remove both the phantom slot and the dangling\n * attribution pointing at it.\n */\nexport function dropUnknownSpeakers(\n audio: AudioLayer[],\n validSlotIds: Set<string>,\n): { audio: AudioLayer[]; dropped: string[] } {\n const dropped: string[] = []\n const out = audio.map((a) => {\n if (a.speakerSlot === undefined) return a\n if (a.mode === \"speech\" && validSlotIds.has(a.speakerSlot)) return a\n dropped.push(a.speakerSlot)\n const { speakerSlot: _drop, ...rest } = a\n return rest\n })\n return { audio: dropped.length > 0 ? out : audio, dropped }\n}\n\n/**\n * Fold each window's reading of the clip look into one, FIELD BY FIELD: the first\n * window that had something to say about a field wins it.\n *\n * Per-field rather than first-window-wins-everything because the windows see\n * different footage — an opening window may read the grade confidently while only\n * a later one contains the shot that reveals the format. Mirrors how `language` is\n * resolved across windows rather than taken from window 0.\n *\n * Returns undefined when no window said anything, so an analysis with nothing to\n * report omits the field rather than shipping an empty object.\n */\nexport function mergeClipLook(looks: ReadonlyArray<ClipLook | undefined>): ClipLook | undefined {\n const out: Record<string, string> = {}\n for (const look of looks) {\n for (const [k, v] of Object.entries(look ?? {})) {\n if (typeof v === \"string\" && v.trim() && !out[k]) out[k] = v.trim()\n }\n }\n return Object.keys(out).length > 0 ? (out as ClipLook) : undefined\n}\n\n/** Substitute {slot:x}: castMap binding wins, else the slot's description, else literal id. */\nexport function renderAnalyzedScene(scene: { visual: string }, slots: EntitySlot[], castMap?: Record<string, string>): string {\n const byId = new Map(slots.map((s) => [s.slotId, s]))\n return scene.visual.replace(SLOT_TOKEN_RE, (_whole, id: string) => castMap?.[id] ?? byId.get(id)?.description ?? id)\n}\n\n/**\n * Float slack for the oversize comparison.\n *\n * Scene boundaries arrive as decimal seconds and the duration is derived by\n * SUBTRACTING two of them, which does not land on the cap exactly: a real job\n * produced a 12.67 → 20.67 scene whose computed length is 8.000000000000002,\n * so a scene sitting precisely ON the 8s cap was flagged oversized and carried\n * a `oversized: true` defect marker downstream for no reason.\n *\n * A microsecond is orders of magnitude below any boundary precision the\n * analyzer can actually resolve (windows land on ~0.01s at best), so this can\n * never mask a genuinely oversized scene — the smallest real overshoot is\n * still ~10000x larger than the tolerance.\n */\nconst OVERSIZE_TOLERANCE_SEC = 1e-6\n\nexport function isOversizedScene(startSec: number, endSec: number): boolean {\n return endSec - startSec > VIDEO_ANALYSIS_MAX_SCENE_SEC + OVERSIZE_TOLERANCE_SEC\n}\n\nconst STANDARD_RATIOS: Array<[string, number]> = [\n [\"16:9\", 16 / 9], [\"9:16\", 9 / 16], [\"1:1\", 1], [\"4:3\", 4 / 3], [\"3:4\", 3 / 4], [\"21:9\", 21 / 9],\n]\nexport function aspectRatioFromDims(w: number, h: number): string {\n const r = w / h\n for (const [label, v] of STANDARD_RATIOS) if (Math.abs(r - v) / v < 0.03) return label\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b))\n const g = gcd(Math.round(w), Math.round(h))\n return `${Math.round(w) / g}:${Math.round(h) / g}`\n}\n\n/** Sung-vocal evidence in a music layer's gen-ready description. Word-bounded\n * and deliberately WITHOUT bare \"song\"/\"music\" (an instrumental bed is\n * routinely described as a \"pop song\"). Quoted text of some length inside a\n * music layer counts too — analysers quote lyrics. */\nconst MUSIC_VOCAL_RE = /\\b(?:lyrics?|sung|sings?|singing|vocals?|chorus|verse|rap(?:ping|ped)?|a cappella)\\b/i\nconst MUSIC_VOCAL_QUOTE_RE = /[\"\\u201c][^\"\\u201d]{6,}[\"\\u201d]/\n/** Negated-vocal phrasing — a layer matching this contributes NO vocal\n * evidence (it does not veto other layers). */\nconst MUSIC_NO_VOCAL_RE = /\\b(?:no|without|non)[- ](?:vocals?|lyrics?|singing)\\b|\\binstrumental\\b|\\bwordless\\b/i\n\n/**\n * MUSIC-VIDEO INFERENCE (2026-08-17): is this clip a music video — one whose\n * soundtrack IS the content, to be taken as-is with no stem separation?\n *\n * Lives in SHARED because two sides must agree BYTE-FOR-BYTE on the answer:\n * the recast route derives `music.mode` from it server-side, and the client\n * both prices the original-audio prep and GUARDS on the server's derived mode\n * at generate time — two hand-written copies of this heuristic would drift\n * into that guard firing on honest runs. Deterministic, throw-proof on any\n * malformed analysis (absent fields ⇒ false).\n *\n * The rule is conservative toward FALSE (a false positive keeps unwanted\n * dialogue in the render; a false negative merely runs the separation, which\n * was yesterday's default): at least 4 scenes, at least 80% of scenes carry a\n * music layer, and at least one music layer carries sung-vocal evidence that\n * is not negated (\"instrumental\", \"no vocals\").\n *\n * An EXPLICIT analyze-time flag always wins — callers use\n * `flag === true || inferMusicVideo(analysis)` and never let a cached false\n * suppress the inference (the flag can only ever be set true; false means\n * \"unset\", not \"denied\").\n */\nexport function inferMusicVideo(analysis: {\n scenes?: ReadonlyArray<{ audio?: ReadonlyArray<{ mode?: string; content?: string }> }>\n} | undefined | null): boolean {\n const scenes = analysis?.scenes ?? []\n if (scenes.length < 4) return false\n const musicLayers = (sc: (typeof scenes)[number]) => (sc.audio ?? []).filter((a) => a?.mode === \"music\")\n const withMusic = scenes.filter((sc) => musicLayers(sc).length > 0).length\n if (withMusic / scenes.length < 0.8) return false\n return scenes.some((sc) =>\n musicLayers(sc).some((a) => {\n const content = typeof a.content === \"string\" ? a.content : \"\"\n if (MUSIC_NO_VOCAL_RE.test(content)) return false\n return MUSIC_VOCAL_RE.test(content) || MUSIC_VOCAL_QUOTE_RE.test(content)\n }),\n )\n}\n\n// ---------------------------------------------------------------------------\n// The analysis as a BRIEF — the compact projection an LLM is handed\n// ---------------------------------------------------------------------------\n\n/** Top-level keys the analyzer derives AFTER the model's pass (merge\n * diagnostics, folded cast looks). A reader drafting FROM the analysis — a\n * production plan, a script — needs none of them. */\nconst DERIVED_ANALYSIS_TOP_KEYS: ReadonlySet<string> = new Set([\"warnings\", \"variationFolds\"])\n\n/** Per-scene keys the validator computes from `visual` and the slot list. */\nconst DERIVED_ANALYSIS_SCENE_KEYS: ReadonlySet<string> = new Set([\"visualResolved\", \"slotRefs\", \"oversized\"])\n\nconst asRecord = (v: unknown): Record<string, unknown> | null =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null\n\n/**\n * The analysis with its server-derived fields removed — the form an LLM is\n * handed when the analysis IS the brief (Nodaro Studio's Director and its\n * job-id loader). Drops `warnings` and `variationFolds` at the top and\n * `visualResolved`, `slotRefs`, `oversized` on every scene; keeps\n * `refImageUrl` (a downstream cast image) and everything else. Never mutates;\n * a non-object input comes back as-is.\n *\n * ONE strip list, shared by the worker that composes the brief server-side\n * (`llm-structured` jobs with a `videoUrl`) and the client that loads a\n * finished analysis into a textarea, so the two can never drift.\n */\nexport function stripDerivedAnalysisFields(json: unknown): unknown {\n const doc = asRecord(json)\n if (!doc) return json\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(doc)) {\n if (DERIVED_ANALYSIS_TOP_KEYS.has(key)) continue\n out[key] =\n key === \"scenes\" && Array.isArray(value)\n ? value.map((scene) => {\n const s = asRecord(scene)\n if (!s) return scene\n return Object.fromEntries(Object.entries(s).filter(([k]) => !DERIVED_ANALYSIS_SCENE_KEYS.has(k)))\n })\n : value\n }\n return out\n}\n","/**\n * Real output canvases per (video model, resolution, aspect ratio).\n *\n * Every entry is a pixel size read off a finished render with ffprobe — the\n * geometry a model hands back, never a rate or a price. None of it is\n * arithmetic either, because the providers do not follow arithmetic:\n *\n * - minimax-h3 at 768P returns 768x1344 (0.5714) for a 9:16 request,\n * - seedance-2 at 480p 16:9 returns 864x496 (1.742) while seedance-2-5\n * returns 854x480 (1.778) for the same request,\n * - grok returns 736x400 (1.84), seedance 1.0 at 1080p 1:1 returns 1440x1440.\n *\n * A formula would get all four wrong, which is why `resolveOutputCanvas`\n * answers `undefined` for anything not measured: callers must then leave the\n * frame alone rather than invent geometry (see `computeFrameFitPlan`).\n *\n * HOW TO EXTEND: run `node tools/harvest-output-canvas.mjs` (it pages the admin\n * jobs API, groups completed video jobs by provider/resolution/aspect and probes\n * real outputs) and paste new rows here. Take rows from REFERENCE or\n * TEXT-TO-VIDEO jobs only: in frame mode the adaptive models (the seedance and\n * wan families) size the output from the INPUT image, so those rows describe the\n * input that was sent, not the canvas the model would choose on its own.\n *\n * Seeded 2026-09-16 from 3000 completed production jobs.\n */\n\n/** `[width, height]` in pixels. */\nexport type VideoOutputCanvas = readonly [number, number]\n\n/** provider → resolution (lower-cased) → aspect token → canvas. */\nexport const VIDEO_OUTPUT_CANVAS: Readonly<\n Record<string, Readonly<Record<string, Readonly<Record<string, VideoOutputCanvas>>>>>\n> = {\n \"seedance-2-5\": {\n \"480p\": { \"16:9\": [854, 480], \"9:16\": [480, 854] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280], \"1:1\": [960, 960] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n // The 2.0 family is NOT the same as 2.5 at 480p — 864x496 vs 854x480.\n \"seedance-2\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-fast\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-mini\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"gemini-omni-video\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"gemini-omni-flash\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"veo3.1\": {\n \"720p\": { \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"wan-3\": {\n \"480p\": { \"16:9\": [832, 480] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"wan-3-prime\": {\n \"720p\": { \"16:9\": [1280, 720] },\n },\n // 768P's \"9:16\" is 0.5714, not 0.5625 — the single clearest reason this table\n // exists.\n \"minimax-h3\": {\n \"768p\": { \"9:16\": [768, 1344] },\n \"2k\": { \"16:9\": [2560, 1440], \"9:16\": [1440, 2560] },\n },\n}\n\n/**\n * The canvas a model renders for this request, or `undefined` when we have never\n * measured that combination. `undefined` means \"leave the frame alone\".\n *\n * Resolution matching is case-insensitive (`768P`, `2K`, `720p` all appear in\n * the wild). An aspect of `adaptive` / `Auto` has no canvas of its own — the\n * caller resolves it to a concrete ratio first (`resolveFrameFitAspect`).\n */\nexport function resolveOutputCanvas(\n provider: string | undefined,\n resolution: string | undefined,\n aspect: string | undefined,\n): VideoOutputCanvas | undefined {\n if (!provider || !resolution || !aspect) return undefined\n return VIDEO_OUTPUT_CANVAS[provider]?.[resolution.toLowerCase()]?.[aspect]\n}\n\n/** Every measured combination, for tests and for the harvest script's diff. */\nexport function measuredCanvasCombinations(): Array<{\n provider: string\n resolution: string\n aspect: string\n canvas: VideoOutputCanvas\n}> {\n const out: Array<{ provider: string; resolution: string; aspect: string; canvas: VideoOutputCanvas }> = []\n for (const [provider, byResolution] of Object.entries(VIDEO_OUTPUT_CANVAS)) {\n for (const [resolution, byAspect] of Object.entries(byResolution)) {\n for (const [aspect, canvas] of Object.entries(byAspect)) {\n out.push({ provider, resolution, aspect, canvas })\n }\n }\n }\n return out\n}\n","/**\n * START/END FRAME FIT — the pure geometry half.\n *\n * WHY THIS EXISTS (measured on ~40 production renders, 2026-09-16):\n * a start frame whose pixel size is not the model's own output canvas gets\n * reshaped by the provider, and Seedance 2.5 does it VISIBLY — frame 0 is the\n * user's image verbatim, then from frame 1 the generated frames are rescaled\n * ~2% on ONE axis (x1.000 y1.02). Five of ten runs with a 940x1672 image\n * snapped; three of three with the same image resized to 720x1280 did not.\n *\n * So: reshape the frame ourselves, to the size the model was going to render\n * anyway. The canvas comes from measurement (`video-output-canvas.ts`), never\n * from arithmetic, and when a combination has never been measured the fit\n * DEGRADES rather than guesses.\n *\n * This module is pure — no I/O, no sharp, no network. `prepareVideoFrames` in\n * the backend does the pixels and the upload.\n */\nimport { getModel } from \"./model-catalog.js\"\nimport { resolveOutputCanvas, type VideoOutputCanvas } from \"./video-output-canvas.js\"\n\n/** How much of the frame we are allowed to reshape. */\nexport const FRAME_FITS = [\"original\", \"ratio\", \"resolution\"] as const\nexport type FrameFit = (typeof FRAME_FITS)[number]\n\n/** `resolution` — the measured canvas — is the default everywhere. */\nexport const DEFAULT_FRAME_FIT: FrameFit = \"resolution\"\n\n/** How the frame is handed to the model. */\nexport const FRAME_DELIVERIES = [\"auto\", \"frame\", \"reference\"] as const\nexport type FrameDelivery = (typeof FRAME_DELIVERIES)[number]\n\nexport const DEFAULT_FRAME_DELIVERY: FrameDelivery = \"auto\"\n\n/**\n * Stretching an image to a ratio it is nowhere near would squash the subject,\n * so past this gap the frame is centre-cropped to the target ratio FIRST and\n * only then resized. 5% covers every \"1K image into a 720p canvas\" case we\n * measured (940x1672 into 9:16 is a 0.05% gap) while refusing to squash a\n * square photo into 9:16 (a 78% gap).\n */\nexport const FRAME_FIT_STRETCH_TOLERANCE = 0.05\n\n/**\n * Models whose frame mode is measurably worse than reference delivery.\n *\n * The Seedance 2.0 family crop-zooms the frame 2% and drifts 11-26% darker\n * within six frames in frame mode; delivered as a reference with the opening-\n * frame sentence, the same models hold a flat look from frame 0 and keep the\n * image's true geometry. Every OTHER model measured (Seedance 2.5, Gemini Omni\n * video + flash, Veo 3.1, Wan 3.0, Minimax H3) reproduces the opening frame\n * better in frame mode, so the default stays `frame` for anything absent here.\n */\nexport const FRAME_DELIVERY_BY_PROVIDER: Readonly<Record<string, Exclude<FrameDelivery, \"auto\">>> = {\n \"seedance-2\": \"reference\",\n \"seedance-2-fast\": \"reference\",\n \"seedance-2-mini\": \"reference\",\n}\n\n/** Aspect tokens that name no concrete shape — the model picks. */\nconst OPEN_ASPECT_TOKENS = new Set([\"adaptive\", \"auto\"])\n\n/** `\"16:9\"` → 1.777…; anything unparseable → `undefined`. */\nexport function parseAspectToken(token: string | undefined): number | undefined {\n if (!token) return undefined\n const m = /^(\\d+(?:\\.\\d+)?)\\s*[:x/]\\s*(\\d+(?:\\.\\d+)?)$/.exec(token.trim())\n if (!m) return undefined\n const w = Number(m[1]); const h = Number(m[2])\n if (!(w > 0) || !(h > 0)) return undefined\n return w / h\n}\n\n/**\n * The aspect the fit should target.\n *\n * An explicit ratio is used as-is. `adaptive` / `Auto` (and an absent value,\n * which the seedance family sends as adaptive whenever a frame is present) has\n * no shape of its own: the provider will follow the IMAGE, so we snap the\n * image's own ratio to the nearest one the model lists and target that. A model\n * with no declared ratio list and an open token gives `undefined` — no fit.\n */\nexport function resolveFrameFitAspect(args: {\n provider: string | undefined\n requestedAspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n}): string | undefined {\n const requested = args.requestedAspect?.trim()\n if (requested && !OPEN_ASPECT_TOKENS.has(requested.toLowerCase())) return requested\n const ratios = args.provider ? getModel(args.provider)?.aspectRatios : undefined\n if (!ratios?.length || !(args.sourceWidth > 0) || !(args.sourceHeight > 0)) return undefined\n const source = args.sourceWidth / args.sourceHeight\n let best: { token: string; gap: number } | undefined\n for (const token of ratios) {\n const value = parseAspectToken(token)\n if (value === undefined) continue // skips \"adaptive\"/\"Auto\" members\n const gap = Math.abs(Math.log(value / source))\n if (!best || gap < best.gap) best = { token, gap }\n }\n return best?.token\n}\n\n/** What `prepareVideoFrames` should do to one frame. `null` = nothing. */\nexport interface FrameFitPlan {\n /** Final pixel size to produce. */\n readonly width: number\n readonly height: number\n /** Centre-crop applied BEFORE the resize (only past the stretch tolerance). */\n readonly crop?: { readonly left: number; readonly top: number; readonly width: number; readonly height: number }\n /** Why the plan exists — carried into logs and job output for traceability. */\n readonly reason: \"resolution\" | \"ratio\"\n}\n\n/** Round to an even number ≥ 2 — odd dimensions break yuv420p encoders. */\nfunction even(value: number): number {\n return Math.max(2, Math.round(value / 2) * 2)\n}\n\n/**\n * The smallest change that makes `width x height` exactly `aspect`: keep the\n * longer side, move the shorter one. Rounding to even can leave a sub-pixel\n * residue, which is why the caller compares ratios with a tolerance rather than\n * for equality.\n */\nexport function minimalRatioDimensions(width: number, height: number, aspect: number): { width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n // too wide → bring the height up (keep the long side, the width)\n return { width: even(width), height: even(width / aspect) }\n }\n return { width: even(height * aspect), height: even(height) }\n}\n\n/**\n * The centre-crop that turns `width x height` into exactly `aspect`, dropping\n * the overhang on the long axis.\n */\nexport function centreCropToAspect(width: number, height: number, aspect: number): { left: number; top: number; width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n const w = even(height * aspect)\n return { left: Math.max(0, Math.round((width - w) / 2)), top: 0, width: Math.min(width, w), height }\n }\n const h = even(width / aspect)\n return { left: 0, top: Math.max(0, Math.round((height - h) / 2)), width, height: Math.min(height, h) }\n}\n\n/**\n * Turn a request into a concrete plan for ONE frame, or `null` when the frame\n * should be sent untouched.\n *\n * Degradation ladder — a missing measurement must never invent geometry:\n * `resolution` with no measured canvas → behaves as `ratio`\n * `ratio` with no resolvable aspect → no fit\n * any fit whose target equals the source (within a pixel) → no fit\n */\nexport function computeFrameFitPlan(args: {\n fit: FrameFit\n provider: string | undefined\n resolution: string | undefined\n /** The aspect as the request carries it: a ratio, `adaptive`/`Auto`, or absent. */\n aspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n /** Overrides the measured table (tests, and a caller that already looked up). */\n canvas?: VideoOutputCanvas\n tolerance?: number\n}): FrameFitPlan | null {\n const { fit, sourceWidth, sourceHeight } = args\n if (fit === \"original\") return null\n if (!(sourceWidth > 0) || !(sourceHeight > 0)) return null\n\n const aspectToken = resolveFrameFitAspect({\n provider: args.provider,\n requestedAspect: args.aspect,\n sourceWidth,\n sourceHeight,\n })\n\n const canvas = fit === \"resolution\"\n ? args.canvas ?? resolveOutputCanvas(args.provider, args.resolution, aspectToken)\n : undefined\n\n const targetAspect = canvas ? canvas[0] / canvas[1] : parseAspectToken(aspectToken)\n if (targetAspect === undefined || !(targetAspect > 0)) return null\n\n const sourceAspect = sourceWidth / sourceHeight\n const gap = Math.abs(sourceAspect - targetAspect) / targetAspect\n const tolerance = args.tolerance ?? FRAME_FIT_STRETCH_TOLERANCE\n const crop = gap > tolerance ? centreCropToAspect(sourceWidth, sourceHeight, targetAspect) : undefined\n\n const target = canvas\n ? { width: canvas[0], height: canvas[1] }\n : minimalRatioDimensions(\n crop ? crop.width : sourceWidth,\n crop ? crop.height : sourceHeight,\n targetAspect,\n )\n\n const unchanged = target.width === sourceWidth && target.height === sourceHeight && !crop\n if (unchanged) return null\n\n return {\n width: target.width,\n height: target.height,\n ...(crop ? { crop } : {}),\n reason: canvas ? \"resolution\" : \"ratio\",\n }\n}\n\n/**\n * Frame or reference? `auto` reads the per-provider default measured above.\n * Reference delivery is only possible on models that accept reference images —\n * on the others `reference` collapses back to `frame` rather than dropping the\n * frame on the floor.\n */\nexport function resolveFrameDelivery(args: {\n provider: string | undefined\n requested: FrameDelivery | undefined\n supportsReferenceImages: boolean\n}): Exclude<FrameDelivery, \"auto\"> {\n const requested = args.requested ?? DEFAULT_FRAME_DELIVERY\n const wanted = requested === \"auto\"\n ? (args.provider ? FRAME_DELIVERY_BY_PROVIDER[args.provider] ?? \"frame\" : \"frame\")\n : requested\n if (wanted === \"reference\" && !args.supportsReferenceImages) return \"frame\"\n return wanted\n}\n"]}
@@ -700,5 +700,5 @@ exports.videoFaceMeshPartsOfLayers = videoFaceMeshPartsOfLayers;
700
700
  exports.videoMaskBilledSeconds = videoMaskBilledSeconds;
701
701
  exports.videoMaskCreditId = videoMaskCreditId;
702
702
  exports.videoMaskCreditIds = videoMaskCreditIds;
703
- //# sourceMappingURL=chunk-KYMHFVAZ.cjs.map
704
- //# sourceMappingURL=chunk-KYMHFVAZ.cjs.map
703
+ //# sourceMappingURL=chunk-Y4GCJJPF.cjs.map
704
+ //# sourceMappingURL=chunk-Y4GCJJPF.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/freecut-protocol.ts","../src/inpaint-region.ts","../src/lottie-slots.ts","../src/lottie-overlay-catalog.ts","../src/audio-fx-presets.ts","../src/video-mask.ts","../src/video-face-mesh.ts","../src/generate-mask.ts","../src/mask-composite.ts"],"names":["clamp01","copy","pricedClipSeconds"],"mappings":";;;;;AAMO,IAAM,iBAAA,GAAoB;AAI1B,IAAM,oBAAA,GAAuB;AAC7B,IAAM,mBAAA,GAAsB;AAC5B,IAAM,oBAAA,GAAuB;AAG7B,IAAM,aAAA,GAAgB;AACtB,IAAM,uBAAA,GAA0B;AAChC,IAAM,uBAAA,GAA0B;AAChC,IAAM,sBAAA,GAAyB;;;ACPtC,SAAS,KAAK,MAAA,EAAwC;AACpD,EAAA,IAAI,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO,KAAA;AAC3B,EAAA,IAAI,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO,MAAA;AAC3B,EAAA,OAAO,KAAA;AACT;AAEA,IAAM,OAAO,EAAE,GAAA,EAAK,SAAS,GAAA,EAAK,QAAA,EAAU,MAAM,OAAA,EAAQ;AAC1D,IAAM,OAAO,EAAE,GAAA,EAAK,QA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AS,wBAAwB,IAAA,EAA0F;AAChI,EAAA,OAAO,2BAAA,CAA4B,mBAAA,CAAoB,IAAI,CAAC,IAAI,OAAA,GAAU,kBAAA;AAC5E;AAQO,SAAS,kCAAkC,CAAA,EAAkF;AAClI,EAAA,IAAI,2BAAA,CAA4B,CAAA,CAAE,IAAI,CAAA,SAAU,CAAA,CAAE,WAAA;AAClD,EAAA,OAAO,YAAA;AACT","file":"chunk-Y4GCJJPF.cjs","sourcesContent":["// Single source of truth for the Nodaro <-> FreeCut iframe postMessage protocol.\n// Imported by app's freecut-editor-modal and Studio's ported modal so the wire\n// format cannot drift. The fork (Nodaro-ai/freecut-fork) mirrors these strings in\n// src/features/embedded/services/embedded-message-handler.ts + use-send-back.ts.\n\n// Nodaro (parent) -> FreeCut (iframe)\nexport const NODARO_LOAD_VIDEO = \"NODARO_LOAD_VIDEO\"\n// Multi-clip analog of NODARO_LOAD_VIDEO: lay N ordered urls on the timeline as\n// sequential clips (FreeCut fetches them itself). Used by Studio's production\n// \"Edit in FreeCut\" to assemble the whole cut.\nexport const NODARO_LOAD_TIMELINE = \"NODARO_LOAD_TIMELINE\"\nexport const NODARO_IMPORT_FILES = \"NODARO_IMPORT_FILES\"\nexport const NODARO_RESET_PROJECT = \"NODARO_RESET_PROJECT\"\n\n// FreeCut (iframe) -> Nodaro (parent)\nexport const FREECUT_READY = \"FREECUT_READY\"\nexport const FREECUT_EXPORT_COMPLETE = \"FREECUT_EXPORT_COMPLETE\"\nexport const FREECUT_EXPORT_PROGRESS = \"FREECUT_EXPORT_PROGRESS\" // reserved; fork emits it, v1 parents ignore it\nexport const FREECUT_REQUEST_IMPORT = \"FREECUT_REQUEST_IMPORT\"\n\nexport interface FreecutImportFile {\n readonly name: string\n readonly type: string\n readonly size: number\n readonly buffer: ArrayBuffer\n}\n\nexport interface NodaroLoadVideoPayload {\n readonly videoUrl: string\n /** Display/file name for the primary video (\"Shot 1.mp4\") — optional; absent = URL-derived name (fork default). */\n readonly videoName?: string\n readonly videoBuffer?: ArrayBuffer\n readonly projectJson?: unknown\n readonly additionalFiles?: ReadonlyArray<FreecutImportFile>\n /**\n * What the editor's Save & Exit hands back. \"video\": it renders the timeline\n * and answers with FREECUT_EXPORT_COMPLETE (the video and the project JSON),\n * for a parent that keeps an edit as a new video (the workflow editor).\n * Absent or \"project\": it answers with the project JSON alone\n * (FREECUT_SAVE_EXIT), for a parent that renders the cut itself (Studio).\n */\n readonly saveExit?: \"video\" | \"project\"\n}\n\nexport interface NodaroLoadTimelinePayload {\n // Ordered clip urls; FreeCut fetches each and lays them end-to-end on the timeline.\n readonly clips: ReadonlyArray<string>\n}\n\nexport interface FreecutExportCompletePayload {\n readonly videoBuffer: ArrayBuffer\n readonly projectJson?: unknown\n}\n\nexport interface FreecutExportProgressPayload {\n readonly percent: number\n}\n\nexport interface FreecutRequestImportPayload {\n readonly accept?: string\n readonly multiple?: boolean\n}\n","export interface PixelBox { x: number; y: number; width: number; height: number }\n\nexport interface MaskRegionDescriptor {\n /** bbox normalized to 0..1 against the image, clamped so x+width ≤ 1 and y+height ≤ 1. */\n normBbox: PixelBox\n /** Natural-language location, e.g. \"the upper-left region\" / \"the center\". */\n location: string\n /** Prompt fragment to PREPEND to the user instruction. */\n fragment: string\n}\n\nfunction band(center: number): \"low\" | \"mid\" | \"high\" {\n if (center < 1 / 3) return \"low\"\n if (center > 2 / 3) return \"high\"\n return \"mid\"\n}\n\nconst VERT = { low: \"upper\", mid: \"middle\", high: \"lower\" } as const\nconst HORZ = { low: \"left\", mid: \"center\", high: \"right\" } as const\n\n/**\n * Turn a pixel bounding box of the masked (edit) region into a normalized bbox\n * + natural-language location + a prompt fragment. Pure — no IO. This is the\n * Tier-B descriptor injected for strong instruction-following editors, and the\n * exact primitive Phase 2 (named regions) will reuse.\n */\nexport function describeMaskRegion(box: PixelBox, image: { width: number; height: number }): MaskRegionDescriptor {\n const clamp01 = (n: number) => Math.max(0, Math.min(1, n))\n const round2 = (n: number) => Math.round(n * 100) / 100\n const nx = clamp01(box.x / image.width)\n const ny = clamp01(box.y / image.height)\n const normBbox: PixelBox = {\n x: round2(nx),\n y: round2(ny),\n width: round2(Math.max(0, Math.min(1 - nx, box.width / image.width))),\n height: round2(Math.max(0, Math.min(1 - ny, box.height / image.height))),\n }\n\n const cx = (box.x + box.width / 2) / image.width\n const cy = (box.y + box.height / 2) / image.height\n const v = VERT[band(cy)]\n const h = HORZ[band(cx)]\n const location = v === \"middle\" && h === \"center\" ? \"the center\" : `the ${v}-${h} region`\n\n const fragment =\n `Apply the following change ONLY to ${location} of the image ` +\n `(normalized region x=${normBbox.x} y=${normBbox.y} w=${normBbox.width} h=${normBbox.height}), ` +\n `leaving everything else unchanged: `\n\n return { normBbox, location, fragment }\n}\n","/**\n * Lottie slot substitution — single source of truth (design §5).\n *\n * A slotted property is an object containing a `sid` key (canonically exactly\n * `{\"sid\": \"name\"}`; tolerantly also the annotation form `{a, k, sid}`). The\n * slot manifest maps sid → { p: <whatever belongs at the reference position> }.\n * Overrides map sid → raw value (what UI controls write).\n *\n * KEY CONVENTION: a slot's `p` is, by design, EXACTLY what belongs at the\n * reference position — and we substitute it VERBATIM, never auto-wrapping it in\n * an `{a:0,k:...}` envelope. At a property position (a fill color, a shape size)\n * that means `p` is a property object like `{\"a\":0,\"k\":[1,0,0,1]}`. At a RAW\n * position inside a text document — `layers[].t.d.k[0].s.t`, where lottie-web's\n * `buildFinalText` iterates string characters — `p` is a BARE string, e.g.\n * `{ \"nameText\": { \"p\": \"John Smith\" } }` substitutes the string `\"John Smith\"`\n * straight onto `s.t`. (Auto-wrapping there produced `{a:0,k:\"John Smith\"}` and\n * broke text rendering — the defect this contract fixes.)\n *\n * An override is wrapped ONLY when it lands on a property-object default: the\n * `{...p, k: override}` form preserves the default's envelope (animated/static\n * flags). On a raw default (or a missing slot) the override is substituted\n * verbatim too — so a raw text override stays a bare string.\n *\n * Substitution is renderer-agnostic: we replace every sid node ourselves and\n * never rely on lottie-web's version-dependent native slot support.\n */\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isPlainObject(v: unknown): v is JsonRecord {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\n/** True when `p` already looks like a lottie animated-property object. */\nfunction isPropertyObject(v: unknown): v is JsonRecord {\n return isPlainObject(v) && \"k\" in v\n}\n\nfunction resolveSlotNode(\n node: JsonRecord,\n slots: JsonRecord,\n overrides: JsonRecord,\n): unknown {\n const sid = node.sid as string\n const slot = slots[sid]\n const slotP = isPlainObject(slot) ? (slot as JsonRecord).p : undefined\n const override = overrides[sid]\n\n if (override !== undefined) {\n // Wrap into the default's property-object envelope when the default IS one\n // (preserves animated/static flags); otherwise substitute the raw override\n // verbatim — a raw text override must stay a bare string at `s.t`.\n if (isPropertyObject(slotP)) return { ...slotP, k: structuredClone(override) }\n return structuredClone(override)\n }\n if (slotP !== undefined) {\n // `p` is by convention exactly what belongs at the reference position —\n // substitute it verbatim, never auto-wrap (a bare string stays a string).\n return structuredClone(slotP)\n }\n // No slot, no override — leave the node as-is (validator rule #6 should\n // prevent this; belt-and-braces for hand-fed documents).\n return node\n}\n\nfunction walk(value: unknown, slots: JsonRecord, overrides: JsonRecord): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, slots, overrides))\n }\n if (isPlainObject(value)) {\n if (typeof value.sid === \"string\") {\n const resolved = resolveSlotNode(value, slots, overrides)\n // The original node comes back only in the missing-slot case; replacements\n // are leaf property objects and need no further walking.\n if (resolved === value) {\n const copy: JsonRecord = {}\n for (const [k, v] of Object.entries(value)) copy[k] = walk(v, slots, overrides)\n return copy\n }\n return resolved\n }\n const copy: JsonRecord = {}\n for (const [k, v] of Object.entries(value)) copy[k] = walk(v, slots, overrides)\n return copy\n }\n return value\n}\n\n/** Pure: returns a new document; never mutates inputs. */\nexport function applySlots(\n lottie: JsonRecord,\n slots: JsonRecord | undefined,\n overrides: JsonRecord | undefined,\n): JsonRecord {\n return walk(lottie, slots ?? {}, overrides ?? {}) as JsonRecord\n}\n\n// ── Playback normalization ───────────────────────────────────────────────────\n//\n// lottie-web computes a layer's local time as `frame - layer.st` and gates the\n// layer on `local >= ip && local < op`. A layer missing `st` yields NaN, fails\n// the gate, and stays `display:none` forever — the document \"loads\" (DOMLoaded\n// fires) but every frame renders blank (prod incident 2026-06-12: all authored\n// lottie renders came out as empty frames in headless Chrome). `st` and `sr`\n// are spec-optional with defaults, so documents routinely omit them; complete\n// them at the playback boundary so any source — authored plan, baked export,\n// catalog asset, external URL — renders. Mutates `doc` in place and returns it\n// (callers pass freshly fetched or freshly copied documents).\n\nexport function normalizeLottieLayers<T>(doc: T): T {\n if (!isPlainObject(doc)) return doc\n const fix = (layers: unknown): void => {\n if (!Array.isArray(layers)) return\n for (const layer of layers) {\n if (!isPlainObject(layer)) continue\n if (typeof layer.st !== \"number\") layer.st = 0\n if (typeof layer.sr !== \"number\") layer.sr = 1\n }\n }\n fix((doc as JsonRecord).layers)\n const assets = (doc as JsonRecord).assets\n if (Array.isArray(assets)) {\n for (const asset of assets) {\n if (isPlainObject(asset)) fix(asset.layers)\n }\n }\n return doc\n}\n\n// ── Slot control descriptors (Phase 2 — UI mapping) ──────────────────────────\n//\n// A slot manifest entry is `{ p: <whatever belongs at the reference position> }`\n// (Amendment 1). `describeSlotControl` unwraps that envelope to the editable raw\n// value and classifies it into the control kind the config panel should render.\n// `p` is either a property object `{a, k}` (colors, sizes, scalars) whose `k`\n// holds the value, or a bare raw value (text strings live unwrapped at `s.t`).\n\nexport type SlotControlKind = \"color\" | \"text\" | \"number\" | \"point\"\nexport interface SlotControlDescriptor {\n kind: SlotControlKind\n value: unknown\n}\n\n/**\n * Unwraps a slot entry to its editable raw value and classifies it:\n * {p:{a:0,k:[1,0,0,1]}} → { kind:\"color\", value:[1,0,0,1] }\n * {p:\"John\"} → { kind:\"text\", value:\"John\" }\n * {p:{a:0,k:42}} → { kind:\"number\", value:42 }\n * {p:{a:0,k:[10,20]}} → { kind:\"point\", value:[10,20] }\n * Animated property objects (`a:1`) and anything that doesn't map to a known\n * control kind return null (no editable control).\n */\nexport function describeSlotControl(slot: unknown): SlotControlDescriptor | null {\n if (!isPlainObject(slot)) return null\n const p = (slot as JsonRecord).p\n let value: unknown = p\n if (isPropertyObject(p)) {\n if ((p as JsonRecord).a === 1) return null\n value = (p as JsonRecord).k\n }\n if (typeof value === \"string\") return { kind: \"text\", value }\n if (typeof value === \"number\") return { kind: \"number\", value }\n if (\n Array.isArray(value) &&\n value.length === 4 &&\n value.every((n) => typeof n === \"number\" && n >= 0 && n <= 1)\n ) {\n return { kind: \"color\", value }\n }\n if (Array.isArray(value) && value.length === 2 && value.every((n) => typeof n === \"number\")) {\n return { kind: \"point\", value }\n }\n return null\n}\n\nfunction clamp01(n: number): number {\n if (Number.isNaN(n)) return 0\n return n < 0 ? 0 : n > 1 ? 1 : n\n}\n\nfunction toHexByte(component: number): string {\n return Math.round(clamp01(component) * 255)\n .toString(16)\n .padStart(2, \"0\")\n}\n\n/**\n * RGBA array (components 0..1) → hex string. The alpha component is omitted\n * when it is exactly 1 (`[1,0,0,1]` → `\"#ff0000\"`); otherwise an 8-digit hex is\n * emitted (`[0,1,0,0.5]` → `\"#00ff0080\"`). Output is always lowercase.\n */\nexport function rgbaArrayToHex(rgba: number[]): string {\n const [r = 0, g = 0, b = 0, a = 1] = rgba\n const base = `#${toHexByte(r)}${toHexByte(g)}${toHexByte(b)}`\n return a >= 1 ? base : `${base}${toHexByte(a)}`\n}\n\n/**\n * Hex string → RGBA array (components 0..1). Accepts `#rgb`, `#rrggbb`, and\n * `#rrggbbaa`; alpha defaults to 1 when absent. Leading `#` is optional.\n */\nexport function hexToRgbaArray(hex: string): number[] {\n let h = hex.trim().replace(/^#/, \"\")\n if (h.length === 3) {\n h = h\n .split(\"\")\n .map((c) => c + c)\n .join(\"\")\n }\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const a = h.length >= 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1\n return [r, g, b, a]\n}\n\n/** Manifest sids in insertion order (drives the slot-control list ordering). */\nexport function listSlotSids(slots: Record<string, unknown>): string[] {\n return Object.keys(slots ?? {})\n}\n\n// ── Slot → app-field derivation (Phase 3 — single source of truth) ────────────\n//\n// `deriveLottieSlotFields` turns a lottie-graphic plan's slot manifest into\n// ExposableField-shaped descriptors. ONE function feeds three surfaces: the\n// editor's publish picker, the published-app runtime, and the backend MCP\n// schema extractor — so the set of slots an app exposes can never drift between\n// them. It deliberately mirrors `describeSlotControl`'s classification (the\n// editor's live slot controls use the same source of truth).\n\n/** Prefix for the synthetic field key of a derived slot field: `slot:<sid>`. */\nexport const LOTTIE_SLOT_FIELD_PREFIX = \"slot:\"\n\n/** \"primaryColor\" → \"Primary Color\"; \"bar_size\" → \"Bar Size\". */\nexport function humanizeSlotSid(sid: string): string {\n return sid\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_-]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\n/** ExposableField-shaped descriptor derived from one slot. */\nexport interface LottieSlotField {\n /** Synthetic field key: `slot:<sid>`. */\n key: string\n /** Humanized sid (camelCase / snake_case → Title Case). */\n label: string\n /** Maps onto the `ExposableField.type` members used in apps. */\n type: \"color\" | \"text\" | \"slider\"\n min?: number\n max?: number\n step?: number\n /** Hex string for color; raw value for text/number. */\n defaultValue?: unknown\n}\n\n/**\n * Derive ExposableField-shaped descriptors from a motion-graphics node's plan.\n *\n * Returns [] unless `motionPlan.planType === \"lottie-graphic\"` and `slots` is a\n * non-empty object — the elements engine and absent plans expose nothing.\n *\n * Per slot, via `describeSlotControl`:\n * - color → `{ type: \"color\", defaultValue: rgbaArrayToHex(value) }`\n * - text → `{ type: \"text\", defaultValue: value }`\n * - number → `{ type: \"slider\", min, max, step, defaultValue: value }`\n * (0–1 values → 0..1 step 0.01; larger → 0..ceil(value*2) step 1)\n * - point / null → SKIPPED. Point-kind slots are intentionally not exposed in\n * apps (no paired-number card; positions are rarely end-user-meaningful).\n */\nexport function deriveLottieSlotFields(\n motionPlan: Record<string, unknown> | undefined,\n): LottieSlotField[] {\n if (!motionPlan || motionPlan.planType !== \"lottie-graphic\") return []\n const slots = motionPlan.slots\n if (!isPlainObject(slots)) return []\n\n const fields: LottieSlotField[] = []\n for (const [sid, slot] of Object.entries(slots)) {\n const control = describeSlotControl(slot)\n if (!control) continue\n const base = { key: `${LOTTIE_SLOT_FIELD_PREFIX}${sid}`, label: humanizeSlotSid(sid) }\n\n if (control.kind === \"color\") {\n fields.push({\n ...base,\n type: \"color\",\n defaultValue: rgbaArrayToHex(control.value as number[]),\n })\n } else if (control.kind === \"text\") {\n fields.push({ ...base, type: \"text\", defaultValue: control.value })\n } else if (control.kind === \"number\") {\n const value = Number(control.value)\n const isUnit = value <= 1\n fields.push({\n ...base,\n type: \"slider\",\n min: 0,\n max: isUnit ? 1 : Math.ceil(value * 2) || 100,\n step: isUnit ? 0.01 : 1,\n defaultValue: control.value,\n })\n }\n // point / unrecognized kinds are intentionally not exposed.\n }\n return fields\n}\n","/**\n * Built-in Lottie Overlay catalog — single source of truth.\n *\n * The Lottie Overlay node ships a curated set of 12 animations the overlay LLM\n * can pick from. They were originally served from the third-party lottie.host\n * CDN, which went dead (origin returns 403) and broke every catalog-based\n * overlay render in production. The replacements were authored with our own\n * Lottie engine, baked (slots resolved, no `sid` refs), and are now self-hosted\n * on the Nodaro CDN at `https://cdn.nodaro.ai/lottie-catalog/<slug>.json`.\n *\n * This module is the ONE place the catalog lives:\n * - `LOTTIE_OVERLAY_CATALOG` feeds the overlay system prompt (the LLM's menu).\n * - `LEGACY_LOTTIE_HOST_REMAP` + `resolveLottieOverlaySrc` heal saved overlay\n * plans at render time — a plan authored before the cut-over still points at\n * a dead lottie.host URL, so the renderer rewrites it to its self-hosted\n * replacement before fetching.\n */\n\nexport interface LottieOverlayCatalogEntry {\n /** Stable system key — the R2 object is `lottie-catalog/<slug>.json`. */\n readonly slug: string\n /** Display name — mirrors the original prompt's catalog labels. */\n readonly name: string\n /** Catalog group (drives the grouped layout in the system prompt). */\n readonly group:\n | \"Celebration\"\n | \"Social / Reactions\"\n | \"UI / Indicators\"\n | \"Ambient / Decorative\"\n /** One placement-intent line for the overlay LLM. */\n readonly description: string\n /** Public CDN URL: `https://cdn.nodaro.ai/lottie-catalog/<slug>.json`. */\n readonly url: string\n /** Whether the animation is continuous (loop) or a one-shot effect. */\n readonly loop: boolean\n}\n\nconst CDN_BASE = \"https://cdn.nodaro.ai/lottie-catalog\"\n\nexport const LOTTIE_OVERLAY_CATALOG: readonly LottieOverlayCatalogEntry[] = [\n // ── Celebration ────────────────────────────────────────────────────────────\n {\n slug: \"confetti-burst\",\n name: \"Confetti burst\",\n group: \"Celebration\",\n description: \"Multicolor confetti shower — large coverage at a celebratory peak; one-shot.\",\n url: `${CDN_BASE}/confetti-burst.json`,\n loop: false,\n },\n {\n slug: \"fireworks\",\n name: \"Fireworks\",\n group: \"Celebration\",\n description: \"Bursting fireworks against the sky — big-moment payoff over the upper frame; one-shot.\",\n url: `${CDN_BASE}/fireworks.json`,\n loop: false,\n },\n {\n slug: \"party-popper\",\n name: \"Party popper\",\n group: \"Celebration\",\n description: \"Party popper streamers from a corner — a quick celebratory accent; one-shot.\",\n url: `${CDN_BASE}/party-popper.json`,\n loop: false,\n },\n {\n slug: \"stars-sparkle\",\n name: \"Stars sparkle\",\n group: \"Celebration\",\n description: \"Twinkling stars/sparkles — small accent over a highlight; loops.\",\n url: `${CDN_BASE}/stars-sparkle.json`,\n loop: true,\n },\n // ── Social / Reactions ──────────────────────────────────────────────────────\n {\n slug: \"heart-pulse\",\n name: \"Heart pulse\",\n group: \"Social / Reactions\",\n description: \"Pulsing heart reaction — medium size at a corner or edge; loops.\",\n url: `${CDN_BASE}/heart-pulse.json`,\n loop: true,\n },\n {\n slug: \"thumbs-up\",\n name: \"Thumbs up\",\n group: \"Social / Reactions\",\n description: \"Thumbs-up approval reaction — medium size, pops in once; one-shot.\",\n url: `${CDN_BASE}/thumbs-up.json`,\n loop: false,\n },\n {\n slug: \"fire-flame\",\n name: \"Fire emoji\",\n group: \"Social / Reactions\",\n description: \"Flickering flame reaction (“this is fire”) — small size at an edge; loops.\",\n url: `${CDN_BASE}/fire-flame.json`,\n loop: true,\n },\n // ── UI / Indicators ─────────────────────────────────────────────────────────\n {\n slug: \"loading-spinner\",\n name: \"Loading spinner\",\n group: \"UI / Indicators\",\n description: \"Circular loading spinner — small, centered, signals progress; loops.\",\n url: `${CDN_BASE}/loading-spinner.json`,\n loop: true,\n },\n {\n slug: \"checkmark-success\",\n name: \"Checkmark success\",\n group: \"UI / Indicators\",\n description: \"Animated success checkmark — small, marks a completed/correct moment; one-shot.\",\n url: `${CDN_BASE}/checkmark-success.json`,\n loop: false,\n },\n {\n slug: \"arrow-pointer\",\n name: \"Arrow pointer\",\n group: \"UI / Indicators\",\n description: \"Animated arrow drawing attention to a spot — small, timed to a key area; loops.\",\n url: `${CDN_BASE}/arrow-pointer.json`,\n loop: true,\n },\n // ── Ambient / Decorative ────────────────────────────────────────────────────\n {\n slug: \"floating-particles\",\n name: \"Floating particles\",\n group: \"Ambient / Decorative\",\n description: \"Soft drifting particles — large coverage, low opacity, full-duration ambience; loops.\",\n url: `${CDN_BASE}/floating-particles.json`,\n loop: true,\n },\n {\n slug: \"glowing-ring\",\n name: \"Glowing ring\",\n group: \"Ambient / Decorative\",\n description: \"Pulsing glowing ring/halo — decorative accent around a focal point; loops.\",\n url: `${CDN_BASE}/glowing-ring.json`,\n loop: true,\n },\n] as const\n\n/**\n * Dead lottie.host URLs (origin returns 403) → their replacement catalog URLs.\n * Heals saved plans at render time. The keys are copied EXACTLY from the\n * original `lottie-overlay-system.ts` prompt — they are the literal `src`\n * strings the overlay LLM emitted before the cut-over.\n */\nexport const LEGACY_LOTTIE_HOST_REMAP: Readonly<Record<string, string>> = {\n // Celebration\n \"https://lottie.host/d7313e87-e4c9-4e0d-8e03-c3a59e87d8fb/TjHnrCGBjI.json\": `${CDN_BASE}/confetti-burst.json`,\n \"https://lottie.host/d5cad0dd-4e93-4bbe-b023-e94a04bc1581/JHEZMrqfMk.json\": `${CDN_BASE}/fireworks.json`,\n \"https://lottie.host/0060c9cd-75da-42d5-af7c-1a191fa8a8fd/c1xHMRnGTO.json\": `${CDN_BASE}/party-popper.json`,\n \"https://lottie.host/c04a2758-a1d9-40a9-b81f-6f3e4e13a88c/xKCYDU2w0O.json\": `${CDN_BASE}/stars-sparkle.json`,\n // Social / Reactions\n \"https://lottie.host/44c9e8d1-856c-4641-bfbe-d0e2a5c9850e/GIBsMSIkkq.json\": `${CDN_BASE}/heart-pulse.json`,\n \"https://lottie.host/9a611d56-1f35-4f51-9fa4-6a4daa6b8714/EH71MjHKPD.json\": `${CDN_BASE}/thumbs-up.json`,\n \"https://lottie.host/66db1de9-c1a8-4d0b-bb03-47a8932a8a86/q5JBGQ8fxu.json\": `${CDN_BASE}/fire-flame.json`,\n // UI / Indicators\n \"https://lottie.host/b03d748c-3b4a-4c07-a10c-e9eb3c967349/eMVAVEnb5x.json\": `${CDN_BASE}/loading-spinner.json`,\n \"https://lottie.host/3ffaab4a-58b0-4a72-9f1c-5eaa484d8c88/g27v7IPaJc.json\": `${CDN_BASE}/checkmark-success.json`,\n \"https://lottie.host/6f831c6e-693a-4d1d-90a0-d7e2b3f00e68/PFj0MwSPrj.json\": `${CDN_BASE}/arrow-pointer.json`,\n // Ambient / Decorative\n \"https://lottie.host/9c8e1aef-f8e5-4ce8-bc80-1647ffb0724d/mNDClfKJVB.json\": `${CDN_BASE}/floating-particles.json`,\n \"https://lottie.host/b5d3e7e7-40bc-44fa-9a53-78b98ad66e80/pQVdNsVDmQ.json\": `${CDN_BASE}/glowing-ring.json`,\n}\n\n/**\n * Resolve an overlay `src` through the legacy remap: a dead lottie.host URL is\n * rewritten to its self-hosted replacement; everything else (already-migrated\n * catalog URLs, user-provided assets) passes through unchanged.\n */\nexport function resolveLottieOverlaySrc(src: string): string {\n return LEGACY_LOTTIE_HOST_REMAP[src] ?? src\n}\n","/**\n * Audio FX node — preset id union (single source of truth).\n *\n * Shared so the backend Zod route enum, the frontend config dropdown, and the\n * `AudioFxData` node type can't drift. The per-preset FFmpeg filter chains\n * (IR DUR/SHAPE, delay/EQ knobs) live in the backend provider's PRESET_CHAINS\n * map — this file only fixes the id set + their human labels.\n *\n * Reverb presets are named by ON-SCREEN SCENARIO (where the voice is happening\n * in the scene) rather than abstract size, so a creator picking \"Church\" or\n * \"Car\" gets a believable space for that shot.\n */\n\nexport const AUDIO_FX_PRESETS = [\n // — reverb / spaces (afir + inline-synth IR), ordered small → large —\n \"room\", // ordinary indoor room — bedroom / office dialogue\n \"bathroom\", // small, bright, tiled — hard early reflections\n \"car\", // tight, very damped cabin\n \"hall\", // lobby / corridor / large room\n \"concert-hall\", // big, lush, musical tail\n \"church\", // cathedral — long, dark, reverberant\n \"cave\", // dark, diffuse, long\n \"arena\", // stadium / PA — huge, bright tail\n \"outdoor\", // open air — almost dry, faint early reflections\n // — character / non-reverb —\n \"telephone\", // band-limited phone line\n \"megaphone\", // PA / bullhorn — mid-forward + light grit\n \"echo\", // discrete echo / slap-back\n \"custom\", // manual: reverb wet · delay · EQ\n] as const\n\nexport type AudioFxPreset = (typeof AUDIO_FX_PRESETS)[number]\n\nexport const AUDIO_FX_PRESET_SET: ReadonlySet<string> = new Set(AUDIO_FX_PRESETS)\n\n/** Display labels for the config dropdown. */\nexport const AUDIO_FX_PRESET_LABELS: Record<AudioFxPreset, string> = {\n room: \"Room (indoor)\",\n bathroom: \"Bathroom\",\n car: \"Car interior\",\n hall: \"Hall / Lobby\",\n \"concert-hall\": \"Concert Hall\",\n church: \"Church\",\n cave: \"Cave\",\n arena: \"Arena / Stadium\",\n outdoor: \"Outdoor (open air)\",\n telephone: \"Telephone\",\n megaphone: \"Megaphone / PA\",\n echo: \"Echo / Slap-back\",\n custom: \"Custom\",\n}\n\n/** Presets that apply convolution reverb (afir + inline-synth IR). */\nexport const AUDIO_FX_REVERB_PRESETS: ReadonlySet<AudioFxPreset> = new Set<AudioFxPreset>([\n \"room\",\n \"bathroom\",\n \"car\",\n \"hall\",\n \"concert-hall\",\n \"church\",\n \"cave\",\n \"arena\",\n \"outdoor\",\n])\n","/**\n * Video Mask — text-prompted video segmentation (SAM 3.1 / SAM 3). The wire contract of\n * the `video-mask` node, `POST /v1/video-mask`, the `video_mask` MCP verb,\n * `client.media.videoMask` and `nodaro media video-mask`, defined ONCE:\n * - every bound the route schema, the node panel and the MCP verb read;\n * - `videoMaskBilledSeconds`: the length a run is priced at — the clip's\n * length at the 30 fps basis, so a 60 fps clip is priced at twice its\n * length (the segmentation works per FRAME);\n * - `videoMaskCreditId`: which price row (`model_pricing`) that length is\n * charged from. The credit amounts live in the rows, never here.\n *\n * Worked examples (repeated in docs/nodes/ai-video/video-mask.md):\n * 4 s at 30 fps → `sam-3.1-video:5s`, 5.005 s at 29.97 fps → `sam-3.1-video:5s`, 12 s at 24 fps → `sam-3.1-video:15s`,\n * 10 s at 60 fps (priced as 20 s) → `sam-3.1-video:30s`, 45 s at 30 fps → `sam-3.1-video:60s`,\n * 100 s at 30 fps → `sam-3.1-video:120s`, 4 min at 30 fps on SAM 3 → `sam-3-video:240s`.\n *\n * Wire contract only — no I/O.\n */\nimport { pricedClipSeconds } from \"./priced-clip-seconds.js\"\n\n/** Segmentation models a Video Mask run can use. SAM 3.1 (the default)\n * tracks several objects in one pass and runs faster; SAM 3 costs half. */\nexport const VIDEO_MASK_PROVIDERS = [\"sam-3.1\", \"sam-3\"] as const\nexport type VideoMaskProvider = (typeof VIDEO_MASK_PROVIDERS)[number]\nexport const DEFAULT_VIDEO_MASK_PROVIDER: VideoMaskProvider = \"sam-3.1\"\n\n/**\n * `zone`: keep only the subjects whose bounding-box CENTRE lies inside an\n * inner rectangle, given as margins in % of the frame (each\n * `VIDEO_MASK_LIMITS.ZONE_MARGIN_PCT_MIN`–`ZONE_MARGIN_PCT_MAX`). All zero, or\n * no zone, = off.\n */\nexport interface VideoMaskZone {\n readonly leftPct: number\n readonly rightPct: number\n readonly topPct: number\n readonly bottomPct: number\n}\n\n/** A new Video Mask node's settings — spread into its node definition. */\nexport const VIDEO_MASK_DEFAULTS = {\n threshold: 0.5,\n provider: \"sam-3.1\" as VideoMaskProvider,\n /** Off: the mask is the model's, frame for frame (see `HOLD_EMPTY_BELOW_FRACTION`). */\n holdLastMask: false,\n /** 0 = off: every region the model finds is kept (see `MIN_SUBJECT_HEIGHT_PCT_*`). */\n minSubjectHeightPct: 0,\n /** 0 = off: no ceiling on a region's height (see `MAX_SUBJECT_HEIGHT_PCT_*`). */\n maxSubjectHeightPct: 0,\n /** Off: subjects anywhere in the frame are kept (see `ZONE_MARGIN_PCT_*`). */\n zone: null as VideoMaskZone | null,\n /**\n * Off: one pass over the whole clip. On: the clip's scene cuts are found\n * first and each shot is segmented on its own — the model starts afresh\n * after every cut (finding the new shot's subjects), and `holdLastMask`\n * never carries a mask across a cut. A clip with no cut (a flash is\n * usually not one) is one shot: the same mask, fitted to the clip's exact\n * frame count.\n */\n perShot: false,\n /**\n * 0 = off: a new detection only where a request starts anyway (the clip's\n * start, every 1,800 frames, and every cut with `perShot`). Above 0: the\n * model is also sent a new request every this many seconds of footage, so a\n * subject that first appears mid-shot is found within that time (see\n * `REDETECT_EVERY_SEC_*`). These boundaries are not cuts: `holdLastMask`\n * keeps holding across them.\n */\n redetectEverySec: 0,\n} as const\n\nexport const VIDEO_MASK_LIMITS = {\n /** The longest input clip a run accepts, in seconds of PRICED length (see `videoMaskBilledSeconds`). */\n MAX_BILLED_SEC: 300,\n /** Frame rate the price rows assume. A faster clip is priced proportionally longer. */\n FPS_BASIS: 30,\n /** Subject description length cap. */\n PROMPT_MAX_LENGTH: 500,\n /** Detection confidence bounds (the model's own range, narrowed to useful values). */\n THRESHOLD_MIN: 0.05,\n THRESHOLD_MAX: 0.95,\n THRESHOLD_STEP: 0.05,\n /** Default detection confidence. Lower finds more (and less precise) regions. */\n THRESHOLD_DEFAULT: VIDEO_MASK_DEFAULTS.threshold,\n /**\n * `holdLastMask`: a frame whose mask covers less than this fraction of the\n * picture (0.002 % — about 41 px at 1080p: a stray speck, never a subject) counts as empty — the subject lost (hidden behind a\n * hand, turned away) — and shows the most recent non-empty frame's mask\n * instead. Frames before the first detection stay as they are.\n */\n HOLD_EMPTY_BELOW_FRACTION: 0.00002,\n /**\n * `holdLastMask`: the longest a mask is held, in seconds of frames (at the\n * clip's rate). The hold is for a subject hidden for a moment; a run of\n * empty frames longer than this shows the held mask for its first second\n * and then nothing, until the model finds the subject again — a mask held\n * on for longer sits where the subject no longer is.\n */\n HOLD_MAX_SEC: 1,\n /**\n * `minSubjectHeightPct`: drop every connected white region (8-connected)\n * whose bounding box is shorter than this % of the frame height — extras'\n * small faces behind the main subject. 0 = off. Applied before\n * `holdLastMask`, so a frame left with only small regions counts as empty\n * and is held from the last frame with a big subject.\n */\n MIN_SUBJECT_HEIGHT_PCT_MIN: 0,\n MIN_SUBJECT_HEIGHT_PCT_MAX: 100,\n /**\n * `maxSubjectHeightPct`, the mirror: drop every region whose bounding box is\n * TALLER than this % of the frame height (keep only the small subjects — a\n * paste-back mask of the background faces). 0 = off. With both set, a\n * region is kept when min ≤ height ≤ max (min > max is refused). Same pass,\n * same order (before `holdLastMask`).\n */\n MAX_SUBJECT_HEIGHT_PCT_MIN: 0,\n MAX_SUBJECT_HEIGHT_PCT_MAX: 100,\n /**\n * `zone` margins (left / right / top / bottom, % of the frame width or\n * height): drop every connected region whose bounding-box centre lies\n * outside `[w·left/100, w·(1−right/100)] × [h·top/100, h·(1−bottom/100)]`\n * — the faces at the edges of the picture. At most 49 % a side, so the\n * inner rectangle is never empty. Applied after the size cut and before\n * `holdLastMask`, so a frame left with nothing inside counts as empty.\n */\n ZONE_MARGIN_PCT_MIN: 0,\n ZONE_MARGIN_PCT_MAX: 49,\n /**\n * `redetectEverySec`: 0 (off) or `REDETECT_EVERY_SEC_MIN`–`MAX` seconds. The\n * model picks up its subjects near the start of each request; a face that\n * turns to the camera, or a person who walks in, partway through a request is\n * never masked. On, the clip (each shot, with `perShot`) is cut into requests\n * of at most this many seconds of frames — counted from the shot's start, a\n * last piece shorter than `VIDEO_MASK_MIN_SHOT_FRAMES` joining the one before\n * — so the subjects are detected again at every such boundary. Each request\n * adds wall time (they run three at a time); the price follows the clip's\n * length and does not change.\n */\n REDETECT_EVERY_SEC_MIN: 1,\n REDETECT_EVERY_SEC_MAX: 10,\n /** The panel's step (the API takes any value in range). */\n REDETECT_EVERY_SEC_STEP: 1,\n} as const\n\n/**\n * The version of what a Video Mask run's mask looks like for a given clip and\n * settings: every finished `video-mask` job reports it as `output_data.recipe`.\n * A mask stored ahead of time and reused (a trend's approved face mask) is\n * held to it, and reads as out of date once it changes.\n *\n * BUMP IT (to the date of the change) whenever the algorithm changes the mask\n * a run produces from the same clip and settings: the cut rule (`perShot`),\n * the hold (`holdLastMask`, `HOLD_*`), the size and zone filters, the\n * rendering. Never for a change that leaves every mask the same (pricing,\n * limits on what is accepted, messages). `\"2026-10-25\"`: the lone-spike cut\n * rule and the 1 s hold cap.\n */\nexport const VIDEO_MASK_RECIPE = \"2026-10-25\"\n\nconst VIDEO_MASK_BUCKETS_SEC = [5, 10, 15, 30, 60, 90, 120, 180, 240, 300] as const\n\n/** Every price row a provider can be charged from, smallest first. */\nexport function videoMaskCreditIds(provider: VideoMaskProvider = DEFAULT_VIDEO_MASK_PROVIDER): string[] {\n return VIDEO_MASK_BUCKETS_SEC.map((sec) => `${provider}-video:${sec}s`)\n}\n\n/**\n * The length a clip is priced at: its duration at the 30 fps basis. A clip\n * at or under 30 fps is priced at its own length; a 60 fps clip at twice it.\n * An unknown frame rate counts as the basis. The cap reads this figure; the\n * price row reads it through `pricedClipSeconds`.\n */\nexport function videoMaskBilledSeconds(durationSec: number, fps?: number | null): number {\n const rate = typeof fps === \"number\" && Number.isFinite(fps) && fps > 0 ? fps : VIDEO_MASK_LIMITS.FPS_BASIS\n return durationSec * Math.max(1, rate / VIDEO_MASK_LIMITS.FPS_BASIS)\n}\n\n/**\n * The price row for a clip priced at `billedSec` seconds: the smallest that\n * holds it, after `pricedClipSeconds` (up to 0.05 s past a row's length stays in\n * that row). An unknown or non-positive length prices the LONGEST row (a clip\n * the route could not measure is refused, so this is only the pre-run quote for\n * a clip whose length is not known yet); anything past the cap prices the last\n * row.\n */\nexport function videoMaskCreditId(\n billedSec: number | null | undefined,\n provider: VideoMaskProvider = DEFAULT_VIDEO_MASK_PROVIDER,\n): string {\n const ids = videoMaskCreditIds(provider)\n if (typeof billedSec !== \"number\" || !Number.isFinite(billedSec) || billedSec <= 0) return ids[ids.length - 1]!\n const priced = pricedClipSeconds(billedSec)\n const i = VIDEO_MASK_BUCKETS_SEC.findIndex((b) => priced <= b)\n return ids[i === -1 ? ids.length - 1 : i]!\n}\n\n/** Narrow an arbitrary value to a known provider, falling back to the default. */\nexport function resolveVideoMaskProvider(value: unknown): VideoMaskProvider {\n return (VIDEO_MASK_PROVIDERS as readonly string[]).includes(value as string)\n ? (value as VideoMaskProvider)\n : DEFAULT_VIDEO_MASK_PROVIDER\n}\n\n/**\n * A zone as the region filter reads it: each margin a finite number clamped\n * to `ZONE_MARGIN_PCT_MIN`–`ZONE_MARGIN_PCT_MAX` (anything else is 0), and\n * null when there is no zone or every margin is 0 (off). The one reading\n * shared by the worker, a workflow run's payload and the node's own run.\n */\nexport function resolveVideoMaskZone(value: unknown): VideoMaskZone | null {\n if (!value || typeof value !== \"object\") return null\n const v = value as Record<string, unknown>\n const margin = (x: unknown) =>\n typeof x === \"number\" && Number.isFinite(x)\n ? Math.min(VIDEO_MASK_LIMITS.ZONE_MARGIN_PCT_MAX, Math.max(VIDEO_MASK_LIMITS.ZONE_MARGIN_PCT_MIN, x))\n : 0\n const zone = { leftPct: margin(v.leftPct), rightPct: margin(v.rightPct), topPct: margin(v.topPct), bottomPct: margin(v.bottomPct) }\n return zone.leftPct > 0 || zone.rightPct > 0 || zone.topPct > 0 || zone.bottomPct > 0 ? zone : null\n}\n\n/**\n * `redetectEverySec` as a run reads it: a finite number above 0 clamped to\n * `REDETECT_EVERY_SEC_MIN`–`MAX` (a value between 0 and the minimum snaps up\n * to it — it asked for re-detection); anything else (absent, 0, negative,\n * not a number) is 0 = off. The one reading shared by the worker, a workflow\n * run's payload, the node's own run and its panel (the route refuses a value\n * out of range instead).\n */\nexport function resolveVideoMaskRedetectSec(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return 0\n return Math.min(VIDEO_MASK_LIMITS.REDETECT_EVERY_SEC_MAX, Math.max(VIDEO_MASK_LIMITS.REDETECT_EVERY_SEC_MIN, value))\n}\n\n/** `POST /v1/video-mask` request body. */\nexport interface VideoMaskRequest {\n /** The clip to segment. */\n readonly videoUrl: string\n /** What to track: a short noun phrase; separate several with commas. */\n readonly prompt: string\n /** Detection confidence, `VIDEO_MASK_LIMITS.THRESHOLD_MIN`–`THRESHOLD_MAX` (default 0.5). */\n readonly threshold?: number\n readonly provider?: VideoMaskProvider\n /** Hold the last mask where the subject is lost (default false): an empty frame\n * after the first detection repeats the most recent non-empty one. */\n readonly holdLastMask?: boolean\n /** Ignore subjects smaller than this % of the frame height, 0–100 (default 0 = off):\n * connected regions whose bounding box is shorter are dropped from every frame. */\n readonly minSubjectHeightPct?: number\n /** Ignore subjects larger than this % of the frame height, 0–100 (default 0 = off):\n * connected regions whose bounding box is taller are dropped from every frame. */\n readonly maxSubjectHeightPct?: number\n /** Keep only the subjects whose bounding-box centre is inside these margins, each\n * 0–49 % of the frame (a margin left out is 0). null / omitted / all 0 = off. */\n readonly zone?: Partial<VideoMaskZone> | null\n /** Segment each shot on its own (default false): the clip's scene cuts are found\n * first and the subjects are detected again in every shot; `holdLastMask` never\n * carries a mask across a cut. The output then carries `shots`. */\n readonly perShot?: boolean\n /** Detect the subjects again every this many seconds (0 = off, the default, or\n * `VIDEO_MASK_LIMITS.REDETECT_EVERY_SEC_MIN`–`MAX`): the clip — each shot, with\n * `perShot` — is sent to the model in pieces of at most that length, so a subject\n * that first appears mid-shot is masked from the next boundary on. Not a cut:\n * `holdLastMask` holds across these boundaries. Slower (more requests); same price. */\n readonly redetectEverySec?: number\n}\n","/**\n * Video Face Mesh (`POST /v1/video-face-mesh`, job type `video-face-mesh`):\n * thin GRAY face lines — a wireframe, and darker eye and lip outlines, each a\n * tone of the picture under it — drawn on the faces of a clip, frame for\n * frame. An internal step of Nodaro Motion's face masking: the lines go on\n * the masked (or depth) clip so the video model still sees where the mouth\n * and the eyes are. A request may draw only the eye and lip outlines, only\n * the lip outline, or the face's contours (`parts`).\n *\n * Priced by the clip's length at the 30 fps basis Video Mask uses\n * (`videoMaskBilledSeconds`), one row per length bucket.\n */\nimport { pricedClipSeconds } from \"./priced-clip-seconds.js\"\nimport { VIDEO_MASK_LIMITS, type VideoMaskZone } from \"./video-mask.js\"\nimport type { VideoDepthColormap } from \"./video-depth.js\"\n\n/** The route, as the Cast Swap engine calls it. */\nexport const VIDEO_FACE_MESH_PATH = \"/v1/video-face-mesh\"\n\nexport const VIDEO_FACE_MESH_LIMITS = {\n /** The longest clip a run accepts, in seconds of PRICED length (the 30 fps basis): Video Mask's own cap. */\n MAX_BILLED_SEC: VIDEO_MASK_LIMITS.MAX_BILLED_SEC,\n /** `minFaceHeightPct` / `maxFaceHeightPct` bounds (0 = off). */\n FACE_HEIGHT_PCT_MIN: 0,\n FACE_HEIGHT_PCT_MAX: 100,\n /** `zone` margin bounds, as Video Mask's. */\n ZONE_MARGIN_PCT_MIN: VIDEO_MASK_LIMITS.ZONE_MARGIN_PCT_MIN,\n ZONE_MARGIN_PCT_MAX: VIDEO_MASK_LIMITS.ZONE_MARGIN_PCT_MAX,\n} as const\n\n/**\n * What a face mesh run draws on each face (`VideoFaceMeshRequest.parts`):\n * `\"full\"` (the default) the thin wireframe and the darker eye and lip\n * outlines; `\"features\"` the eye outlines and the lip outline only, no\n * wireframe; `\"mouth\"` the lip outline only; `\"contours\"` the face oval,\n * both eyebrows, the nose and the eye and lip outlines, no wireframe (a host\n * that draws them says so to its engine: `videoFaceMeshContours`).\n */\nexport const VIDEO_FACE_MESH_PARTS = [\"full\", \"features\", \"mouth\", \"contours\"] as const\nexport type VideoFaceMeshParts = (typeof VIDEO_FACE_MESH_PARTS)[number]\n\n/**\n * The face mesh's layers (`VideoFaceMeshRequest.layers`), each drawn or not\n * on its own:\n * - `wireframe`: the thin mesh over the whole face;\n * - `eyes`: the eye outlines; `lips`: the lip outline, outer and inner;\n * - `contours`: the face oval, both eyebrows and the nose. With it on, every\n * line drawn leaves out what the face hides (a turned face's far side);\n * with it off, nothing is left out;\n * - `irises`: a circle round each iris and a dot at its centre, drawn only\n * inside the eye's opening (an eyelid covers it, a closed eye hides it);\n * - `bold`: the lines drawn thicker and in a deeper tone. It draws nothing\n * of its own: it changes the lines of the other layers.\n * Every `parts` value is one set of layers (`videoFaceMeshLayersOfParts`),\n * drawn exactly as that value is.\n */\nexport const VIDEO_FACE_MESH_LAYERS = [\"wireframe\", \"eyes\", \"lips\", \"contours\", \"irises\", \"bold\"] as const\nexport type VideoFaceMeshLayer = (typeof VIDEO_FACE_MESH_LAYERS)[number]\n/** The layers that draw lines of their own (all but `bold`): a set needs at least one. */\nexport const VIDEO_FACE_MESH_LINE_LAYERS = [\"wireframe\", \"eyes\", \"lips\", \"contours\", \"irises\"] as const satisfies readonly VideoFaceMeshLayer[]\n/** A set of layers: each one on when `true`; left out or `false` is off. */\nexport type VideoFaceMeshLayers = { readonly [K in VideoFaceMeshLayer]?: boolean }\n\nconst PARTS_LAYERS: Readonly<Record<VideoFaceMeshParts, readonly VideoFaceMeshLayer[]>> = {\n full: [\"wireframe\", \"eyes\", \"lips\"],\n features: [\"eyes\", \"lips\"],\n mouth: [\"lips\"],\n contours: [\"eyes\", \"lips\", \"contours\"],\n}\n\n/** The set of layers a `parts` value draws (left out: `\"full\"`), a new object with only its layers, each `true`. */\nexport function videoFaceMeshLayersOfParts(parts: VideoFaceMeshParts = \"full\"): VideoFaceMeshLayers {\n return Object.fromEntries(PARTS_LAYERS[parts].map((l) => [l, true]))\n}\n\n/** The set with only its layers that are on, each `true`, in `VIDEO_FACE_MESH_LAYERS` order: a new object. */\nexport function videoFaceMeshLayersOn(layers: VideoFaceMeshLayers | null | undefined): VideoFaceMeshLayers {\n return Object.fromEntries(VIDEO_FACE_MESH_LAYERS.filter((l) => layers?.[l] === true).map((l) => [l, true]))\n}\n\n/** Whether the set draws any line (a layer other than `bold` on). */\nexport function videoFaceMeshLayersDrawLines(layers: VideoFaceMeshLayers | null | undefined): boolean {\n return VIDEO_FACE_MESH_LINE_LAYERS.some((l) => layers?.[l] === true)\n}\n\n/**\n * The `parts` value that draws exactly this set of layers, or undefined when\n * none does (a set only layers can name: the irises, bold lines, the eyes\n * alone…). `among` limits the values it may answer (a setting that takes only\n * some of them).\n */\nexport function videoFaceMeshPartsOfLayers(\n layers: VideoFaceMeshLayers | null | undefined,\n among: readonly VideoFaceMeshParts[] = VIDEO_FACE_MESH_PARTS,\n): VideoFaceMeshParts | undefined {\n const on = VIDEO_FACE_MESH_LAYERS.filter((l) => layers?.[l] === true)\n return among.find((p) => PARTS_LAYERS[p].length === on.length && PARTS_LAYERS[p].every((l) => on.includes(l)))\n}\n\n/**\n * The version of what a face mesh run draws for a given clip and settings:\n * every finished `video-face-mesh` job reports it as `output_data.recipe`,\n * for the caller to record beside a clip it stores with the lines on it (a\n * trend's approved face mask). Nothing on the platform compares it yet: a\n * stored mask is held to Video Mask's recipe and the engine's own.\n *\n * BUMP IT (to the date of the change) whenever the drawing changes for the\n * same input: the model, the crop, the smoothing, the filters, the colours or\n * the widths. Never for pricing, limits or messages. 2026-11-02: MediaPipe's\n * refined landmark model (478 points, a 256 × 256 crop) in place of the basic\n * one; the lines' colours and widths are 2026-11-01's. 2026-11-03: a face gets\n * lines only when it is found in at least 3 frames of its track (found faces\n * at the same place in frames at most 2 apart): one found in a frame or two\n * is never drawn.\n */\nexport const VIDEO_FACE_MESH_RECIPE = \"2026-11-03\"\n\nconst VIDEO_FACE_MESH_BUCKETS_SEC = [5, 10, 15, 30, 60, 120, 300] as const\n\n/** Every price row, smallest first (`video-face-mesh:<n>s`). */\nexport function videoFaceMeshCreditIds(): string[] {\n return VIDEO_FACE_MESH_BUCKETS_SEC.map((sec) => `video-face-mesh:${sec}s`)\n}\n\n/**\n * The price row for a clip priced at `billedSec` seconds: the smallest bucket\n * that holds it, after `pricedClipSeconds` (up to 0.05 s past a bucket's length\n * stays in that bucket). An unknown or non-positive length, or one past the cap,\n * prices the LONGEST row (the route measures every clip and refuses one past\n * the cap, so this is only ever a ceiling).\n */\nexport function videoFaceMeshCreditId(billedSec: number | null | undefined): string {\n const ids = videoFaceMeshCreditIds()\n if (typeof billedSec !== \"number\" || !Number.isFinite(billedSec) || billedSec <= 0) return ids[ids.length - 1]!\n const priced = pricedClipSeconds(billedSec)\n const i = VIDEO_FACE_MESH_BUCKETS_SEC.findIndex((b) => priced <= b)\n return ids[i === -1 ? ids.length - 1 : i]!\n}\n\n/** `POST /v1/video-face-mesh` request body. */\nexport interface VideoFaceMeshRequest {\n /** The clip the faces are FOUND in (the original). */\n readonly videoUrl: string\n /** The clip the lines are DRAWN on (default `videoUrl`): the masked or depth clip. Same frame count. */\n readonly drawOnUrl?: string\n /** A mask video (white = covered, same frame count): only faces whose box centre lies inside it are drawn. */\n readonly maskUrl?: string\n /** Draw only faces at least this % of the frame's height (default 0 = off). */\n readonly minFaceHeightPct?: number\n /** Draw only faces at most this % of the frame's height (0 = no cap). */\n readonly maxFaceHeightPct?: number\n /** Margins (% of the frame) where no face is drawn. */\n readonly zone?: Partial<VideoMaskZone> | null\n /**\n * The depth map's colormap (Video Depth's `VIDEO_DEPTH_COLORMAPS`) when the\n * lines go on a depth map: each line is then a colour OF that map — the map\n * at the line's tone of the depth under it. Needs `depthUrl`, except\n * `grayscale` (a gray depth clip is its own depth). Left out with a\n * `depthUrl`: `grayscale`.\n */\n readonly colormap?: VideoDepthColormap\n /**\n * The GRAYSCALE depth render of the clip (Video Depth with `colormap:\n * \"grayscale\"`, same frame count as `videoUrl`, any size): the depth each\n * line's colour is read from. Left out (a blurred mask, a gray depth clip\n * drawn on directly): each line is a gray tone of the pixel under it.\n */\n readonly depthUrl?: string\n /**\n * What is drawn on each face (`VIDEO_FACE_MESH_PARTS`): left out or\n * `\"full\"`, the wireframe and the eye and lip outlines; `\"features\"`, the\n * eye and lip outlines only; `\"mouth\"`, the lip outline only. The outlines\n * are drawn as they are in the full mesh (the same tone and width).\n */\n readonly parts?: VideoFaceMeshParts\n /**\n * What is drawn, layer by layer (`VIDEO_FACE_MESH_LAYERS`), in place of\n * `parts` (never both). At least one layer other than `bold`. A set that is\n * a `parts` value's draws exactly as that value does.\n */\n readonly layers?: VideoFaceMeshLayers\n}\n\n/** A finished `video-face-mesh` job's `output_data`. */\nexport interface VideoFaceMeshOutput {\n /** The drawn clip: `drawOnUrl`'s frame count, size and frame rate, its audio copied untouched. */\n readonly videoUrl: string\n readonly width: number\n readonly height: number\n readonly frames: number\n /** Frames with at least one face drawn. */\n readonly framesWithFaces: number\n /** Faces drawn, summed over the frames (0 = nothing drawn; the clip comes back as it was sent). */\n readonly facesDrawn: number\n /** The map the lines were coloured from (a request with `depthUrl`); absent = gray tones of the pixel under them. */\n readonly colormap?: VideoDepthColormap\n /** What was drawn when it was not the full mesh (a request with `parts` `\"features\"` or `\"mouth\"`); absent = the full mesh. */\n readonly parts?: Exclude<VideoFaceMeshParts, \"full\">\n /** The layers drawn, for a request that named `layers` (only those on, each `true`); absent: `parts` says. */\n readonly layers?: VideoFaceMeshLayers\n readonly recipe: string\n}\n","/**\n * Generate Mask — text-prompted IMAGE segmentation (Grounded SAM). The wire\n * contract of `POST /v1/generate-mask`, the `generate_mask` MCP verb, the SDK's\n * `nodes.run(\"generate-mask\", …)` and `nodaro media generate-mask`, defined ONCE:\n * every bound the route schema and the SDK/CLI read.\n *\n * The finished job's output is `{ maskUrl, imageUrl }`: `maskUrl` is the\n * black-and-white mask PNG (white = the subject), `imageUrl` is the SOURCE\n * image passed through unchanged, so an inpainting step can take the pair.\n *\n * Wire contract only — no I/O.\n */\n\nexport const GENERATE_MASK_LIMITS = {\n /** Subject description length cap. */\n PROMPT_MAX_LENGTH: 500,\n /** Segmentation confidence bounds. */\n THRESHOLD_MIN: 0,\n THRESHOLD_MAX: 1,\n /** Default segmentation confidence. Lower selects more (and less precise) regions. */\n THRESHOLD_DEFAULT: 0.3,\n} as const\n\n/** `POST /v1/generate-mask` request body. */\nexport interface GenerateMaskRequest {\n /** The image to segment. */\n readonly imageUrl: string\n /** What to select, in plain words (e.g. \"the person\", \"sky and clouds\"). 1–500 characters. */\n readonly prompt: string\n /** Segmentation confidence, `GENERATE_MASK_LIMITS.THRESHOLD_MIN`–`THRESHOLD_MAX` (default 0.3). */\n readonly threshold?: number\n}\n\n/** A completed Generate Mask job's `output_data`. */\nexport interface GenerateMaskOutput {\n /** The mask: a black-and-white PNG, white = the subject. */\n readonly maskUrl: string\n /** The source image, passed through unchanged. */\n readonly imageUrl: string\n}\n","/**\n * Mask Composite — place a foreground video over a background video through a\n * mask video (white = keep the foreground, black = show the background). The\n * wire contract of the `mask-composite` node, `POST /v1/mask-composite`, the\n * `mask_composite` MCP verb, `client.media.maskComposite` and\n * `nodaro media mask-composite`, defined ONCE. Pair it with Video Mask, whose\n * output is exactly such a mask.\n *\n * The render follows the FOREGROUND: its size, frame rate and length. The\n * background is fitted to that frame (`backgroundFit`) and loops when shorter;\n * the mask is stretched to the frame and holds its last frame when shorter.\n *\n * `fill` picks what fills the masked area. `\"video\"` (the default) is the\n * foreground, as above. `\"pixelate\"` and `\"blur\"` fill it with the BACKGROUND\n * itself, pixelated or blurred: there is no foreground then (a sent\n * `foregroundUrl` is ignored), so the render follows the BACKGROUND (its size,\n * frame rate and length; `backgroundFit` has nothing to fit), and the run is\n * priced on the background's length. With no foreground the result always\n * carries the background's sound — `audioSource` is ignored there\n * ({@link maskCompositeEffectiveAudioSource}); the canvas hides the control.\n *\n * Priced per started 5 seconds of the result (the foreground's length), like\n * Trim / Loop / Combine Videos: the node's own `model_pricing` row is ONE unit\n * (`maskCompositeUnits` counts them). Worked examples (repeated in\n * docs/nodes/processing-video/mask-composite.md, at the 10-credit row):\n * 3 s → 1 unit (10), 10 s → 2 units (20), 61 s → 13 units (130), 5 min → 60 units (600).\n *\n * Wire contract only — no I/O.\n */\nimport { pricedClipSeconds } from \"./priced-clip-seconds.js\"\n\n/** How the background is fitted to the foreground's frame. */\nexport const MASK_COMPOSITE_BACKGROUND_FITS = [\"cover\", \"contain\", \"stretch\"] as const\nexport type MaskCompositeBackgroundFit = (typeof MASK_COMPOSITE_BACKGROUND_FITS)[number]\n\n/** What fills the masked area: the foreground video, or the background itself pixelated or blurred. */\nexport const MASK_COMPOSITE_FILLS = [\"video\", \"pixelate\", \"blur\"] as const\nexport type MaskCompositeFill = (typeof MASK_COMPOSITE_FILLS)[number]\n\n/** Which sound the result carries. `mix` blends both tracks at equal level. */\nexport const MASK_COMPOSITE_AUDIO_SOURCES = [\"foreground\", \"background\", \"mix\", \"none\"] as const\nexport type MaskCompositeAudioSource = (typeof MASK_COMPOSITE_AUDIO_SOURCES)[number]\n\nexport const MASK_COMPOSITE_BOUNDS = {\n /** Edge softening, pixels of blur radius on the mask (0 = hard edge). */\n FEATHER_MIN: 0,\n FEATHER_MAX: 20,\n /** Grow (+) or shrink (−) the white region, pixels. */\n GROW_MIN: -10,\n GROW_MAX: 10,\n /** How strongly the foreground covers the background inside the mask\n * (1 = fully, today's output; 0 = not at all). */\n OPACITY_MIN: 0,\n OPACITY_MAX: 1,\n /** Pixelate: the block size as a % of the frame's WIDTH (relative, so a\n * setting looks the same at any resolution); the worker makes the blocks\n * max(2, round(width × pct / 100)) px. 1.25 % = 16 px on a 1280-wide frame. */\n PIXEL_SIZE_PCT_MIN: 0.2,\n PIXEL_SIZE_PCT_MAX: 10,\n /** Blur: the gaussian's sigma as a % of the frame's WIDTH (2 % ≈ sigma 25 px on a 1280-wide frame). */\n BLUR_STRENGTH_PCT_MIN: 0.1,\n BLUR_STRENGTH_PCT_MAX: 5,\n /** The longest leading video (the foreground; the background when `fill` is not video) a run accepts, seconds. */\n MAX_DURATION_SEC: 300,\n} as const\n\n/** Seconds of result one pricing unit covers. */\nexport const MASK_COMPOSITE_UNIT_SEC = 5\n\n/**\n * How much longer, in seconds, the leading video the render downloads may run\n * than the one measured before the run was charged, before the render refuses\n * it as changed: a re-measure can read a hair longer (a re-encode, a\n * container's rounding), and that is not a different file. Applied to the\n * seconds, never to the units, before the price's own 0.05 s grace\n * (`pricedClipSeconds`): a run billed for 10 s renders a lead of up to about\n * 10.55 s. The same slack as Video Overlay's base.\n */\nexport const MASK_COMPOSITE_REMEASURE_SLACK_SEC = 0.5\n\n/**\n * Pricing units for a result `durationSec` long: one per started 5 seconds,\n * at least one, after `pricedClipSeconds` (up to 0.05 s past a whole second is\n * ignored, so a 10.01 s result is 2 units, not 3). An unknown length counts the\n * longest result a run accepts (an upper bound — the pre-run quote for a clip\n * whose length is not known yet; every run measures its foreground).\n */\nexport function maskCompositeUnits(durationSec: number | null | undefined): number {\n const sec =\n typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n ? Math.min(durationSec, MASK_COMPOSITE_BOUNDS.MAX_DURATION_SEC)\n : MASK_COMPOSITE_BOUNDS.MAX_DURATION_SEC\n return Math.ceil(pricedClipSeconds(sec) / MASK_COMPOSITE_UNIT_SEC)\n}\n\nexport const MASK_COMPOSITE_DEFAULTS = {\n invertMask: false,\n feather: 2,\n grow: 0,\n opacity: 1,\n fill: \"video\" as MaskCompositeFill,\n pixelSizePct: 1.25,\n blurStrengthPct: 2,\n backgroundFit: \"cover\" as MaskCompositeBackgroundFit,\n audioSource: \"foreground\" as MaskCompositeAudioSource,\n} as const\n\nexport interface MaskCompositeSettings {\n readonly invertMask: boolean\n readonly feather: number\n readonly grow: number\n /** Inside the mask: opacity × foreground + (1 − opacity) × background. */\n readonly opacity: number\n /** What fills the masked area (`video` = the foreground). */\n readonly fill: MaskCompositeFill\n /** Pixelate block size, % of the frame width (used when `fill` is `pixelate`). */\n readonly pixelSizePct: number\n /** Blur strength: the gaussian's sigma as a % of the frame width (used when `fill` is `blur`). */\n readonly blurStrengthPct: number\n readonly backgroundFit: MaskCompositeBackgroundFit\n readonly audioSource: MaskCompositeAudioSource\n}\n\nconst clampInt = (v: unknown, min: number, max: number, fallback: number): number =>\n typeof v === \"number\" && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : fallback\n\nconst clampNumber = (v: unknown, min: number, max: number, fallback: number): number =>\n typeof v === \"number\" && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback\n\n/**\n * Node data (or any loose object) → settings every engine renders with.\n * Unknown enum values fall back to the default and numbers are clamped, so a\n * node written straight into workflow JSON renders the same as one set in the\n * panel. The ONE normaliser both workflow engines and the worker call.\n */\nexport function resolveMaskCompositeSettings(data: Readonly<Record<string, unknown>>): MaskCompositeSettings {\n const d = MASK_COMPOSITE_DEFAULTS\n const b = MASK_COMPOSITE_BOUNDS\n return {\n invertMask: typeof data.invertMask === \"boolean\" ? data.invertMask : d.invertMask,\n feather: clampInt(data.feather, b.FEATHER_MIN, b.FEATHER_MAX, d.feather),\n grow: clampInt(data.grow, b.GROW_MIN, b.GROW_MAX, d.grow),\n opacity: clampNumber(data.opacity, b.OPACITY_MIN, b.OPACITY_MAX, d.opacity),\n fill: maskCompositeFillOf(data),\n pixelSizePct: clampNumber(data.pixelSizePct, b.PIXEL_SIZE_PCT_MIN, b.PIXEL_SIZE_PCT_MAX, d.pixelSizePct),\n blurStrengthPct: clampNumber(data.blurStrengthPct, b.BLUR_STRENGTH_PCT_MIN, b.BLUR_STRENGTH_PCT_MAX, d.blurStrengthPct),\n backgroundFit: (MASK_COMPOSITE_BACKGROUND_FITS as readonly string[]).includes(data.backgroundFit as string)\n ? (data.backgroundFit as MaskCompositeBackgroundFit)\n : d.backgroundFit,\n audioSource: (MASK_COMPOSITE_AUDIO_SOURCES as readonly string[]).includes(data.audioSource as string)\n ? (data.audioSource as MaskCompositeAudioSource)\n : d.audioSource,\n }\n}\n\n/** The fill a node, payload or request body asks for: an unknown value is `video` (the default). */\nexport function maskCompositeFillOf(data: Readonly<Record<string, unknown>> | null | undefined): MaskCompositeFill {\n const f = data?.fill\n return (MASK_COMPOSITE_FILLS as readonly string[]).includes(f as string) ? (f as MaskCompositeFill) : MASK_COMPOSITE_DEFAULTS.fill\n}\n\n/** Does this fill take a foreground video? Only `video` does; pixelate and blur fill from the background. */\nexport function maskCompositeUsesForeground(fill: MaskCompositeFill): boolean {\n return fill === \"video\"\n}\n\n/**\n * The input whose size, rate and length the result has (and so the one a run\n * is measured and priced on): the canvas handle — `video` (the foreground) for\n * the video fill, `background-video` for pixelate and blur. The one rule the\n * route, the workflow run, the run estimates and the length walks read.\n */\nexport function maskCompositeLeadHandle(data: Readonly<Record<string, unknown>> | null | undefined): \"video\" | \"background-video\" {\n return maskCompositeUsesForeground(maskCompositeFillOf(data)) ? \"video\" : \"background-video\"\n}\n\n/**\n * The sound a render actually carries. With no foreground (pixelate / blur) it\n * is ALWAYS the background's — the only track there is — whatever\n * `audioSource` says (the canvas hides that control for these fills, so a\n * stored `none` from the Video fill can never silently mute the result).\n */\nexport function maskCompositeEffectiveAudioSource(s: Pick<MaskCompositeSettings, \"fill\" | \"audioSource\">): MaskCompositeAudioSource {\n if (maskCompositeUsesForeground(s.fill)) return s.audioSource\n return \"background\"\n}\n\n/** `POST /v1/mask-composite` request body. */\nexport interface MaskCompositeRequest extends Partial<MaskCompositeSettings> {\n /** The video whose white-masked region is kept (its size, rate and length lead).\n * Required when `fill` is `video` (the default); not used by `pixelate` / `blur`. */\n readonly foregroundUrl?: string\n /** The video shown where the mask is black. */\n readonly backgroundUrl: string\n /** The mask video — white = foreground (Video Mask's output). */\n readonly maskUrl: string\n}\n"]}