@nodaro/shared 3.55.0 → 3.56.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.
- package/dist/{chunk-3CHOZ573.js → chunk-2AR3OXAA.js} +276 -17
- package/dist/chunk-2AR3OXAA.js.map +1 -0
- package/dist/{chunk-ZKHQSG76.js → chunk-2J6NTA5I.js} +4 -4
- package/dist/{chunk-ZKHQSG76.js.map → chunk-2J6NTA5I.js.map} +1 -1
- package/dist/{chunk-AGTCHDG5.cjs → chunk-33P5FI2U.cjs} +6 -6
- package/dist/{chunk-AGTCHDG5.cjs.map → chunk-33P5FI2U.cjs.map} +1 -1
- package/dist/{chunk-HG3KKCJJ.js → chunk-4JODLC2N.js} +3 -3
- package/dist/{chunk-HG3KKCJJ.js.map → chunk-4JODLC2N.js.map} +1 -1
- package/dist/{chunk-N3WL6IOJ.js → chunk-4O5STV7N.js} +55 -5
- package/dist/chunk-4O5STV7N.js.map +1 -0
- package/dist/chunk-4ONS6QRT.js +42 -0
- package/dist/chunk-4ONS6QRT.js.map +1 -0
- package/dist/{chunk-E4YES25K.js → chunk-55FQBILM.js} +4 -4
- package/dist/{chunk-E4YES25K.js.map → chunk-55FQBILM.js.map} +1 -1
- package/dist/{chunk-ZWB3NG4M.js → chunk-62ZQQA7L.js} +3 -3
- package/dist/{chunk-ZWB3NG4M.js.map → chunk-62ZQQA7L.js.map} +1 -1
- package/dist/{chunk-HEF4BIMA.js → chunk-6GGHM33Z.js} +4 -4
- package/dist/{chunk-HEF4BIMA.js.map → chunk-6GGHM33Z.js.map} +1 -1
- package/dist/{chunk-KMSEU6FK.js → chunk-7DGJDISO.js} +3 -3
- package/dist/{chunk-KMSEU6FK.js.map → chunk-7DGJDISO.js.map} +1 -1
- package/dist/{chunk-2OYV6K7D.cjs → chunk-7JM5EZF3.cjs} +13 -13
- package/dist/{chunk-2OYV6K7D.cjs.map → chunk-7JM5EZF3.cjs.map} +1 -1
- package/dist/chunk-AKDJKMAL.cjs +48 -0
- package/dist/chunk-AKDJKMAL.cjs.map +1 -0
- package/dist/{chunk-HZL7QMXK.js → chunk-AWS4BWEC.js} +7 -3
- package/dist/chunk-AWS4BWEC.js.map +1 -0
- package/dist/{chunk-5DVDHL7Y.js → chunk-AZDVL7IM.js} +20 -6
- package/dist/chunk-AZDVL7IM.js.map +1 -0
- package/dist/{chunk-2R74OU76.cjs → chunk-CGZLENU4.cjs} +276 -16
- package/dist/chunk-CGZLENU4.cjs.map +1 -0
- package/dist/{chunk-G7IUQKRU.cjs → chunk-CLKU3ZIU.cjs} +51 -51
- package/dist/{chunk-G7IUQKRU.cjs.map → chunk-CLKU3ZIU.cjs.map} +1 -1
- package/dist/{chunk-MCIBQ5BF.js → chunk-DURFRWAW.js} +9 -9
- package/dist/{chunk-MCIBQ5BF.js.map → chunk-DURFRWAW.js.map} +1 -1
- package/dist/{chunk-C5S75476.js → chunk-EAKO7PGC.js} +8 -4
- package/dist/{chunk-C5S75476.js.map → chunk-EAKO7PGC.js.map} +1 -1
- package/dist/{chunk-IPCWYKX5.cjs → chunk-EWARI452.cjs} +60 -46
- package/dist/chunk-EWARI452.cjs.map +1 -0
- package/dist/{chunk-C6IQCKJT.cjs → chunk-FCQYMPUQ.cjs} +4 -4
- package/dist/{chunk-C6IQCKJT.cjs.map → chunk-FCQYMPUQ.cjs.map} +1 -1
- package/dist/{chunk-WVACGZYV.cjs → chunk-H7VMJBNZ.cjs} +8 -8
- package/dist/{chunk-WVACGZYV.cjs.map → chunk-H7VMJBNZ.cjs.map} +1 -1
- package/dist/{chunk-SEEQ3H22.cjs → chunk-HWJE4FNS.cjs} +59 -6
- package/dist/chunk-HWJE4FNS.cjs.map +1 -0
- package/dist/{chunk-3633VD2M.cjs → chunk-IKP4GOWZ.cjs} +8 -8
- package/dist/{chunk-3633VD2M.cjs.map → chunk-IKP4GOWZ.cjs.map} +1 -1
- package/dist/{chunk-5R6LTKE5.cjs → chunk-ILMHITHK.cjs} +5 -5
- package/dist/{chunk-5R6LTKE5.cjs.map → chunk-ILMHITHK.cjs.map} +1 -1
- package/dist/chunk-IOET54EV.js +39 -0
- package/dist/chunk-IOET54EV.js.map +1 -0
- package/dist/{chunk-ZAK276QF.js → chunk-JHTYULY2.js} +4 -4
- package/dist/{chunk-ZAK276QF.js.map → chunk-JHTYULY2.js.map} +1 -1
- package/dist/{chunk-OVIIJVXH.cjs → chunk-JO3XSUO2.cjs} +21 -21
- package/dist/{chunk-OVIIJVXH.cjs.map → chunk-JO3XSUO2.cjs.map} +1 -1
- package/dist/{chunk-UWMXMLMV.js → chunk-MROKQP4U.js} +3 -3
- package/dist/{chunk-UWMXMLMV.js.map → chunk-MROKQP4U.js.map} +1 -1
- package/dist/{chunk-J4CVGAAV.cjs → chunk-NZRG5CXQ.cjs} +7 -2
- package/dist/chunk-NZRG5CXQ.cjs.map +1 -0
- package/dist/{chunk-KM35K2M5.cjs → chunk-O7DXNX5J.cjs} +92 -25
- package/dist/chunk-O7DXNX5J.cjs.map +1 -0
- package/dist/chunk-OWNPYQSH.cjs +283 -0
- package/dist/chunk-OWNPYQSH.cjs.map +1 -0
- package/dist/{chunk-FIYVKW7F.cjs → chunk-PFXPAWPQ.cjs} +12 -12
- package/dist/{chunk-FIYVKW7F.cjs.map → chunk-PFXPAWPQ.cjs.map} +1 -1
- package/dist/chunk-QSWUSXRL.cjs +53 -0
- package/dist/chunk-QSWUSXRL.cjs.map +1 -0
- package/dist/{chunk-MGJR5OXO.js → chunk-RX7WII6I.js} +5 -5
- package/dist/{chunk-MGJR5OXO.js.map → chunk-RX7WII6I.js.map} +1 -1
- package/dist/chunk-S7FCFQ6X.js +255 -0
- package/dist/chunk-S7FCFQ6X.js.map +1 -0
- package/dist/{chunk-YBZQXZ6A.js → chunk-ST4WQ6ND.js} +68 -8
- package/dist/chunk-ST4WQ6ND.js.map +1 -0
- package/dist/{chunk-LKCPFD5X.js → chunk-SWVGHAYO.js} +5 -3
- package/dist/chunk-SWVGHAYO.js.map +1 -0
- package/dist/{chunk-MTUNORQB.cjs → chunk-TSKYEREJ.cjs} +11 -11
- package/dist/{chunk-MTUNORQB.cjs.map → chunk-TSKYEREJ.cjs.map} +1 -1
- package/dist/{chunk-LYWJAXPT.js → chunk-UMPZR56R.js} +3 -3
- package/dist/{chunk-LYWJAXPT.js.map → chunk-UMPZR56R.js.map} +1 -1
- package/dist/{chunk-6HUWQLF2.cjs → chunk-WKCFTWLO.cjs} +6 -6
- package/dist/{chunk-6HUWQLF2.cjs.map → chunk-WKCFTWLO.cjs.map} +1 -1
- package/dist/chunk-XPUGMYAJ.cjs +27 -0
- package/dist/{chunk-HD45Y7QU.cjs.map → chunk-XPUGMYAJ.cjs.map} +1 -1
- package/dist/{chunk-G5NTNQ7W.cjs → chunk-XROE3CAS.cjs} +5 -3
- package/dist/chunk-XROE3CAS.cjs.map +1 -0
- package/dist/{chunk-SZUDEFX2.cjs → chunk-ZXDH3L3P.cjs} +43 -39
- package/dist/{chunk-SZUDEFX2.cjs.map → chunk-ZXDH3L3P.cjs.map} +1 -1
- package/dist/{chunk-25KAGSPT.js → chunk-ZYITB47P.js} +3 -3
- package/dist/{chunk-25KAGSPT.js.map → chunk-ZYITB47P.js.map} +1 -1
- package/dist/entries/apps.cjs +43 -42
- package/dist/entries/apps.js +8 -7
- package/dist/entries/credits.cjs +151 -150
- package/dist/entries/credits.d.cts +4 -1
- package/dist/entries/credits.d.ts +4 -1
- package/dist/entries/credits.js +8 -7
- package/dist/entries/entities.cjs +125 -125
- package/dist/entries/entities.d.cts +1 -1
- package/dist/entries/entities.d.ts +1 -1
- package/dist/entries/entities.js +1 -1
- package/dist/entries/llm-models.d.cts +1 -1
- package/dist/entries/llm-models.d.ts +1 -1
- package/dist/entries/model-catalog.cjs +127 -66
- package/dist/entries/model-catalog.d.cts +61 -9
- package/dist/entries/model-catalog.d.ts +61 -9
- package/dist/entries/model-catalog.js +5 -4
- package/dist/entries/models.cjs +304 -276
- package/dist/entries/models.d.cts +3 -3
- package/dist/entries/models.d.ts +3 -3
- package/dist/entries/models.js +4 -4
- package/dist/entries/nodes.cjs +208 -207
- package/dist/entries/nodes.d.cts +1 -1
- package/dist/entries/nodes.d.ts +1 -1
- package/dist/entries/nodes.js +10 -9
- package/dist/entries/pipeline.cjs +161 -149
- package/dist/entries/pipeline.d.cts +165 -26
- package/dist/entries/pipeline.d.ts +165 -26
- package/dist/entries/pipeline.js +3 -3
- package/dist/entries/runtime-config.cjs +116 -0
- package/dist/entries/runtime-config.cjs.map +1 -0
- package/dist/entries/runtime-config.d.cts +308 -0
- package/dist/entries/runtime-config.d.ts +308 -0
- package/dist/entries/runtime-config.js +3 -0
- package/dist/entries/runtime-config.js.map +1 -0
- package/dist/entries/ugc.cjs +71 -71
- package/dist/entries/ugc.js +4 -4
- package/dist/entries/video.cjs +117 -117
- package/dist/entries/video.js +4 -4
- package/dist/entries/workflow.cjs +150 -146
- package/dist/entries/workflow.d.cts +8 -1
- package/dist/entries/workflow.d.ts +8 -1
- package/dist/entries/workflow.js +2 -2
- package/dist/index.cjs +3156 -2942
- package/dist/index.d.cts +6 -5
- package/dist/index.d.ts +6 -5
- package/dist/index.js +23 -21
- package/dist/{model-catalog-Dm2UiwUe.d.ts → model-catalog-vQ3NWn24.d.cts} +33 -2
- package/dist/{model-catalog-Dm2UiwUe.d.cts → model-catalog-vQ3NWn24.d.ts} +33 -2
- package/dist/{model-constants-DZUGVDOw.d.ts → model-constants-QZVHZX25.d.cts} +35 -6
- package/dist/{model-constants-DZUGVDOw.d.cts → model-constants-QZVHZX25.d.ts} +35 -6
- package/package.json +6 -1
- package/src/__tests__/fixtures/root-exports.baseline.json +2 -0
- package/src/__tests__/gpt-image-2-6.test.ts +277 -0
- package/src/__tests__/image-model-roles.test.ts +28 -9
- package/src/__tests__/runtime-config.test.ts +398 -0
- package/src/__tests__/voice-library-values.test.ts +24 -0
- package/src/credit-identifiers.ts +42 -0
- package/src/entries/model-catalog.ts +17 -0
- package/src/entries/models.ts +9 -0
- package/src/entries/runtime-config.ts +51 -0
- package/src/entries/workflow.ts +1 -1
- package/src/gpt-image-2-6.ts +104 -0
- package/src/image-model-roles.ts +31 -10
- package/src/index.ts +1 -0
- package/src/model-catalog.ts +302 -14
- package/src/model-constants.ts +84 -3
- package/src/node-default-mappings.ts +4 -0
- package/src/node-refs.ts +11 -0
- package/src/pipeline-types.ts +2 -0
- package/src/reference-board-templates.ts +2 -0
- package/src/runtime-config/contract.ts +492 -0
- package/src/runtime-config/worlds.ts +77 -0
- package/src/voices.ts +175 -2
- package/dist/chunk-2R74OU76.cjs.map +0 -1
- package/dist/chunk-3CHOZ573.js.map +0 -1
- package/dist/chunk-5DVDHL7Y.js.map +0 -1
- package/dist/chunk-ATWLKUAI.cjs +0 -34
- package/dist/chunk-ATWLKUAI.cjs.map +0 -1
- package/dist/chunk-DUL5ZLTJ.js +0 -29
- package/dist/chunk-DUL5ZLTJ.js.map +0 -1
- package/dist/chunk-G5NTNQ7W.cjs.map +0 -1
- package/dist/chunk-HD45Y7QU.cjs +0 -27
- package/dist/chunk-HZL7QMXK.js.map +0 -1
- package/dist/chunk-IPCWYKX5.cjs.map +0 -1
- package/dist/chunk-J4CVGAAV.cjs.map +0 -1
- package/dist/chunk-KM35K2M5.cjs.map +0 -1
- package/dist/chunk-LKCPFD5X.js.map +0 -1
- package/dist/chunk-N3WL6IOJ.js.map +0 -1
- package/dist/chunk-SEEQ3H22.cjs.map +0 -1
- package/dist/chunk-YBZQXZ6A.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ugc-call-body.ts","../src/ugc-lane-wires.ts"],"names":["pick","UGC_NEWER_APP_MESSAGE","ugcPlanLengthSec","UGC_SCRIPT_LANGUAGES","ugcPlanScreenshotCount","UGC_OVER_HOLD_MESSAGE","UGC_FINISH_NEEDS_CLIPS_MESSAGE","readUgcWire","UGC_NODE_MESSAGES","UGC_FINISH_NOT_READY_MESSAGE","UGC_NEEDS_FINISH_MESSA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A,MACP,MAAM,EAAE,QAAA,EAAU,aAAa,OAAO,CAAA,CAAE,QAAQ,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,CAAA,CAAE,GAAG,CAAA,IAAK,CAAA,CAAE,MAAM,CAAA,GAAI,CAAA,CAAE,MAAM,IAAA;AAAK,KACjH,CAAE;AAAA,GACJ;AACF;AAMO,SAAS,cAAA,CACd,KAAA,EACA,KAAA,EACA,OAAA,EACS;AACT,EAAA,MAAM,SAAA,GAAY,IAAI,GAAA,CAAI,KAAA,CAAM,OAAO,CAAC,CAAA,KAAM,EAAE,IAAA,KAAS,qBAAA,IAAyB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAQ,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,EAAY,CAAC,CAAA;AACtI,EAAA,OAAO,KAAA,CAAM,KAAK,CAAC,CAAA,KAAM,EAAE,MAAA,KAAW,OAAA,IAAW,EAAE,YAAA,KAAiB,UAAA,IAAc,EAAE,MAAA,KAAW,MAAA,IAAa,UAAU,GAAA,CAAI,CAAA,CAAE,MAAM,CAAA,IAAA,CAAM,CAAA,CAAE,YAAA,IAAgB,EAAA,MAAQ,MAAM,CAAA;AAC1K;AAGO,SAAS,kBAAA,CACd,KAAA,EACA,KAAA,EACA,OAAA,EACe;AACf,EAAA,OAAO,cAAA,CAAe,KAAA,EAAO,KAAA,EAAO,OAAO,IAAI,IAAA,GAAOS,0CAAA;AACxD","file":"chunk-OVIIJVXH.cjs","sourcesContent":["/**\n * A UGC builder call `{ tool, args }` (MCP argument names) → the REST body of\n * the public route that tool dispatches to. The builder sets every price lever;\n * this adds none — its one addition is the image of a call that needs the\n * previous step's image (`imageArg`, or the photo of `image_to_text`). A tool\n * it does not know → undefined, so an app older than the builder fails plainly\n * instead of guessing. Kept equal to the MCP verbs by ugc-call-body-parity.test.ts.\n */\nexport interface UgcToolCall {\n readonly tool: string\n readonly args: Readonly<Record<string, unknown>>\n readonly imageArg?: string\n}\nexport type UgcRouteBody = {\n readonly path: \"/v1/generate-image\" | \"/v1/image-to-image\" | \"/v1/image-to-text/describe\"\n readonly body: Record<string, unknown>\n}\n\nconst pick = (a: Readonly<Record<string, unknown>>, from: string, to: string): Record<string, unknown> =>\n a[from] !== undefined && a[from] !== null ? { [to]: a[from] } : {}\n\n/** The LLM levers image_to_text forwards (the verb's llmPayloadFields). */\nfunction llmFields(a: Readonly<Record<string, unknown>>): Record<string, unknown> {\n return {\n ...pick(a, \"llmModel\", \"llmModel\"),\n ...pick(a, \"reasoning_effort\", \"reasoningEffort\"),\n ...(a.advanced_mode === true ? { advancedMode: true } : {}),\n ...pick(a, \"temperature\", \"temperature\"),\n ...pick(a, \"max_tokens\", \"maxTokens\"),\n }\n}\n\nexport function ugcCallToRouteBody(\n call: UgcToolCall,\n opts: { readonly image?: string } = {},\n): UgcRouteBody | { readonly error: string } | undefined {\n const args: Record<string, unknown> = { ...call.args }\n if (call.imageArg) {\n if (!opts.image) return { error: `${call.tool} needs the previous step's image` }\n args[call.imageArg] = opts.image\n }\n switch (call.tool) {\n case \"generate_image\":\n return {\n path: \"/v1/generate-image\",\n body: {\n ...pick(args, \"prompt\", \"prompt\"),\n ...pick(args, \"model\", \"provider\"),\n ...pick(args, \"aspect_ratio\", \"aspectRatio\"),\n ...pick(args, \"resolution\", \"resolution\"),\n ...pick(args, \"quality\", \"quality\"),\n ...pick(args, \"negative_prompt\", \"negativePrompt\"),\n },\n }\n case \"image_to_image\":\n return {\n path: \"/v1/image-to-image\",\n body: {\n ...pick(args, \"image_url\", \"imageUrl\"),\n ...pick(args, \"prompt\", \"prompt\"),\n ...pick(args, \"model\", \"provider\"),\n ...pick(args, \"resolution\", \"resolution\"),\n ...pick(args, \"quality\", \"quality\"),\n ...pick(args, \"strength\", \"strength\"),\n ...pick(args, \"aspect_ratio\", \"aspectRatio\"),\n ...pick(args, \"negative_prompt\", \"negativePrompt\"),\n ...pick(args, \"seed\", \"seed\"),\n },\n }\n case \"image_to_text\": {\n const image = opts.image ?? (typeof args.image_url === \"string\" ? args.image_url : undefined)\n if (!image) return { error: \"image_to_text needs an image\" }\n return {\n path: \"/v1/image-to-text/describe\",\n body: {\n imageUrl: image,\n ...pick(args, \"detail_level\", \"detailLevel\"),\n ...pick(args, \"custom_prompt\", \"customPrompt\"),\n ...llmFields(args),\n },\n }\n }\n default:\n return undefined\n }\n}\n","/**\n * The UGC wires of a language whose clips are cut from one recorded speech (the\n * segmented lane): UGC Clips' prelude (record the speech, time its words, split\n * it at its pauses, then ask for the clips again with the segments) and UGC\n * Finish (lay the speech back over the rendered clips and trim the dead air,\n * as one job over all of them). One pure implementation both engines call, as\n * the rest of the UGC wires (`ugc-node-wires.ts`).\n *\n * Content-free: an answer is read only for `phase`, its three calls' `tool`\n * and `args` (argument names, never their meaning), the `finish` call's\n * `args`, and a finished job's clip list. Which language takes this lane, which\n * voice speaks and what the calls say are the builder's.\n */\nimport {\n UGC_FINISH_NEEDS_CLIPS_MESSAGE,\n UGC_FINISH_NOT_READY_MESSAGE,\n UGC_NEEDS_FINISH_MESSAGE,\n UGC_NEWER_APP_MESSAGE,\n UGC_NODE_MESSAGES,\n UGC_OVER_HOLD_MESSAGE,\n UGC_SCRIPT_LANGUAGES,\n readUgcWire,\n ugcPlanLengthSec,\n ugcPlanScreenshotCount,\n} from \"./ugc-node-wires.js\"\nimport type { FanOutItemMeta } from \"./fan-out-meta.js\"\n\ntype Obj = Record<string, unknown>\nconst isObject = (x: unknown): x is Obj => !!x && typeof x === \"object\" && !Array.isArray(x)\n\n/** UGC Finish's node type. Not the plugin job it runs (`ugc-finish`): a price, a dispatch or a reconcile keyed on a type never confuses the two. */\nexport const UGC_FINISH_CLIPS_TYPE = \"ugc-finish-clips\"\n\n/** The child steps of UGC Clips' prelude, in run order: each is a job of its own, keyed by its step. */\nexport const UGC_PRELUDE_STEPS = [\"speech\", \"alignment\", \"split\"] as const\nexport type UgcPreludeStep = (typeof UGC_PRELUDE_STEPS)[number]\n\n/** The public route each prelude step runs on, and the node type its job is read as. */\nexport const UGC_PRELUDE_ROUTES: Readonly<Record<UgcPreludeStep, { readonly path: string; readonly jobType: string }>> = {\n speech: { path: \"/v1/text-to-speech\", jobType: \"text-to-speech\" },\n alignment: { path: \"/v1/forced-alignment\", jobType: \"forced-alignment\" },\n split: { path: \"/v1/ugc/segments\", jobType: \"ugc-segments\" },\n}\n\n/** The `/v1/ugc/clips` answer's phase: 1 = the prelude must run first, 2 = the clips; null = an answer with no phase (one call, as English). */\nexport function ugcClipsPhase(answer: Readonly<Obj>): 1 | 2 | null {\n return answer.phase === 1 ? 1 : answer.phase === 2 ? 2 : null\n}\n\nconst callOf = (raw: unknown, tool: string): Obj | undefined => {\n if (!isObject(raw) || raw.tool !== tool || !isObject(raw.args)) return undefined\n return raw.args\n}\nconst pick = (a: Readonly<Obj>, from: string, to: string): Obj => (a[from] !== undefined && a[from] !== null ? { [to]: a[from] } : {})\n\n/** What the prelude runs: the speech's route body, and the two that need the step before them. */\nexport interface UgcPrelude {\n readonly speech: Obj\n readonly alignment: (audioUrl: string) => Obj\n readonly split: (audioUrl: string, alignment: unknown) => Obj\n}\n\n/**\n * A phase-1 answer's three calls (`speech`, `align`, `split`, MCP argument names) → the REST bodies of\n * the public routes their MCP tools dispatch to: `generate_speech` → `/v1/text-to-speech` (text, voice,\n * voice type, model as provider, language code, as the verb maps them), `forced_alignment` →\n * `/v1/forced-alignment` (the transcript, with the speech's audio), `ugc_split_speech` →\n * `/v1/ugc/segments` (the plan, with the speech's audio and its word timings). A call that is missing\n * or names another tool → the newer-app sentence: the app never guesses.\n */\nexport function ugcPrelude(answer: Readonly<Obj>): UgcPrelude | { readonly error: string } {\n const speech = callOf(answer.speech, \"generate_speech\")\n const align = callOf(answer.align, \"forced_alignment\")\n const split = callOf(answer.split, \"ugc_split_speech\")\n if (!speech || !align || !split || typeof speech.text !== \"string\" || !isObject(split.plan)) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n speech: {\n text: speech.text,\n ...pick(speech, \"voice_id\", \"voice\"),\n ...pick(speech, \"voice_type\", \"voiceType\"),\n ...pick(speech, \"model\", \"provider\"),\n ...pick(speech, \"language_code\", \"languageCode\"),\n },\n alignment: (audioUrl) => ({ ...pick(align, \"transcript\", \"transcript\"), audioUrl }),\n split: (audioUrl, alignment) => ({ plan: split.plan, audioUrl, alignment }),\n }\n}\n\n/** The finished speech job's audio, its word timings and its segments, as their jobs write them. */\nexport function ugcPreludeOutput(step: UgcPreludeStep, output: Readonly<Obj> | undefined): { value: unknown } | { error: string } {\n const value = step === \"speech\" ? output?.audioUrl : step === \"alignment\" ? output?.alignment : output?.segments\n const ok = step === \"speech\" ? typeof value === \"string\" && value !== \"\" : Array.isArray(value) && value.length > 0\n return ok ? { value } : { error: UGC_NEWER_APP_MESSAGE }\n}\n\n/** The second `/v1/ugc/clips` call: the first call's body with the segments the split returned. */\nexport function ugcClipsPhase2Body(body: Readonly<Obj>, segments: readonly unknown[]): Obj {\n return { ...body, segments: [...segments] }\n}\n\n// ── The hold check once the speech is split ──────────────────────────────────\n\n/** The estimate input of a video cut from one recorded speech, as the hold check names it (`runEstimate`). */\nexport interface UgcRunEstimateInput {\n readonly targetDurationSec: number\n readonly screenshotCount: number\n readonly source: \"sampled\"\n readonly language: string\n}\n\n/**\n * The estimate input of the video a UGC Clips run belongs to, read from the plan the node was sent: its\n * length, its screenshot cards and its language — the reading a kept plan is priced with. Read on a\n * phase-1 answer, before the prelude spends anything, so a plan the check cannot read refuses the run\n * while nothing is paid. The creator's source prices no clip, so it is not read. A plan without a length,\n * or without a language this lane takes → the newer-app sentence: the check never guesses.\n */\nexport function ugcRunEstimateInput(plan: unknown): { runEstimate: UgcRunEstimateInput } | { error: string } {\n const targetDurationSec = ugcPlanLengthSec(plan)\n const language = planOf(plan)?.language\n if (targetDurationSec === undefined || typeof language !== \"string\" || language === \"en\" || !(UGC_SCRIPT_LANGUAGES as readonly unknown[]).includes(language)) {\n return { error: UGC_NEWER_APP_MESSAGE }\n }\n return { runEstimate: { targetDurationSec, screenshotCount: ugcPlanScreenshotCount(plan) ?? 0, source: \"sampled\", language } }\n}\n\n/**\n * The quote that checks a video cut from one recorded speech before any of its clips renders: the clips\n * the second `/v1/ugc/clips` call handed on, priced as the UGC Clips quote prices them (`tickets`,\n * `hasCards`, `finishes`), with `runEstimate` (`ugcRunEstimateInput`). The route then also answers\n * `runHold`, the most the video's estimate holds for the clips and the steps after them, which the run's\n * balance was checked against before it started (`ugcRenderHoldVerdict`). No clips → the newer-app sentence.\n */\nexport function ugcRenderHoldBody(input: { runEstimate: UgcRunEstimateInput; tickets: unknown; hasCards: boolean; finishes: boolean }): { path: \"/v1/ugc/quote\"; body: Obj } | { error: string } {\n if (!Array.isArray(input.tickets) || input.tickets.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n path: \"/v1/ugc/quote\",\n body: {\n tickets: [...input.tickets],\n hasCards: input.hasCards,\n ...(input.finishes ? { finishes: true } : {}),\n runEstimate: { ...input.runEstimate },\n },\n }\n}\n\n/** A plan, or its wire (a JSON string), as an object; undefined for anything else. */\nfunction planOf(plan: unknown): Obj | undefined {\n if (typeof plan !== \"string\") return isObject(plan) ? plan : undefined\n try {\n const parsed: unknown = JSON.parse(plan)\n return isObject(parsed) ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\nconst isCredits = (x: unknown): x is number => typeof x === \"number\" && Number.isFinite(x) && x >= 0\n\n/**\n * The hold check's answer → go on, or stop before any clip renders: the clips and the steps after them\n * (`ceiling`, each clip at its hold) over what the run was checked for (`runHold`) → the over-hold\n * sentence. An answer without both figures stops too (the newer-app sentence): a clip never renders\n * on a figure nobody checked.\n */\nexport function ugcRenderHoldVerdict(answer: unknown): { readonly ok: true } | { readonly error: string } {\n if (!isObject(answer) || !isCredits(answer.ceiling) || !isCredits(answer.runHold)) return { error: UGC_NEWER_APP_MESSAGE }\n return answer.ceiling > answer.runHold ? { error: UGC_OVER_HOLD_MESSAGE } : { ok: true }\n}\n\n// ── UGC Finish ───────────────────────────────────────────────────────────────\n\n/** What UGC Finish does with the clips it was handed. */\nexport type UgcFinishPlan =\n /** No finish call on the plan (English): the clips go on as they came, no call, no job. */\n | { readonly kind: \"pass\"; readonly clips: readonly string[] }\n /** The finish job's body: the segments with their room, one roll per clip, in order. */\n | { readonly kind: \"job\"; readonly path: \"/v1/ugc/finish\"; readonly body: Obj }\n\n/**\n * UGC Finish's input → what it does. The `plan` input is UGC Clips' Script (sized) output; a plan\n * carrying `finish` (the segmented lane) asks for the finish job over the clips, in order; any other\n * plan passes the clips through. Clips are the fan-in list (`inputs.inputs`), in clip order.\n */\nexport function ugcFinishPlan(input: { planOutWire: unknown; clipUrls: readonly unknown[] }): UgcFinishPlan | { readonly error: string } {\n const clips = input.clipUrls.filter((u): u is string => typeof u === \"string\" && u !== \"\")\n if (clips.length === 0) return { error: UGC_FINISH_NEEDS_CLIPS_MESSAGE }\n const read = readUgcWire(input.planOutWire, UGC_NODE_MESSAGES.needsPlanOut)\n if (\"error\" in read) return read\n const finish = read.value.finish\n if (finish === undefined) return { kind: \"pass\", clips }\n if (!isObject(finish) || !Array.isArray(finish.segments) || finish.segments.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n if (finish.segments.length !== clips.length) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n kind: \"job\",\n path: \"/v1/ugc/finish\",\n body: { segments: finish.segments, clips: clips.map((url, i) => ({ clip: i + 1, rolls: [url] })) },\n }\n}\n\n/** A finished clip, as UGC Finish hands it on: its URL and the notes its downstream nodes read. */\nexport interface UgcFinishedClip { readonly url: string; readonly meta: FanOutItemMeta }\n\n/**\n * A finished `ugc-finish` job → the finished clips in clip order, each with its real length. `ready: false`\n * (a clip that does not follow its speech) → the not-ready sentence: the node fails, never hands on a\n * partial list. A dry finish's warning rides every clip's notes.\n */\nexport function ugcFinishOutputs(output: Readonly<Obj> | undefined): { clips: UgcFinishedClip[] } | { error: string } {\n if (!output) return { error: UGC_NEWER_APP_MESSAGE }\n if (output.ready === false) return { error: UGC_FINISH_NOT_READY_MESSAGE }\n if (output.ready !== true || !Array.isArray(output.clips) || output.clips.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n const warnings = Array.isArray(output.warnings)\n ? output.warnings.flatMap((w) => (isObject(w) && typeof w.code === \"string\" ? [w.code] : typeof w === \"string\" ? [w] : []))\n : []\n const rows = [...output.clips].filter(isObject).sort((a, b) => Number(a.clip) - Number(b.clip))\n if (rows.length !== output.clips.length || rows.some((r, i) => r.clip !== i + 1 || typeof r.url !== \"string\" || r.url === \"\")) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n clips: rows.map((r) => ({\n url: r.url as string,\n meta: { warnings, durationSec: typeof r.sec === \"number\" && Number.isFinite(r.sec) && r.sec > 0 ? r.sec : null },\n })),\n }\n}\n\n/**\n * Whether a UGC Finish reads this UGC Clips node's Script (sized) output: the graph can finish a video\n * whose clips are cut from one recorded speech. Read before the prelude spends anything.\n */\nexport function ugcFinishWired(\n edges: ReadonlyArray<{ readonly source?: string; readonly target?: string; readonly sourceHandle?: string | null; readonly targetHandle?: string | null }>,\n nodes: ReadonlyArray<{ readonly id?: string; readonly type?: string | null }>,\n clipsId: string,\n): boolean {\n const finishIds = new Set(nodes.filter((n) => n.type === UGC_FINISH_CLIPS_TYPE && typeof n.id === \"string\").map((n) => n.id as string))\n return edges.some((e) => e.source === clipsId && e.sourceHandle === \"plan-out\" && e.target !== undefined && finishIds.has(e.target) && (e.targetHandle ?? \"\") === \"plan\")\n}\n\n/** UGC Clips' refusal before its prelude: the sentence when no UGC Finish reads its Script (sized) output, else null. */\nexport function ugcLaneNeedsFinish(\n edges: Parameters<typeof ugcFinishWired>[0],\n nodes: Parameters<typeof ugcFinishWired>[1],\n clipsId: string,\n): string | null {\n return ugcFinishWired(edges, nodes, clipsId) ? null : UGC_NEEDS_FINISH_MESSAGE\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/ugc-call-body.ts","../src/ugc-lane-wires.ts"],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,QAAA,IAAY,CAAA,CAAE,GAAA,KAAQ,EAAE,CAAA,EAAG,OAAO,EAAE,KAAA,EAAOA,uCAAA,EAAsB;AACrK,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,MACtB,KAAK,CAAA,CAAE,GAAA;AAAA,MACP,MAAM,EAAE,QAAA,EAAU,aAAa,OAAO,CAAA,CAAE,QAAQ,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,CAAA,CAAE,GAAG,CAAA,IAAK,CAAA,CAAE,MAAM,CAAA,GAAI,CAAA,CAAE,MAAM,IAAA;AAAK,KACjH,CAAE;AAAA,GACJ;AACF;AAMO,SAAS,cAAA,CACd,KAAA,EACA,KAAA,EACA,OAAA,EACS;AACT,EAAA,MAAM,SAAA,GAAY,IAAI,GAAA,CAAI,KAAA,CAAM,OAAO,CAAC,CAAA,KAAM,EAAE,IAAA,KAAS,qBAAA,IAAyB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAQ,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,EAAY,CAAC,CAAA;AACtI,EAAA,OAAO,KAAA,CAAM,KAAK,CAAC,CAAA,KAAM,EAAE,MAAA,KAAW,OAAA,IAAW,EAAE,YAAA,KAAiB,UAAA,IAAc,EAAE,MAAA,KAAW,MAAA,IAAa,UAAU,GAAA,CAAI,CAAA,CAAE,MAAM,CAAA,IAAA,CAAM,CAAA,CAAE,YAAA,IAAgB,EAAA,MAAQ,MAAM,CAAA;AAC1K;AAGO,SAAS,kBAAA,CACd,KAAA,EACA,KAAA,EACA,OAAA,EACe;AACf,EAAA,OAAO,cAAA,CAAe,KAAA,EAAO,KAAA,EAAO,OAAO,IAAI,IAAA,GAAOS,0CAAA;AACxD","file":"chunk-JO3XSUO2.cjs","sourcesContent":["/**\n * A UGC builder call `{ tool, args }` (MCP argument names) → the REST body of\n * the public route that tool dispatches to. The builder sets every price lever;\n * this adds none — its one addition is the image of a call that needs the\n * previous step's image (`imageArg`, or the photo of `image_to_text`). A tool\n * it does not know → undefined, so an app older than the builder fails plainly\n * instead of guessing. Kept equal to the MCP verbs by ugc-call-body-parity.test.ts.\n */\nexport interface UgcToolCall {\n readonly tool: string\n readonly args: Readonly<Record<string, unknown>>\n readonly imageArg?: string\n}\nexport type UgcRouteBody = {\n readonly path: \"/v1/generate-image\" | \"/v1/image-to-image\" | \"/v1/image-to-text/describe\"\n readonly body: Record<string, unknown>\n}\n\nconst pick = (a: Readonly<Record<string, unknown>>, from: string, to: string): Record<string, unknown> =>\n a[from] !== undefined && a[from] !== null ? { [to]: a[from] } : {}\n\n/** The LLM levers image_to_text forwards (the verb's llmPayloadFields). */\nfunction llmFields(a: Readonly<Record<string, unknown>>): Record<string, unknown> {\n return {\n ...pick(a, \"llmModel\", \"llmModel\"),\n ...pick(a, \"reasoning_effort\", \"reasoningEffort\"),\n ...(a.advanced_mode === true ? { advancedMode: true } : {}),\n ...pick(a, \"temperature\", \"temperature\"),\n ...pick(a, \"max_tokens\", \"maxTokens\"),\n }\n}\n\nexport function ugcCallToRouteBody(\n call: UgcToolCall,\n opts: { readonly image?: string } = {},\n): UgcRouteBody | { readonly error: string } | undefined {\n const args: Record<string, unknown> = { ...call.args }\n if (call.imageArg) {\n if (!opts.image) return { error: `${call.tool} needs the previous step's image` }\n args[call.imageArg] = opts.image\n }\n switch (call.tool) {\n case \"generate_image\":\n return {\n path: \"/v1/generate-image\",\n body: {\n ...pick(args, \"prompt\", \"prompt\"),\n ...pick(args, \"model\", \"provider\"),\n ...pick(args, \"aspect_ratio\", \"aspectRatio\"),\n ...pick(args, \"resolution\", \"resolution\"),\n ...pick(args, \"quality\", \"quality\"),\n ...pick(args, \"negative_prompt\", \"negativePrompt\"),\n },\n }\n case \"image_to_image\":\n return {\n path: \"/v1/image-to-image\",\n body: {\n ...pick(args, \"image_url\", \"imageUrl\"),\n ...pick(args, \"prompt\", \"prompt\"),\n ...pick(args, \"model\", \"provider\"),\n ...pick(args, \"resolution\", \"resolution\"),\n ...pick(args, \"quality\", \"quality\"),\n ...pick(args, \"strength\", \"strength\"),\n ...pick(args, \"aspect_ratio\", \"aspectRatio\"),\n ...pick(args, \"negative_prompt\", \"negativePrompt\"),\n ...pick(args, \"seed\", \"seed\"),\n },\n }\n case \"image_to_text\": {\n const image = opts.image ?? (typeof args.image_url === \"string\" ? args.image_url : undefined)\n if (!image) return { error: \"image_to_text needs an image\" }\n return {\n path: \"/v1/image-to-text/describe\",\n body: {\n imageUrl: image,\n ...pick(args, \"detail_level\", \"detailLevel\"),\n ...pick(args, \"custom_prompt\", \"customPrompt\"),\n ...llmFields(args),\n },\n }\n }\n default:\n return undefined\n }\n}\n","/**\n * The UGC wires of a language whose clips are cut from one recorded speech (the\n * segmented lane): UGC Clips' prelude (record the speech, time its words, split\n * it at its pauses, then ask for the clips again with the segments) and UGC\n * Finish (lay the speech back over the rendered clips and trim the dead air,\n * as one job over all of them). One pure implementation both engines call, as\n * the rest of the UGC wires (`ugc-node-wires.ts`).\n *\n * Content-free: an answer is read only for `phase`, its three calls' `tool`\n * and `args` (argument names, never their meaning), the `finish` call's\n * `args`, and a finished job's clip list. Which language takes this lane, which\n * voice speaks and what the calls say are the builder's.\n */\nimport {\n UGC_FINISH_NEEDS_CLIPS_MESSAGE,\n UGC_FINISH_NOT_READY_MESSAGE,\n UGC_NEEDS_FINISH_MESSAGE,\n UGC_NEWER_APP_MESSAGE,\n UGC_NODE_MESSAGES,\n UGC_OVER_HOLD_MESSAGE,\n UGC_SCRIPT_LANGUAGES,\n readUgcWire,\n ugcPlanLengthSec,\n ugcPlanScreenshotCount,\n} from \"./ugc-node-wires.js\"\nimport type { FanOutItemMeta } from \"./fan-out-meta.js\"\n\ntype Obj = Record<string, unknown>\nconst isObject = (x: unknown): x is Obj => !!x && typeof x === \"object\" && !Array.isArray(x)\n\n/** UGC Finish's node type. Not the plugin job it runs (`ugc-finish`): a price, a dispatch or a reconcile keyed on a type never confuses the two. */\nexport const UGC_FINISH_CLIPS_TYPE = \"ugc-finish-clips\"\n\n/** The child steps of UGC Clips' prelude, in run order: each is a job of its own, keyed by its step. */\nexport const UGC_PRELUDE_STEPS = [\"speech\", \"alignment\", \"split\"] as const\nexport type UgcPreludeStep = (typeof UGC_PRELUDE_STEPS)[number]\n\n/** The public route each prelude step runs on, and the node type its job is read as. */\nexport const UGC_PRELUDE_ROUTES: Readonly<Record<UgcPreludeStep, { readonly path: string; readonly jobType: string }>> = {\n speech: { path: \"/v1/text-to-speech\", jobType: \"text-to-speech\" },\n alignment: { path: \"/v1/forced-alignment\", jobType: \"forced-alignment\" },\n split: { path: \"/v1/ugc/segments\", jobType: \"ugc-segments\" },\n}\n\n/** The `/v1/ugc/clips` answer's phase: 1 = the prelude must run first, 2 = the clips; null = an answer with no phase (one call, as English). */\nexport function ugcClipsPhase(answer: Readonly<Obj>): 1 | 2 | null {\n return answer.phase === 1 ? 1 : answer.phase === 2 ? 2 : null\n}\n\nconst callOf = (raw: unknown, tool: string): Obj | undefined => {\n if (!isObject(raw) || raw.tool !== tool || !isObject(raw.args)) return undefined\n return raw.args\n}\nconst pick = (a: Readonly<Obj>, from: string, to: string): Obj => (a[from] !== undefined && a[from] !== null ? { [to]: a[from] } : {})\n\n/** What the prelude runs: the speech's route body, and the two that need the step before them. */\nexport interface UgcPrelude {\n readonly speech: Obj\n readonly alignment: (audioUrl: string) => Obj\n readonly split: (audioUrl: string, alignment: unknown) => Obj\n}\n\n/**\n * A phase-1 answer's three calls (`speech`, `align`, `split`, MCP argument names) → the REST bodies of\n * the public routes their MCP tools dispatch to: `generate_speech` → `/v1/text-to-speech` (text, voice,\n * voice type, model as provider, language code, as the verb maps them), `forced_alignment` →\n * `/v1/forced-alignment` (the transcript, with the speech's audio), `ugc_split_speech` →\n * `/v1/ugc/segments` (the plan, with the speech's audio and its word timings). A call that is missing\n * or names another tool → the newer-app sentence: the app never guesses.\n */\nexport function ugcPrelude(answer: Readonly<Obj>): UgcPrelude | { readonly error: string } {\n const speech = callOf(answer.speech, \"generate_speech\")\n const align = callOf(answer.align, \"forced_alignment\")\n const split = callOf(answer.split, \"ugc_split_speech\")\n if (!speech || !align || !split || typeof speech.text !== \"string\" || !isObject(split.plan)) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n speech: {\n text: speech.text,\n ...pick(speech, \"voice_id\", \"voice\"),\n ...pick(speech, \"voice_type\", \"voiceType\"),\n ...pick(speech, \"model\", \"provider\"),\n ...pick(speech, \"language_code\", \"languageCode\"),\n },\n alignment: (audioUrl) => ({ ...pick(align, \"transcript\", \"transcript\"), audioUrl }),\n split: (audioUrl, alignment) => ({ plan: split.plan, audioUrl, alignment }),\n }\n}\n\n/** The finished speech job's audio, its word timings and its segments, as their jobs write them. */\nexport function ugcPreludeOutput(step: UgcPreludeStep, output: Readonly<Obj> | undefined): { value: unknown } | { error: string } {\n const value = step === \"speech\" ? output?.audioUrl : step === \"alignment\" ? output?.alignment : output?.segments\n const ok = step === \"speech\" ? typeof value === \"string\" && value !== \"\" : Array.isArray(value) && value.length > 0\n return ok ? { value } : { error: UGC_NEWER_APP_MESSAGE }\n}\n\n/** The second `/v1/ugc/clips` call: the first call's body with the segments the split returned. */\nexport function ugcClipsPhase2Body(body: Readonly<Obj>, segments: readonly unknown[]): Obj {\n return { ...body, segments: [...segments] }\n}\n\n// ── The hold check once the speech is split ──────────────────────────────────\n\n/** The estimate input of a video cut from one recorded speech, as the hold check names it (`runEstimate`). */\nexport interface UgcRunEstimateInput {\n readonly targetDurationSec: number\n readonly screenshotCount: number\n readonly source: \"sampled\"\n readonly language: string\n}\n\n/**\n * The estimate input of the video a UGC Clips run belongs to, read from the plan the node was sent: its\n * length, its screenshot cards and its language — the reading a kept plan is priced with. Read on a\n * phase-1 answer, before the prelude spends anything, so a plan the check cannot read refuses the run\n * while nothing is paid. The creator's source prices no clip, so it is not read. A plan without a length,\n * or without a language this lane takes → the newer-app sentence: the check never guesses.\n */\nexport function ugcRunEstimateInput(plan: unknown): { runEstimate: UgcRunEstimateInput } | { error: string } {\n const targetDurationSec = ugcPlanLengthSec(plan)\n const language = planOf(plan)?.language\n if (targetDurationSec === undefined || typeof language !== \"string\" || language === \"en\" || !(UGC_SCRIPT_LANGUAGES as readonly unknown[]).includes(language)) {\n return { error: UGC_NEWER_APP_MESSAGE }\n }\n return { runEstimate: { targetDurationSec, screenshotCount: ugcPlanScreenshotCount(plan) ?? 0, source: \"sampled\", language } }\n}\n\n/**\n * The quote that checks a video cut from one recorded speech before any of its clips renders: the clips\n * the second `/v1/ugc/clips` call handed on, priced as the UGC Clips quote prices them (`tickets`,\n * `hasCards`, `finishes`), with `runEstimate` (`ugcRunEstimateInput`). The route then also answers\n * `runHold`, the most the video's estimate holds for the clips and the steps after them, which the run's\n * balance was checked against before it started (`ugcRenderHoldVerdict`). No clips → the newer-app sentence.\n */\nexport function ugcRenderHoldBody(input: { runEstimate: UgcRunEstimateInput; tickets: unknown; hasCards: boolean; finishes: boolean }): { path: \"/v1/ugc/quote\"; body: Obj } | { error: string } {\n if (!Array.isArray(input.tickets) || input.tickets.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n path: \"/v1/ugc/quote\",\n body: {\n tickets: [...input.tickets],\n hasCards: input.hasCards,\n ...(input.finishes ? { finishes: true } : {}),\n runEstimate: { ...input.runEstimate },\n },\n }\n}\n\n/** A plan, or its wire (a JSON string), as an object; undefined for anything else. */\nfunction planOf(plan: unknown): Obj | undefined {\n if (typeof plan !== \"string\") return isObject(plan) ? plan : undefined\n try {\n const parsed: unknown = JSON.parse(plan)\n return isObject(parsed) ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\nconst isCredits = (x: unknown): x is number => typeof x === \"number\" && Number.isFinite(x) && x >= 0\n\n/**\n * The hold check's answer → go on, or stop before any clip renders: the clips and the steps after them\n * (`ceiling`, each clip at its hold) over what the run was checked for (`runHold`) → the over-hold\n * sentence. An answer without both figures stops too (the newer-app sentence): a clip never renders\n * on a figure nobody checked.\n */\nexport function ugcRenderHoldVerdict(answer: unknown): { readonly ok: true } | { readonly error: string } {\n if (!isObject(answer) || !isCredits(answer.ceiling) || !isCredits(answer.runHold)) return { error: UGC_NEWER_APP_MESSAGE }\n return answer.ceiling > answer.runHold ? { error: UGC_OVER_HOLD_MESSAGE } : { ok: true }\n}\n\n// ── UGC Finish ───────────────────────────────────────────────────────────────\n\n/** What UGC Finish does with the clips it was handed. */\nexport type UgcFinishPlan =\n /** No finish call on the plan (English): the clips go on as they came, no call, no job. */\n | { readonly kind: \"pass\"; readonly clips: readonly string[] }\n /** The finish job's body: the segments with their room, one roll per clip, in order. */\n | { readonly kind: \"job\"; readonly path: \"/v1/ugc/finish\"; readonly body: Obj }\n\n/**\n * UGC Finish's input → what it does. The `plan` input is UGC Clips' Script (sized) output; a plan\n * carrying `finish` (the segmented lane) asks for the finish job over the clips, in order; any other\n * plan passes the clips through. Clips are the fan-in list (`inputs.inputs`), in clip order.\n */\nexport function ugcFinishPlan(input: { planOutWire: unknown; clipUrls: readonly unknown[] }): UgcFinishPlan | { readonly error: string } {\n const clips = input.clipUrls.filter((u): u is string => typeof u === \"string\" && u !== \"\")\n if (clips.length === 0) return { error: UGC_FINISH_NEEDS_CLIPS_MESSAGE }\n const read = readUgcWire(input.planOutWire, UGC_NODE_MESSAGES.needsPlanOut)\n if (\"error\" in read) return read\n const finish = read.value.finish\n if (finish === undefined) return { kind: \"pass\", clips }\n if (!isObject(finish) || !Array.isArray(finish.segments) || finish.segments.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n if (finish.segments.length !== clips.length) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n kind: \"job\",\n path: \"/v1/ugc/finish\",\n body: { segments: finish.segments, clips: clips.map((url, i) => ({ clip: i + 1, rolls: [url] })) },\n }\n}\n\n/** A finished clip, as UGC Finish hands it on: its URL and the notes its downstream nodes read. */\nexport interface UgcFinishedClip { readonly url: string; readonly meta: FanOutItemMeta }\n\n/**\n * A finished `ugc-finish` job → the finished clips in clip order, each with its real length. `ready: false`\n * (a clip that does not follow its speech) → the not-ready sentence: the node fails, never hands on a\n * partial list. A dry finish's warning rides every clip's notes.\n */\nexport function ugcFinishOutputs(output: Readonly<Obj> | undefined): { clips: UgcFinishedClip[] } | { error: string } {\n if (!output) return { error: UGC_NEWER_APP_MESSAGE }\n if (output.ready === false) return { error: UGC_FINISH_NOT_READY_MESSAGE }\n if (output.ready !== true || !Array.isArray(output.clips) || output.clips.length === 0) return { error: UGC_NEWER_APP_MESSAGE }\n const warnings = Array.isArray(output.warnings)\n ? output.warnings.flatMap((w) => (isObject(w) && typeof w.code === \"string\" ? [w.code] : typeof w === \"string\" ? [w] : []))\n : []\n const rows = [...output.clips].filter(isObject).sort((a, b) => Number(a.clip) - Number(b.clip))\n if (rows.length !== output.clips.length || rows.some((r, i) => r.clip !== i + 1 || typeof r.url !== \"string\" || r.url === \"\")) return { error: UGC_NEWER_APP_MESSAGE }\n return {\n clips: rows.map((r) => ({\n url: r.url as string,\n meta: { warnings, durationSec: typeof r.sec === \"number\" && Number.isFinite(r.sec) && r.sec > 0 ? r.sec : null },\n })),\n }\n}\n\n/**\n * Whether a UGC Finish reads this UGC Clips node's Script (sized) output: the graph can finish a video\n * whose clips are cut from one recorded speech. Read before the prelude spends anything.\n */\nexport function ugcFinishWired(\n edges: ReadonlyArray<{ readonly source?: string; readonly target?: string; readonly sourceHandle?: string | null; readonly targetHandle?: string | null }>,\n nodes: ReadonlyArray<{ readonly id?: string; readonly type?: string | null }>,\n clipsId: string,\n): boolean {\n const finishIds = new Set(nodes.filter((n) => n.type === UGC_FINISH_CLIPS_TYPE && typeof n.id === \"string\").map((n) => n.id as string))\n return edges.some((e) => e.source === clipsId && e.sourceHandle === \"plan-out\" && e.target !== undefined && finishIds.has(e.target) && (e.targetHandle ?? \"\") === \"plan\")\n}\n\n/** UGC Clips' refusal before its prelude: the sentence when no UGC Finish reads its Script (sized) output, else null. */\nexport function ugcLaneNeedsFinish(\n edges: Parameters<typeof ugcFinishWired>[0],\n nodes: Parameters<typeof ugcFinishWired>[1],\n clipsId: string,\n): string | null {\n return ugcFinishWired(edges, nodes, clipsId) ? null : UGC_NEEDS_FINISH_MESSAGE\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { INPUT_FIELD_MAP, canonicalExposedFieldKey } from './chunk-
|
|
1
|
+
import { INPUT_FIELD_MAP, canonicalExposedFieldKey } from './chunk-JHTYULY2.js';
|
|
2
2
|
|
|
3
3
|
// src/picker-restrictions.ts
|
|
4
4
|
var valuesOf = (v) => (Array.isArray(v) ? v : [v]).filter((x) => x !== void 0 && x !== null && x !== "").map(String);
|
|
@@ -139,5 +139,5 @@ function templateCategoryStoredValues(category) {
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
export { DEFAULT_TEMPLATE_CATEGORY, HANDLE_PORT_SEPARATOR, INPUT_FIELD_MAP2 as INPUT_FIELD_MAP, LEGACY_TEMPLATE_CATEGORIES, OAUTH_SCOPES, OUTPUT_FIELD_MAP, RECAST_SEGMENT_PACKS, TEMPLATE_CATEGORIES, applyHandleInputOverride, findRestrictedPickerValue, isHandleInputWired, isTemplateCategory, mergeExposedSettings, normalizeTemplateCategory, parseHandleId, resolveTemplateCategory, templateCategoryStoredValues };
|
|
142
|
-
//# sourceMappingURL=chunk-
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
142
|
+
//# sourceMappingURL=chunk-MROKQP4U.js.map
|
|
143
|
+
//# sourceMappingURL=chunk-MROKQP4U.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/picker-restrictions.ts","../src/component-types.ts","../src/oauth-scopes.ts","../src/recast-segment-packs.ts","../src/template-categories.ts"],"names":["INPUT_FIELD_MAP"],"mappings":";;;AAYA,IAAM,QAAA,GAAW,CAAC,CAAA,KAAA,CACf,KAAA,CAAM,QAAQ,CAAC,CAAA,GAAI,CAAA,GAAI,CAAC,CAAC,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AA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,OAAA,CAAQ,IAAI,KAAK,CAAA;AACvD;AAGO,SAAS,wBAAwB,KAAA,EAAgE;AACtG,EAAA,IAAI,KAAA,IAAS,MAAM,OAAO,MAAA;AAC1B,EAAA,IAAI,kBAAA,CAAmB,KAAK,CAAA,EAAG,OAAO,KAAA;AACtC,EAAA,OAAO,2BAA2B,KAAK,CAAA;AACzC;AAGO,SAAS,0BAA0B,KAAA,EAAoD;AAC5F,EAAA,OAAO,uBAAA,CAAwB,KAAK,CAAA,IAAK,yBAAA;AAC3C;AAOO,SAAS,6BAA6B,QAAA,EAAsC;AACjF,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,0BAA0B,CAAA,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,0BAAA,CAA2B,KAAK,CAAA,KAAM,QAAQ,CAAA;AACvH,EAAA,OAAO,CAAC,QAAA,EAAU,GAAG,MAAM,CAAA;AAC7B","file":"chunk-UWMXMLMV.js","sourcesContent":["import { canonicalExposedFieldKey } from \"./exposed-field-keys.js\"\nimport { INPUT_FIELD_MAP } from \"./presentation-utils.js\"\n\n/** What an app's picker card may restrict (stored in `presentationSettings.cardMeta[nodeId]`). */\nexport interface PickerCardRestrictions {\n readonly pickerAllowedValues?: readonly string[]\n readonly pickerAllowedValuesByField?: Readonly<Record<string, readonly string[]>>\n}\n\n// Every submitted value is checked, whatever its type — a number or object where a\n// catalog id belongs must be refused, not skipped. An unset / cleared pick (\"\" , null)\n// is no selection and passes (the node falls back to its default).\nconst valuesOf = (v: unknown): string[] =>\n (Array.isArray(v) ? v : [v]).filter((x) => x !== undefined && x !== null && x !== \"\").map(String)\n\n/**\n * The first submitted picker value an app's card restrictions forbid, as the\n * runner's 400 text; null when all pass. Runs on every app run — `run_app`,\n * the SDK and a hand-built body included — so a restriction is never UI-only.\n * A submitted key is read through `canonicalExposedFieldKey`, so a legacy\n * spelling cannot slip past a restriction written against the current field.\n */\nexport function findRestrictedPickerValue(input: {\n readonly cardMeta: Readonly<Record<string, PickerCardRestrictions | undefined>> | undefined\n readonly nodes: ReadonlyArray<{ readonly id: string; readonly type?: string }>\n readonly inputValues: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n}): string | null {\n if (!input.cardMeta || !input.inputValues) return null\n for (const node of input.nodes) {\n const meta = input.cardMeta[node.id]\n const submitted = input.inputValues[node.id]\n if (!meta || !submitted) continue\n const rules: Array<[string, readonly string[]]> = []\n const rep = node.type ? INPUT_FIELD_MAP[node.type]?.key : undefined\n if (rep && meta.pickerAllowedValues && meta.pickerAllowedValues.length > 0) rules.push([rep, meta.pickerAllowedValues])\n for (const [field, allowed] of Object.entries(meta.pickerAllowedValuesByField ?? {})) {\n if (allowed.length > 0) rules.push([field, allowed])\n }\n for (const [field, allowed] of rules) {\n for (const [key, raw] of Object.entries(submitted)) {\n if (canonicalExposedFieldKey(node.type, key) !== field) continue\n for (const value of valuesOf(raw)) {\n if (!allowed.includes(value)) return `Invalid value for ${field}: ${value}. Allowed: ${allowed.join(\", \")}`\n }\n }\n }\n }\n return null\n}\n","import { INPUT_FIELD_MAP as PRESENTATION_INPUT_MAP } from \"./presentation-utils.js\"\n\nexport interface ComponentHandle {\n id: string\n name: string\n type: \"image\" | \"video\" | \"audio\" | \"text\"\n required: boolean\n mediaPreview?: boolean\n fieldKey: string\n}\n\nexport interface ExposedSetting {\n nodeId: string\n field: string\n label: string\n type: \"select\" | \"text\" | \"number\" | \"toggle\" | \"aspect-ratio\"\n allowedValues?: unknown[]\n /** Full option list with labels for select fields (preferred over allowedValues). */\n options?: Array<{ value: string; label: string }>\n defaultValue: unknown\n /**\n * Set when the setting is one of the node's quick settings (the editor's bottom-bar levers): the node type,\n * so the consuming workflow can render the same control, and the node's own lever values its choices depend\n * on (its model, Draft, …), so the control offers what that model takes. Never prompts or results.\n */\n quick?: {\n nodeType: string\n context?: Record<string, string | number | boolean>\n }\n}\n\nexport interface ComponentMetadata {\n inputs: ComponentHandle[]\n outputs: ComponentHandle[]\n exposedSettings: ExposedSetting[]\n}\n\n/** Maps input node types to their data field key for inputOverrides (derived from presentation-utils) */\nexport const INPUT_FIELD_MAP: Record<string, string> = Object.fromEntries(\n Object.entries(PRESENTATION_INPUT_MAP).map(([k, v]) => [k, v.key]),\n)\n\n/** Separator used in component handle ids that target a specific port on a sub-workflow-input / sub-workflow-output node. */\nexport const HANDLE_PORT_SEPARATOR = \"::\"\n\n/**\n * Split a component handle id of the form `nodeId` or `nodeId::portId`.\n * Returns the literal nodeId when no separator is present.\n */\nexport function parseHandleId(handleId: string): { nodeId: string; portId?: string } {\n const sep = handleId.indexOf(HANDLE_PORT_SEPARATOR)\n if (sep < 0) return { nodeId: handleId }\n const portId = handleId.slice(sep + HANDLE_PORT_SEPARATOR.length)\n return { nodeId: handleId.slice(0, sep), portId: portId || undefined }\n}\n\n/**\n * Apply a value for a component input handle to the inputOverrides map.\n *\n * - Plain handles (id = nodeId) write to `inputOverrides[nodeId][fieldKey]`,\n * which the orchestrator shallow-merges into `node.data` at execution.\n * - Compound handles (id = nodeId::portId) write into\n * `inputOverrides[nodeId].__injectedPortValues[portId]`, the slot that\n * sub-workflow-input nodes read at runtime via output-extractor.\n *\n * Mutates the map in place so multi-port accumulation merges correctly when\n * iterating handles in a loop.\n */\nexport function applyHandleInputOverride(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n value: unknown,\n): void {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const existing = (inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined) ?? {}\n inputOverrides[nodeId] = {\n ...inputOverrides[nodeId],\n __injectedPortValues: { ...existing, [portId]: value },\n }\n } else {\n inputOverrides[nodeId] = { ...inputOverrides[nodeId], [handle.fieldKey]: value }\n }\n}\n\n/**\n * Has a value already been recorded for this handle in the inputOverrides map?\n * Used to skip fallback wiring when an upstream connection already supplied\n * the input.\n */\nexport function isHandleInputWired(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n): boolean {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const injected = inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined\n return injected?.[portId] !== undefined\n }\n return inputOverrides[nodeId]?.[handle.fieldKey] !== undefined\n}\n\n/** Maps output media types to NodeOutput field keys */\nexport const OUTPUT_FIELD_MAP: Record<string, string> = {\n image: \"imageUrl\",\n video: \"videoUrl\",\n audio: \"audioUrl\",\n text: \"text\",\n}\n\n/**\n * Merge exposed settings into inputOverrides format.\n * exposedSettings is keyed by \"nodeId:field\" -> value on the component node data.\n *\n * Connected inputs (already present in inputOverrides) always take priority\n * over exposed settings for the same node+field combination. This ensures\n * that mandatory upstream wires are never silently overwritten by stale\n * default / user-configured exposed-setting values.\n */\nexport function mergeExposedSettings(\n inputOverrides: Record<string, Record<string, unknown>>,\n exposedSettings: Record<string, unknown>,\n metadata: ComponentMetadata,\n): Record<string, Record<string, unknown>> {\n const merged = { ...inputOverrides }\n for (const setting of metadata.exposedSettings) {\n const key = `${setting.nodeId}:${setting.field}`\n const value = exposedSettings[key]\n if (value !== undefined) {\n // Skip if a connected input already provided this field\n if (merged[setting.nodeId]?.[setting.field] !== undefined) continue\n merged[setting.nodeId] = { ...merged[setting.nodeId], [setting.field]: value }\n }\n }\n return merged\n}\n","/**\n * The OAuth scopes a Nodaro token can carry — part of the public API contract\n * (published in the authorization server's `scopes_supported`, requested by\n * developer apps, typed in `@nodaro/sdk`). The server validates against this\n * list and the SDK types against it, so the two cannot drift.\n *\n * A scope in this list is published and handed to any Dynamic Client\n * Registration client that asks for everything, so add one in the same change\n * that makes something check it (see backend/src/lib/scopes.ts).\n */\nexport const OAUTH_SCOPES = [\n \"workflows:read\",\n \"workflows:write\",\n \"workflows:execute\",\n \"jobs:read\",\n \"assets:read\",\n \"assets:write\",\n \"credits:read\",\n \"apps:read\",\n \"pipelines:read\",\n \"pipelines:execute\",\n \"pipelines:approve\",\n \"presets:read\",\n \"workspaces:read\",\n \"workspaces:write\",\n] as const\n\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number]\n","/**\n * How a recast render packs scenes into parts — the values `segmentSec` takes\n * on `POST /v1/recast`, `/v1/recast/estimate` and `/v1/recast/:id/start`. A\n * name, not seconds, despite the field's name:\n *\n * - `\"scenes-max\"` (Long): whole scenes grouped into as few parts as fit, the\n * fewest seams.\n * - `\"scenes\"` (Short): whole scenes in shorter parts.\n * - `\"max\"`: the longest parts the model allows, not grouped by scene.\n */\nexport const RECAST_SEGMENT_PACKS = [\"max\", \"scenes-max\", \"scenes\"] as const\n\nexport type RecastSegmentPack = (typeof RECAST_SEGMENT_PACKS)[number]\n","/**\n * The use cases a marketplace template is filed under — exactly one each.\n * Shared by the publish/browse routes (the `category` enum), the Templates\n * page (tiles, URL filter, labels) and the publish dialog, so the list can\n * only change in one place. Labels live with the frontend's i18n\n * (`lib/template-categories.ts`), keyed by these values.\n */\nexport const TEMPLATE_CATEGORIES = [\n \"product-imagery\",\n \"static-ads\",\n \"user-generated-content\",\n \"video-ads\",\n \"brand-assets\",\n \"automations\",\n \"campaign-concepts\",\n \"social-creatives\",\n // Workflows an AI agent built through the MCP server, kept whole so every step can be opened and changed.\n \"mcp\",\n] as const\n\nexport type TemplateCategory = (typeof TEMPLATE_CATEGORIES)[number]\n\n/** Where a template with no usable category is filed: the plain \"it is a workflow\" bucket. */\nexport const DEFAULT_TEMPLATE_CATEGORY: TemplateCategory = \"automations\"\n\n/**\n * The categories templates were filed under before September 2026, each\n * read as its new home. Migration 423 rewrites the rows with the same map;\n * this keeps an old link (`?category=video-production`), a cached card and a\n * row the migration has not reached yet resolving in the meantime.\n */\nexport const LEGACY_TEMPLATE_CATEGORIES: Readonly<Record<string, TemplateCategory>> = {\n \"image-generation\": \"product-imagery\",\n \"video-production\": \"video-ads\",\n \"audio-music\": \"social-creatives\",\n \"content-writing\": \"campaign-concepts\",\n \"social-media\": \"social-creatives\",\n \"data-processing\": \"automations\",\n \"multi-step\": \"automations\",\n other: \"automations\",\n}\n\nconst CURRENT = new Set<string>(TEMPLATE_CATEGORIES)\n\nexport function isTemplateCategory(value: unknown): value is TemplateCategory {\n return typeof value === \"string\" && CURRENT.has(value)\n}\n\n/** A current category as is, a legacy one as its new home, anything else as undefined. */\nexport function resolveTemplateCategory(value: string | null | undefined): TemplateCategory | undefined {\n if (value == null) return undefined\n if (isTemplateCategory(value)) return value\n return LEGACY_TEMPLATE_CATEGORIES[value]\n}\n\n/** The category a stored row reads as: resolved, else the default bucket. */\nexport function normalizeTemplateCategory(value: string | null | undefined): TemplateCategory {\n return resolveTemplateCategory(value) ?? DEFAULT_TEMPLATE_CATEGORY\n}\n\n/**\n * Every stored value that reads as `category` — the value itself and the\n * legacy ones that map to it — so a database filter matches rows the\n * migration has not rewritten yet.\n */\nexport function templateCategoryStoredValues(category: TemplateCategory): string[] {\n const legacy = Object.keys(LEGACY_TEMPLATE_CATEGORIES).filter((value) => LEGACY_TEMPLATE_CATEGORIES[value] === category)\n return [category, ...legacy]\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/picker-restrictions.ts","../src/component-types.ts","../src/oauth-scopes.ts","../src/recast-segment-packs.ts","../src/template-categories.ts"],"names":["INPUT_FIELD_MAP"],"mappings":";;;AAYA,IAAM,QAAA,GAAW,CAAC,CAAA,KAAA,CACf,KAAA,CAAM,QAAQ,CAAC,CAAA,GAAI,CAAA,GAAI,CAAC,CAAC,CAAA,EAAG,OAAO,CAAC,CAAA,KAAM,MAAM,MAAA,IAAa,CAAA,KAAM,QAAQ,CAAA,KAAM,EAAE,CAAA,CAAE,GAAA,CAAI,MAAM,CAAA;AAS3F,SAAS,0BAA0B,KAAA,EAIxB;AAChB,EAAA,IAAI,CAAC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,aAAa,OAAO,IAAA;AAClD,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAM,KAAA,EAAO;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AC5F,EAAA,OAAO,uBAAA,CAAwB,KAAK,CAAA,IAAK,yBAAA;AAC3C;AAOO,SAAS,6BAA6B,QAAA,EAAsC;AACjF,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,0BAA0B,CAAA,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,0BAAA,CAA2B,KAAK,CAAA,KAAM,QAAQ,CAAA;AACvH,EAAA,OAAO,CAAC,QAAA,EAAU,GAAG,MAAM,CAAA;AAC7B","file":"chunk-MROKQP4U.js","sourcesContent":["import { canonicalExposedFieldKey } from \"./exposed-field-keys.js\"\nimport { INPUT_FIELD_MAP } from \"./presentation-utils.js\"\n\n/** What an app's picker card may restrict (stored in `presentationSettings.cardMeta[nodeId]`). */\nexport interface PickerCardRestrictions {\n readonly pickerAllowedValues?: readonly string[]\n readonly pickerAllowedValuesByField?: Readonly<Record<string, readonly string[]>>\n}\n\n// Every submitted value is checked, whatever its type — a number or object where a\n// catalog id belongs must be refused, not skipped. An unset / cleared pick (\"\" , null)\n// is no selection and passes (the node falls back to its default).\nconst valuesOf = (v: unknown): string[] =>\n (Array.isArray(v) ? v : [v]).filter((x) => x !== undefined && x !== null && x !== \"\").map(String)\n\n/**\n * The first submitted picker value an app's card restrictions forbid, as the\n * runner's 400 text; null when all pass. Runs on every app run — `run_app`,\n * the SDK and a hand-built body included — so a restriction is never UI-only.\n * A submitted key is read through `canonicalExposedFieldKey`, so a legacy\n * spelling cannot slip past a restriction written against the current field.\n */\nexport function findRestrictedPickerValue(input: {\n readonly cardMeta: Readonly<Record<string, PickerCardRestrictions | undefined>> | undefined\n readonly nodes: ReadonlyArray<{ readonly id: string; readonly type?: string }>\n readonly inputValues: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n}): string | null {\n if (!input.cardMeta || !input.inputValues) return null\n for (const node of input.nodes) {\n const meta = input.cardMeta[node.id]\n const submitted = input.inputValues[node.id]\n if (!meta || !submitted) continue\n const rules: Array<[string, readonly string[]]> = []\n const rep = node.type ? INPUT_FIELD_MAP[node.type]?.key : undefined\n if (rep && meta.pickerAllowedValues && meta.pickerAllowedValues.length > 0) rules.push([rep, meta.pickerAllowedValues])\n for (const [field, allowed] of Object.entries(meta.pickerAllowedValuesByField ?? {})) {\n if (allowed.length > 0) rules.push([field, allowed])\n }\n for (const [field, allowed] of rules) {\n for (const [key, raw] of Object.entries(submitted)) {\n if (canonicalExposedFieldKey(node.type, key) !== field) continue\n for (const value of valuesOf(raw)) {\n if (!allowed.includes(value)) return `Invalid value for ${field}: ${value}. Allowed: ${allowed.join(\", \")}`\n }\n }\n }\n }\n return null\n}\n","import { INPUT_FIELD_MAP as PRESENTATION_INPUT_MAP } from \"./presentation-utils.js\"\n\nexport interface ComponentHandle {\n id: string\n name: string\n type: \"image\" | \"video\" | \"audio\" | \"text\"\n required: boolean\n mediaPreview?: boolean\n fieldKey: string\n}\n\nexport interface ExposedSetting {\n nodeId: string\n field: string\n label: string\n type: \"select\" | \"text\" | \"number\" | \"toggle\" | \"aspect-ratio\"\n allowedValues?: unknown[]\n /** Full option list with labels for select fields (preferred over allowedValues). */\n options?: Array<{ value: string; label: string }>\n defaultValue: unknown\n /**\n * Set when the setting is one of the node's quick settings (the editor's bottom-bar levers): the node type,\n * so the consuming workflow can render the same control, and the node's own lever values its choices depend\n * on (its model, Draft, …), so the control offers what that model takes. Never prompts or results.\n */\n quick?: {\n nodeType: string\n context?: Record<string, string | number | boolean>\n }\n}\n\nexport interface ComponentMetadata {\n inputs: ComponentHandle[]\n outputs: ComponentHandle[]\n exposedSettings: ExposedSetting[]\n}\n\n/** Maps input node types to their data field key for inputOverrides (derived from presentation-utils) */\nexport const INPUT_FIELD_MAP: Record<string, string> = Object.fromEntries(\n Object.entries(PRESENTATION_INPUT_MAP).map(([k, v]) => [k, v.key]),\n)\n\n/** Separator used in component handle ids that target a specific port on a sub-workflow-input / sub-workflow-output node. */\nexport const HANDLE_PORT_SEPARATOR = \"::\"\n\n/**\n * Split a component handle id of the form `nodeId` or `nodeId::portId`.\n * Returns the literal nodeId when no separator is present.\n */\nexport function parseHandleId(handleId: string): { nodeId: string; portId?: string } {\n const sep = handleId.indexOf(HANDLE_PORT_SEPARATOR)\n if (sep < 0) return { nodeId: handleId }\n const portId = handleId.slice(sep + HANDLE_PORT_SEPARATOR.length)\n return { nodeId: handleId.slice(0, sep), portId: portId || undefined }\n}\n\n/**\n * Apply a value for a component input handle to the inputOverrides map.\n *\n * - Plain handles (id = nodeId) write to `inputOverrides[nodeId][fieldKey]`,\n * which the orchestrator shallow-merges into `node.data` at execution.\n * - Compound handles (id = nodeId::portId) write into\n * `inputOverrides[nodeId].__injectedPortValues[portId]`, the slot that\n * sub-workflow-input nodes read at runtime via output-extractor.\n *\n * Mutates the map in place so multi-port accumulation merges correctly when\n * iterating handles in a loop.\n */\nexport function applyHandleInputOverride(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n value: unknown,\n): void {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const existing = (inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined) ?? {}\n inputOverrides[nodeId] = {\n ...inputOverrides[nodeId],\n __injectedPortValues: { ...existing, [portId]: value },\n }\n } else {\n inputOverrides[nodeId] = { ...inputOverrides[nodeId], [handle.fieldKey]: value }\n }\n}\n\n/**\n * Has a value already been recorded for this handle in the inputOverrides map?\n * Used to skip fallback wiring when an upstream connection already supplied\n * the input.\n */\nexport function isHandleInputWired(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n): boolean {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const injected = inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined\n return injected?.[portId] !== undefined\n }\n return inputOverrides[nodeId]?.[handle.fieldKey] !== undefined\n}\n\n/** Maps output media types to NodeOutput field keys */\nexport const OUTPUT_FIELD_MAP: Record<string, string> = {\n image: \"imageUrl\",\n video: \"videoUrl\",\n audio: \"audioUrl\",\n text: \"text\",\n}\n\n/**\n * Merge exposed settings into inputOverrides format.\n * exposedSettings is keyed by \"nodeId:field\" -> value on the component node data.\n *\n * Connected inputs (already present in inputOverrides) always take priority\n * over exposed settings for the same node+field combination. This ensures\n * that mandatory upstream wires are never silently overwritten by stale\n * default / user-configured exposed-setting values.\n */\nexport function mergeExposedSettings(\n inputOverrides: Record<string, Record<string, unknown>>,\n exposedSettings: Record<string, unknown>,\n metadata: ComponentMetadata,\n): Record<string, Record<string, unknown>> {\n const merged = { ...inputOverrides }\n for (const setting of metadata.exposedSettings) {\n const key = `${setting.nodeId}:${setting.field}`\n const value = exposedSettings[key]\n if (value !== undefined) {\n // Skip if a connected input already provided this field\n if (merged[setting.nodeId]?.[setting.field] !== undefined) continue\n merged[setting.nodeId] = { ...merged[setting.nodeId], [setting.field]: value }\n }\n }\n return merged\n}\n","/**\n * The OAuth scopes a Nodaro token can carry — part of the public API contract\n * (published in the authorization server's `scopes_supported`, requested by\n * developer apps, typed in `@nodaro/sdk`). The server validates against this\n * list and the SDK types against it, so the two cannot drift.\n *\n * A scope in this list is published and handed to any Dynamic Client\n * Registration client that asks for everything, so add one in the same change\n * that makes something check it (see backend/src/lib/scopes.ts).\n */\nexport const OAUTH_SCOPES = [\n \"workflows:read\",\n \"workflows:write\",\n \"workflows:execute\",\n \"jobs:read\",\n \"assets:read\",\n \"assets:write\",\n \"credits:read\",\n \"apps:read\",\n \"pipelines:read\",\n \"pipelines:execute\",\n \"pipelines:approve\",\n \"presets:read\",\n \"workspaces:read\",\n \"workspaces:write\",\n] as const\n\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number]\n","/**\n * How a recast render packs scenes into parts — the values `segmentSec` takes\n * on `POST /v1/recast`, `/v1/recast/estimate` and `/v1/recast/:id/start`. A\n * name, not seconds, despite the field's name:\n *\n * - `\"scenes-max\"` (Long): whole scenes grouped into as few parts as fit, the\n * fewest seams.\n * - `\"scenes\"` (Short): whole scenes in shorter parts.\n * - `\"max\"`: the longest parts the model allows, not grouped by scene.\n */\nexport const RECAST_SEGMENT_PACKS = [\"max\", \"scenes-max\", \"scenes\"] as const\n\nexport type RecastSegmentPack = (typeof RECAST_SEGMENT_PACKS)[number]\n","/**\n * The use cases a marketplace template is filed under — exactly one each.\n * Shared by the publish/browse routes (the `category` enum), the Templates\n * page (tiles, URL filter, labels) and the publish dialog, so the list can\n * only change in one place. Labels live with the frontend's i18n\n * (`lib/template-categories.ts`), keyed by these values.\n */\nexport const TEMPLATE_CATEGORIES = [\n \"product-imagery\",\n \"static-ads\",\n \"user-generated-content\",\n \"video-ads\",\n \"brand-assets\",\n \"automations\",\n \"campaign-concepts\",\n \"social-creatives\",\n // Workflows an AI agent built through the MCP server, kept whole so every step can be opened and changed.\n \"mcp\",\n] as const\n\nexport type TemplateCategory = (typeof TEMPLATE_CATEGORIES)[number]\n\n/** Where a template with no usable category is filed: the plain \"it is a workflow\" bucket. */\nexport const DEFAULT_TEMPLATE_CATEGORY: TemplateCategory = \"automations\"\n\n/**\n * The categories templates were filed under before September 2026, each\n * read as its new home. Migration 423 rewrites the rows with the same map;\n * this keeps an old link (`?category=video-production`), a cached card and a\n * row the migration has not reached yet resolving in the meantime.\n */\nexport const LEGACY_TEMPLATE_CATEGORIES: Readonly<Record<string, TemplateCategory>> = {\n \"image-generation\": \"product-imagery\",\n \"video-production\": \"video-ads\",\n \"audio-music\": \"social-creatives\",\n \"content-writing\": \"campaign-concepts\",\n \"social-media\": \"social-creatives\",\n \"data-processing\": \"automations\",\n \"multi-step\": \"automations\",\n other: \"automations\",\n}\n\nconst CURRENT = new Set<string>(TEMPLATE_CATEGORIES)\n\nexport function isTemplateCategory(value: unknown): value is TemplateCategory {\n return typeof value === \"string\" && CURRENT.has(value)\n}\n\n/** A current category as is, a legacy one as its new home, anything else as undefined. */\nexport function resolveTemplateCategory(value: string | null | undefined): TemplateCategory | undefined {\n if (value == null) return undefined\n if (isTemplateCategory(value)) return value\n return LEGACY_TEMPLATE_CATEGORIES[value]\n}\n\n/** The category a stored row reads as: resolved, else the default bucket. */\nexport function normalizeTemplateCategory(value: string | null | undefined): TemplateCategory {\n return resolveTemplateCategory(value) ?? DEFAULT_TEMPLATE_CATEGORY\n}\n\n/**\n * Every stored value that reads as `category` — the value itself and the\n * legacy ones that map to it — so a database filter matches rows the\n * migration has not rewritten yet.\n */\nexport function templateCategoryStoredValues(category: TemplateCategory): string[] {\n const legacy = Object.keys(LEGACY_TEMPLATE_CATEGORIES).filter((value) => LEGACY_TEMPLATE_CATEGORIES[value] === category)\n return [category, ...legacy]\n}\n"]}
|
|
@@ -68,6 +68,10 @@ function countRefModalityEdges(edges, nodeId, modality) {
|
|
|
68
68
|
}
|
|
69
69
|
return n;
|
|
70
70
|
}
|
|
71
|
+
function countImageInputEdges(edges, nodeId) {
|
|
72
|
+
const onHandle = (handle) => edges.filter((e) => e.target === nodeId && e.targetHandle === handle).length;
|
|
73
|
+
return countRefModalityEdges(edges, nodeId, "image") + onHandle("assets") + Math.max(0, onHandle("image") - 1);
|
|
74
|
+
}
|
|
71
75
|
function combineSameLabelRefs(candidates) {
|
|
72
76
|
const byLabel = /* @__PURE__ */ new Map();
|
|
73
77
|
for (const c of candidates) {
|
|
@@ -1068,6 +1072,7 @@ exports.buildRangeLabel = buildRangeLabel;
|
|
|
1068
1072
|
exports.canonicalVarName = canonicalVarName;
|
|
1069
1073
|
exports.classifyRefToken = classifyRefToken;
|
|
1070
1074
|
exports.combineSameLabelRefs = combineSameLabelRefs;
|
|
1075
|
+
exports.countImageInputEdges = countImageInputEdges;
|
|
1071
1076
|
exports.countRefModalityEdges = countRefModalityEdges;
|
|
1072
1077
|
exports.describeEdgeBehavior = describeEdgeBehavior;
|
|
1073
1078
|
exports.evaluateCondition = evaluateCondition;
|
|
@@ -1099,5 +1104,5 @@ exports.stringifyPathResults = stringifyPathResults;
|
|
|
1099
1104
|
exports.stripTransientRuntimeData = stripTransientRuntimeData;
|
|
1100
1105
|
exports.tryParseJson = tryParseJson;
|
|
1101
1106
|
exports.unresolvedRefTokens = unresolvedRefTokens;
|
|
1102
|
-
//# sourceMappingURL=chunk-
|
|
1103
|
-
//# sourceMappingURL=chunk-
|
|
1107
|
+
//# sourceMappingURL=chunk-NZRG5CXQ.cjs.map
|
|
1108
|
+
//# sourceMappingURL=chunk-NZRG5CXQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node-refs.ts","../src/trigger-feeds.ts","../src/node-runtime-keys.ts","../src/json-path.ts","../src/filter-condition.ts","../src/selector.ts"],"names":["SUNO_SEPARATE_RESULT_FIELDS","SUNO_SEPARATE_META_FIELDS"],"mappings":";;;;;AAMO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,sBAAA,uBAA6B,GAAA,CAAI;AAAA,EAC5C,MAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAAC;AAUM,SAAS,aAAa,GAAA,EAAwD;AACnF,EAAA,MAAM,CAAA,GAAI,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA;AAC1B,EAAA,IAAI,CAAA,KAAM,IAAI,OAAO,EAAE,MAAM,GAAA,CAAI,IAAA,EAAK,EAAG,QAAA,EAAU,IAAA,EAAK;AACxD,EAAA,OAAO,EAAE,IAAA,EAAM,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,IAAA,EAAK,EAAG,QAAA,EAAU,IAAI,KAAA,CAAM,CAAA,GAAI,CAAC,CAAA,CAAE,MAAK,EAAE;AAC3E;AAYO,SAAS,iBAAiB,KAAA,EAAuB;AACtD,EAAA,OAAO,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AAClC;AAcO,SAAS,2BACX,KAAA,EACU;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,OAA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M,YAAA,GAAe,eAAA,CAAgB,CAAA,EAAG,SAAS,CAAA;AACjD,IAAA,OAAO,uBAAA,CAAwB,cAAc,WAAW,CAAA;AAAA,EAC1D,CAAA;AACA,EAAA,OAAO;AAAA,IACL,GAAG,MAAA;AAAA,IACH,aAAA,EAAe,OAAA,CAAQ,MAAA,CAAO,aAAa,CAAA;AAAA,IAC3C,cAAA,EAAgB,OAAA,CAAQ,MAAA,CAAO,cAAc,CAAA;AAAA,IAC7C,aAAA,EAAe,OAAA,CAAQ,MAAA,CAAO,aAAa,CAAA;AAAA,IAC3C,IAAA,EAAM,OAAA,CAAQ,MAAA,CAAO,IAAI;AAAA,GAC3B;AACF","file":"chunk-NZRG5CXQ.cjs","sourcesContent":["/**\n * Node reference pattern and resolution for {Node Label} template syntax.\n * Shared between frontend and backend.\n */\n\n/** Matches {Node Label} references in text. */\nexport const NODE_REF_PATTERN = /\\{([^}]+)\\}/g\n\n/** Reserved template variable names that should NOT be resolved as node refs */\nexport const RESERVED_TEMPLATE_VARS = new Set([\n \"name\",\n \"description\",\n \"userPrompt\",\n \"assetDescriptions\",\n \"outputCount\",\n])\n\n/**\n * Split a `{...}` token body into its node name and optional fallback. Splits on the FIRST `||`\n * (a fallback may itself contain `||`); both sides are trimmed. `fallback` is null when there is\n * no `||`, preserving the legacy \"leave the literal token\" behavior.\n * \"person || man\" -> { name: \"person\", fallback: \"man\" }\n * \"person || \" -> { name: \"person\", fallback: \"\" } (resolves to empty when absent)\n * \"person\" -> { name: \"person\", fallback: null } (literal {person} when absent)\n */\nexport function parseNodeRef(raw: string): { name: string; fallback: string | null } {\n const i = raw.indexOf(\"||\")\n if (i === -1) return { name: raw.trim(), fallback: null }\n return { name: raw.slice(0, i).trim(), fallback: raw.slice(i + 2).trim() }\n}\n\n/**\n * Canonical form of a node-name variable: trimmed + lowercased. Node-name\n * variables are CASE-INSENSITIVE with lowercase as canonical, so nodes labeled\n * `TEXt`, `TEXT`, `text` all feed the one `{text}` variable and `{TEXT}` /\n * `{Text}` / `{text}` in a prompt all resolve to it.\n *\n * Reserved template vars (RESERVED_TEMPLATE_VARS, e.g. `userPrompt`) are matched\n * case-sensitively on the ORIGINAL token BEFORE canonicalization, so `{userPrompt}`\n * stays a reserved token rather than becoming a `userprompt` node ref.\n */\nexport function canonicalVarName(label: string): string {\n return label.trim().toLowerCase()\n}\n\n/**\n * The distinct `{label}` names referenced across the given texts. Mirrors the\n * canvas-side `referencedRefs`: strips the `|| fallback`, and ignores empty\n * tokens, image-ref tokens (`{image:N}`), and RESERVED_TEMPLATE_VARS. Used to\n * SUPPRESS auto-injection of a connected node the author already placed\n * explicitly via `{label}` (so it isn't injected twice). `matchAll` over the\n * global pattern does not mutate its lastIndex, so sharing the constant is safe.\n *\n * Deliberately NOT `REF_TOKEN_NAMESPACE_PREFIXES`: widening this changes\n * run-time auto-injection on BOTH engines (follow-up ticket), not just the\n * editor.\n */\nexport function extractReferencedLabels(\n ...texts: ReadonlyArray<string | undefined | null>\n): Set<string> {\n const refs = new Set<string>()\n for (const text of texts) {\n if (typeof text !== \"string\" || text.length === 0) continue\n for (const m of text.matchAll(NODE_REF_PATTERN)) {\n const { name } = parseNodeRef(m[1] ?? \"\")\n if (name === \"\" || name.startsWith(\"image:\") || RESERVED_TEMPLATE_VARS.has(name)) continue\n refs.add(canonicalVarName(name)) // case-insensitive: {Foo} suppresses a `foo` node\n }\n }\n return refs\n}\n\n/** Handle → combine-order category for same-label `{label}` merging. Lower wins\n * first: prompt (0) → elements (1) → look family (2). Other handles are -1\n * (not combinable — they keep the per-engine last-wins/suffix behavior). */\nexport const REF_HANDLE_CATEGORY: Readonly<Record<string, number>> = {\n prompt: 0,\n elements: 1,\n look: 2,\n cinematography: 2,\n style: 2,\n}\n\n/** Combine-order category for a direct-parent edge's `targetHandle`; -1 when the\n * handle isn't one of the combinable prompt/elements/look handles. */\nexport function refHandleCategory(targetHandle: string | null | undefined): number {\n if (targetHandle != null && Object.prototype.hasOwnProperty.call(REF_HANDLE_CATEGORY, targetHandle)) {\n return REF_HANDLE_CATEGORY[targetHandle]\n }\n return -1\n}\n\n/**\n * Reference-handle id → resolved-input key. The SINGLE SOURCE OF TRUTH for which\n * `targetHandle` ids carry image / video / audio reference inputs. Shared by the\n * backend input-resolver (routes the wired URL into the matching\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot) AND\n * the positional `{image:N}` / `{video:N}` / `{audio:N}` body-token COUNTS in the\n * FE preview (`video-prompt-assembly.ts`), FE run (`execute-node.ts`), and BE\n * payload-builder.\n *\n * Two handle families map to the same keys:\n * - Legacy / i2v single-name ids (`references` / `reference-videos` /\n * `reference-audio`) — kept for un-migrated workflows.\n * - Canonical typed-handle ids the modern Generate Video node exposes\n * (`imageReferences` / `videoReferences` / `audioReferences`) — share the\n * resolved-input keys with the legacy ids so consumer code never forks.\n */\nexport const REFERENCE_HANDLE_MAP: Record<string, \"referenceImageUrls\" | \"referenceVideoUrls\" | \"referenceAudioUrls\"> = {\n // Legacy / i2v single-name handle ids (kept for un-migrated workflows)\n \"references\": \"referenceImageUrls\",\n \"reference-videos\": \"referenceVideoUrls\",\n \"reference-audio\": \"referenceAudioUrls\",\n // New canonical typed-handle ids (Generate Video) — share the resolved-input\n // keys with the legacy ids so payload-builder code doesn't fork.\n \"imageReferences\": \"referenceImageUrls\",\n \"videoReferences\": \"referenceVideoUrls\",\n \"audioReferences\": \"referenceAudioUrls\",\n}\n\n/** The three reference modalities a reference handle can carry. */\nexport type ReferenceModality = \"image\" | \"video\" | \"audio\"\n\n/**\n * The reference MODALITY a `targetHandle` carries, or null when the handle is\n * not a reference handle. Resolves BOTH the legacy single-name ids and the\n * canonical Generate Video ids (via REFERENCE_HANDLE_MAP), so positional\n * `{image:N}` / `{video:N}` / `{audio:N}` token counts cover every handle alias\n * — without this, the generate-video `imageReferences` handle was silently\n * uncounted and `{image:N}` tokens dropped to bare labels on the only creatable\n * video node.\n */\nexport function referenceModalityForHandle(targetHandle: string | null | undefined): ReferenceModality | null {\n if (targetHandle == null) return null\n const key = REFERENCE_HANDLE_MAP[targetHandle]\n return key === \"referenceImageUrls\" ? \"image\" : key === \"referenceVideoUrls\" ? \"video\" : key === \"referenceAudioUrls\" ? \"audio\" : null\n}\n\n/**\n * Frame target handles (start / end keyframes). An image wired into one of these\n * is a KEYFRAME, not an `{image:N}` reference: the backend appends frames at the\n * TAIL of `reference_image_urls` (`resolveSeedance2Inputs`), never numbered. The\n * editor MUST therefore exclude them from `{image:N}` numbering so editor token N\n * equals the worker reference slot N.\n *\n * The SINGLE source of truth for \"is this a frame handle,\" shared by the\n * config-panel autocomplete (`video-configs.tsx`) AND the inline/modal builder\n * (`connected-references.ts`) — without ONE definition those two surfaces drifted\n * and the inline editor numbered the frame as `{image:1}` (the C1 bug). Frames\n * are deliberately NOT in `REFERENCE_HANDLE_MAP`: they carry no reference\n * modality, so `referenceModalityForHandle` already returns `null` for them on\n * the count side — this set is the exclusion lever for the EDITOR-numbering side.\n */\nexport const FRAME_TARGET_HANDLES: ReadonlySet<string> = new Set([\"startFrame\", \"endFrame\"])\n\n/**\n * Minimal structural edge shape {@link countRefModalityEdges} reads — only the\n * two fields the count needs. Both the FE `WorkflowEdge` (xyflow `Edge`, whose\n * `target` is a non-null string) and the BE `SimpleEdge` satisfy it.\n */\nexport interface RefModalityEdge {\n target?: string | null\n targetHandle?: string | null\n}\n\n/**\n * Count the reference-handle edges of a given reference MODALITY wired into a\n * node — the ONE positional `{image:N}` / `{video:N}` / `{audio:N}` counter\n * shared by the FE preview (`video-prompt-assembly.ts`), the FE run\n * (`execute-node.ts`), and the BE orchestrator (`payload-builder.ts`). Counting\n * via `referenceModalityForHandle` (not a single handle string) covers BOTH the\n * legacy single-name ids (`references` / `reference-videos` / `reference-audio`)\n * AND the canonical Generate Video ids (`imageReferences` / `videoReferences` /\n * `audioReferences`), so editor token N maps 1:1 to the worker\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot N on\n * every handle alias. This is the EDGE count (not the resolved/list-expanded URL\n * count) so all three paths stay byte-identical; the edge-vs-resolved divergence\n * for a reference edge that fans out to >1 URL (a List producer) is a shared,\n * documented v1 limitation.\n */\nexport function countRefModalityEdges(\n edges: ReadonlyArray<RefModalityEdge>,\n nodeId: string,\n modality: ReferenceModality,\n): number {\n let n = 0\n for (const e of edges) {\n if (e.target === nodeId && referenceModalityForHandle(e.targetHandle) === modality) n += 1\n }\n return n\n}\n\n/**\n * The wires that bring a node the images a run sends, besides its own source:\n * its reference images, each identity node on the `assets` handle (one image at\n * least), and every `image` wire after the first (the first is the source, which\n * an edit's estimate counts itself). For a model priced per input image.\n */\nexport function countImageInputEdges(edges: ReadonlyArray<RefModalityEdge>, nodeId: string): number {\n const onHandle = (handle: string) => edges.filter((e) => e.target === nodeId && e.targetHandle === handle).length\n return countRefModalityEdges(edges, nodeId, \"image\") + onHandle(\"assets\") + Math.max(0, onHandle(\"image\") - 1)\n}\n\n/** A candidate contribution to the `{label}` map: the node's label, its resolved\n * output, and its direct-parent handle category (-1 = not combinable / deeper). */\nexport interface RefCandidate {\n label: string\n output: string\n category: number\n}\n\n/**\n * Same-label COMBINE: when ≥2 direct-parent candidates (category ≥ 0) share a\n * label, `{label}` resolves to their values joined by \", \" ordered prompt →\n * elements → look, and within a category by candidate (edge) order. Returns a\n * Map of ONLY the combined labels; the caller fills the rest with its own\n * (FE suffix / BE last-wins) logic, skipping any label present here. Shared so\n * the frontend executor and backend orchestrator never drift.\n */\nexport function combineSameLabelRefs(candidates: ReadonlyArray<RefCandidate>): Map<string, string> {\n const byLabel = new Map<string, RefCandidate[]>()\n for (const c of candidates) {\n if (c.category < 0) continue\n const key = canonicalVarName(c.label) // TEXt + TEXT + text collapse into one {text}\n const arr = byLabel.get(key)\n if (arr) arr.push(c)\n else byLabel.set(key, [c])\n }\n const combined = new Map<string, string>()\n for (const [label, group] of byLabel) {\n if (group.length < 2) continue\n const ordered = group\n .map((c, i) => ({ c, i }))\n .sort((a, b) => a.c.category - b.c.category || a.i - b.i)\n .map((x) => x.c.output)\n combined.set(label, ordered.join(\", \"))\n }\n return combined\n}\n\n/**\n * Resolve {Node Label} references in text by replacing them with actual node outputs.\n * Skips reserved template variables used by applyTemplate().\n * Iterates until stable to handle nested refs (e.g. {List} → {Animal1} → \"dog\").\n */\nexport function resolveNodeRefs(\n text: string,\n labelToOutput: ReadonlyMap<string, string>,\n): string {\n const MAX_PASSES = 10\n let result = text\n for (let i = 0; i < MAX_PASSES; i++) {\n const next = result.replace(NODE_REF_PATTERN, (match, raw: string) => {\n const { name, fallback } = parseNodeRef(raw)\n if (RESERVED_TEMPLATE_VARS.has(name)) return match\n // Node-name vars are case-insensitive: try the literal key first (keeps\n // original-cased maps like condition-variables working), then the\n // lowercase-canonical key (node-ref maps are canonical-keyed).\n const output = labelToOutput.get(name) ?? labelToOutput.get(canonicalVarName(name))\n if (output !== undefined) return output // connected, non-empty output → its value\n if (fallback !== null) return fallback // absent/empty + fallback → default (\"\" for {name || })\n return match // absent + no || → literal {name}\n })\n if (next === result) break\n result = next\n }\n return result\n}\n\n/**\n * Token namespaces that are NOT node-label references. `{image:1:face}` is the\n * unified-reference grammar, `{slot:x}` is recast's, `{video:N}`/`{audio:N}`\n * are reference handles, and `{ref:<id>}` is the id-addressed reference form —\n * all five are substituted by their own resolvers (`resolveReferenceTokens`,\n * `resolveRefIdTokens`, the recast slot pass), not by resolveNodeRefs. Before\n * this list existed, only `image:` was excluded, so `{video:1}` classified as a\n * MISSING node ref.\n *\n * Compared against the LOWERCASED token name: `REFERENCE_TOKEN_RE` is `/gi` and\n * `REF_ID_TOKEN_RE` spells `[rR][eE][fF]`, so `{Image:1}` / `{Ref:x}` really do\n * resolve downstream and must never read as a missing node ref.\n */\nexport const REF_TOKEN_NAMESPACE_PREFIXES: readonly string[] = [\n \"image:\", \"video:\", \"audio:\", \"slot:\", \"ref:\",\n]\n\nexport type RefTokenKind = \"wired\" | \"reserved\" | \"missing\" | \"skip\" | \"unknown\"\n\n/**\n * Classify a parsed `{...}` token name against the resolvable label set.\n * `resolvable === null` means the caller has no ref data at all — such tokens\n * classify `unknown` and must render like wired, so \"no data\" never\n * masquerades as \"nothing wired\".\n *\n * Single source of truth for the editor decoration, the missing-refs chip\n * (frontend/src/lib/prompt-ref-scan.ts delegates here) and the execution\n * engine's dispatch guard.\n */\nexport function classifyRefToken(\n name: string,\n resolvable: ReadonlySet<string> | null,\n): RefTokenKind {\n const lower = name.toLowerCase()\n if (name === \"\" || REF_TOKEN_NAMESPACE_PREFIXES.some((p) => lower.startsWith(p))) return \"skip\"\n if (RESERVED_TEMPLATE_VARS.has(name)) return \"reserved\"\n if (resolvable === null) return \"unknown\"\n return resolvable.has(canonicalVarName(name)) ? \"wired\" : \"missing\"\n}\n\n/**\n * The `{Label}` tokens in `text` that `resolveNodeRefs` would leave LITERAL and\n * that no upstream node can explain — i.e. exactly what would reach a provider\n * as the characters `{Label}`. Evidence for why this matters: `{Describe Image}`\n * ×2 (gpt-image-2) and `{gravity flip}` / `{rewind}` (seedance-2-5) in the\n * 2026-09-01 app-reports export.\n *\n * `resolvable` — labels with a value in the ref map (canonical/lowercase).\n * `known` — canonical labels of the nodes the caller considers to EXIST\n * (no state requirement; the backend passes every node in the\n * run's graph).\n *\n * A token whose label is in `known` but not `resolvable` PASSES: the node\n * exists and simply produced nothing, which is the caller's to substitute (the\n * backend resolves it to empty text), not this function's to refuse. A token\n * with an explicit `|| fallback` passes too — the fallback is substituted.\n * Returns original-cased names, de-duplicated by canonical form, for the\n * user-facing message.\n */\nexport function unresolvedRefTokens(\n text: string,\n opts: { resolvable: ReadonlySet<string>; known: ReadonlySet<string> },\n): string[] {\n if (typeof text !== \"string\" || text.length === 0) return []\n const seen = new Set<string>()\n const out: string[] = []\n for (const m of text.matchAll(NODE_REF_PATTERN)) {\n const { name, fallback } = parseNodeRef(m[1] ?? \"\")\n if (fallback !== null) continue\n if (classifyRefToken(name, opts.resolvable) !== \"missing\") continue\n const canon = canonicalVarName(name)\n if (opts.known.has(canon) || seen.has(canon)) continue\n seen.add(canon)\n out.push(name)\n }\n return out\n}\n","/**\n * Every way one node FEEDS another — the ONE definition the server's run\n * scope (`triggerRunScope`) and the editor's \"is this trigger wired?\" read\n * from, so the card can never say \"the branch\" while the server runs the\n * whole workflow, or the other way round:\n *\n * - a drawn edge whose two ends are both on the graph (a delta that deleted a\n * node leaves its edges behind; those feed nothing);\n * - Group membership: a node inside a Group feeds the group (`parentId`),\n * the way the engine orders a group after its members;\n * - a field mapping: `data.fieldMappings[field].sourceNodeId` feeds the node\n * that carries the mapping, even after the edge it was made from is gone.\n */\n\nexport interface FeedNode {\n readonly id: string\n readonly parentId?: string | null\n readonly data?: unknown\n}\n\nexport interface FeedEdge {\n readonly source: string\n readonly target: string\n}\n\nexport interface FeedMaps {\n /** node id → the ids it feeds */\n readonly children: ReadonlyMap<string, ReadonlyArray<string>>\n /** node id → the ids that feed it */\n readonly parents: ReadonlyMap<string, ReadonlyArray<string>>\n}\n\nexport function buildFeedMaps(nodes: ReadonlyArray<FeedNode>, edges: ReadonlyArray<FeedEdge>): FeedMaps {\n const live = new Set(nodes.map((n) => n.id))\n const children = new Map<string, string[]>()\n const parents = new Map<string, string[]>()\n const feeds = (source: string, target: string) => {\n if (!live.has(source) || !live.has(target) || source === target) return\n children.set(source, [...(children.get(source) ?? []), target])\n parents.set(target, [...(parents.get(target) ?? []), source])\n }\n for (const edge of edges) feeds(edge.source, edge.target)\n for (const n of nodes) {\n if (typeof n.parentId === \"string\" && n.parentId) feeds(n.id, n.parentId)\n const mappings = (n.data as { fieldMappings?: unknown } | null | undefined)?.fieldMappings\n if (mappings && typeof mappings === \"object\") {\n for (const mapping of Object.values(mappings as Record<string, unknown>)) {\n const sourceNodeId = (mapping as { sourceNodeId?: unknown } | null)?.sourceNodeId\n if (typeof sourceNodeId === \"string\" && sourceNodeId) feeds(sourceNodeId, n.id)\n }\n }\n }\n return { children, parents }\n}\n\n/** Does this node feed anything? A trigger that does not runs the whole workflow. */\nexport function nodeFeedsAnything(nodes: ReadonlyArray<FeedNode>, edges: ReadonlyArray<FeedEdge>, nodeId: string): boolean {\n return (buildFeedMaps(nodes, edges).children.get(nodeId) ?? []).length > 0\n}\n","import { SUNO_SEPARATE_META_FIELDS, SUNO_SEPARATE_RESULT_FIELDS } from \"./suno-separate.js\"\n\n/**\n * Field names on a node's `data` that hold runtime / result / transient execution\n * state (job ids, progress, generated outputs, fan-out bookkeeping). These are NEVER\n * part of a node's reusable configuration.\n *\n * Single source of truth, consumed by:\n * - the workflow store's undo logic (execution-only updates skip undo capture, so job\n * polling does not pollute undo history or flip `isDirty`)\n * - the node-preset extractor (presets must never capture runtime state)\n * - the backend defensive strip on preset writes\n *\n * When adding a new runtime/result field to a node's data, add its key here — or, when it is a\n * generic name only one node type writes as a result, to that type's row of\n * NODE_TYPE_EXECUTION_DATA_KEYS (read through `isExecutionDataKey` / `executionDataKeysOf`).\n */\nexport const EXECUTION_DATA_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"errorMessage\",\n // Structured detail alongside errorMessage for a safety-filter block\n // (see `JobErrorHint` in the app's frontend/src/types/nodes.ts). Same\n // lifecycle as errorMessage: a RESULT the user expects to survive reload,\n // never user-edited config.\n \"errorHint\",\n // A job policy registered by the deployment held this node's result for a\n // human reviewer (`jobs.status = \"pending_review\"`). Pure run state, like\n // executionStatus: the node is still \"running\" and the flag disappears the\n // moment the review resolves — so it is ALSO in TRANSIENT_RUNTIME_KEYS\n // below. Without the transient half, a flip into review marks a passive tab\n // dirty and a preset captures \"awaiting review\".\n \"jobAwaitingReview\",\n // The editor cannot reach the server to read this node's job. The job keeps\n // running and the watch keeps polling. Pure run state, cleared by the next\n // check that gets through, so it is ALSO in TRANSIENT_RUNTIME_KEYS below.\n \"jobConnectionLost\",\n // Where this node's job stands in line while it waits for a free slot\n // (the job read's `queue` field), shown by the editor's queue badge. Pure run\n // state, replaced on each read and cleared once the job leaves `queued`, so\n // it is ALSO in TRANSIENT_RUNTIME_KEYS below: a badge never marks the\n // workflow dirty and is never saved.\n \"queueInfo\",\n \"isStreaming\",\n \"generatedImageUrl\",\n \"generatedVideoUrl\",\n \"generatedAudioUrl\",\n \"generatedText\",\n \"generatedScript\",\n \"generatedItems\",\n \"generatedResults\",\n \"activeResultIndex\",\n \"sourceImageUrl\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listResults\",\n // Row-aligned twin of __listResults (Extract Field, List output) — read only\n // by the fan-out so two lists cut from one array pair by row.\n \"__alignedListResults\",\n // A render's fan-out row stamps, row-aligned with __listResults: each row's\n // take identity, and the clip every row was sent for (a failed row too).\n \"__listResultStamps\",\n // List fan-out window flag (abandon-guard exemption). Set/cleared by\n // executeNodeForList — purely execution-related, never user-edited.\n \"__listRunning\",\n // Why the last server run skipped this node (`empty_input`): a chip on the\n // card for the run that just ended, never a saved result — also in\n // TRANSIENT_RUNTIME_KEYS below.\n \"__runSkipReason\",\n // One token per paid run still out on this node that no executor mark\n // covers (the editor's `withRunInFlight`, around each paid call outside the\n // executors). Purely execution-related, never user-edited; also in\n // TRANSIENT_RUNTIME_KEYS.\n \"__runsInFlight\",\n // Selector node dual-channel outputs (picked + rest). Server-side execution\n // output, not user-edited config.\n \"pickedResults\",\n \"restResults\",\n \"__pickedResults\",\n \"__restResults\",\n \"__pickedTotal\",\n \"__restTotal\",\n \"generatedJson\",\n // A render's remapped transcript on its own pip (Speaker View's\n // `transcript`, RENDER_NODE_TYPES transcriptOutput) — run-result data.\n \"generatedTranscript\",\n // Edit Plan: a person's review of the plan (`EditedEdl`, edit-plan-review.ts),\n // kept beside `generatedJson` and fingerprinted against it. Run-result data\n // (TA14, decided 2026-10-04): out of undo, presets, templates and exports,\n // and Clear results wipes it. Persisted — never transient.\n \"editedEdl\",\n \"subWorkflowProgress\",\n \"outputResults\",\n \"shots\",\n \"result\",\n \"processedResult\",\n \"activeRoutes\",\n \"routeOutputs\",\n \"_upstreamRefresh\",\n \"zoom\",\n // Character LoRA training status fields — written every 8s while training.\n \"loraReplicateVersion\",\n \"loraTriggerWord\",\n \"loraTrainingStatus\",\n // Collect (fan-in) execution snapshot.\n \"lastInputs\",\n \"lastMeta\",\n \"__upstreamCount\",\n // Video URL node — the download's live percent/phase, written on every\n // progress tick (~2/s). Pure run-state; also in TRANSIENT_RUNTIME_KEYS below.\n \"downloadPercent\",\n \"downloadPhase\",\n // Webhook Output's delivery receipt. A webhook target may reflect the\n // request back (httpbin, RequestBin, an API that 400s with \"headers\n // received: …\"), so `webhookResponseBody` can carry whatever the request\n // carried — with an attached credential, the secret itself. Listing the three\n // here is what keeps the receipt out of template exports (GENERATED_FIELDS\n // derives from this set), out of node presets, and out of undo history.\n \"webhookSuccess\",\n \"webhookStatusCode\",\n \"webhookResponseBody\",\n // Content Ideas: one creative brief per idea (the node's list output — kept\n // out of __listResults, which would clone the node). And the non-fatal notes\n // a Content Recipe / Content Ideas run returns (\"read the first of 3 posts\").\n // Both are RESULTS: they persist, and a preset, a template or a run-only\n // patch must never treat them as config.\n \"ideaBriefs\",\n \"runWarnings\",\n // Content Ideas: the own brand whose results the last run leaned on — a\n // RESULT naming the runner's brand, so a template or a preset never carries it.\n \"brandLessons\",\n // Social Search: every post the last search found (the picker's grid), the\n // ids a person picked from them, and the run's non-fatal notes (\"only part\n // of the results loaded\"). All RESULTS: a template, a preset or a run-only\n // patch must never carry yesterday's posts or picks as configuration.\n \"searchResults\",\n \"pickedIds\",\n \"searchWarnings\",\n // Save to Collection: how the last run ended for this node (inserted /\n // duplicate / replayed) and how many old records the cap evicted. RESULTS of\n // a run — Clear results wipes them, and a template, a preset or a run-only\n // patch never carries them as configuration.\n \"lastOutcome\",\n \"lastEvicted\",\n // When the editor's \"Clear results\" last emptied this node (ISO time). Not a\n // result and not config: bookkeeping that tells the load-time recovery lanes\n // \"this node is empty ON PURPOSE\" — without it, every reload reads an empty\n // node as \"ran while the editor was closed\" and paints the last run back.\n // Persisted (never transient): the reload is exactly when it is read.\n \"resultsClearedAt\",\n // The id of the trigger-started run whose results this node shows (the\n // editor paints a Telegram run onto the canvas). Bookkeeping, not a result\n // and not config: it stops a reload from painting the same run again over\n // edits made since. Persisted for the same reason as resultsClearedAt.\n \"resultsRunId\",\n // When that run ended the node (beside resultsRunId): the editor's reopen\n // keeps a result a NEWER run left even when its own run listing cannot see\n // that run. Bookkeeping, persisted for the same reason.\n \"resultsRunEndedAt\",\n // A trigger's last run values (also in TRANSIENT_RUNTIME_KEYS: never saved).\n \"__triggerData\",\n // A fan-out's notes rows, every fan-out's (row-aligned with __listResults):\n // a row's warnings and length. A RESULT: persisted.\n \"__listResultMeta\",\n // A use-case node's continuation of one of its runs (Tighten Episode): set\n // for ONE run only, as that run's input override (an app's or the editor's\n // Render final, the canvas Continue's run option). Never saved — also in\n // TRANSIENT_RUNTIME_KEYS — so a saved one can never turn a later plain run\n // into a continuation of an old run.\n \"useCaseContinue\",\n // The content rights confirmation a run fetches a Video URL node's link\n // under: that run's input override alone, never saved (also transient).\n \"rightsConfirmationId\",\n])\n\n/**\n * Run results a node type writes under a GENERIC name — `quote`, `durationSec`,\n * `candidates` — that are execution data on THAT type only. Another node may\n * keep a setting under the same name; filing these globally would misfile it\n * (out of undo, presets, templates and the copilot's view). Same lifecycle as\n * the global results: persisted, and a run writing them is never an undo step.\n *\n * UGC video (Nodaro Cloud): the outputs a node hands on (`ugcOutputs`), UGC\n * Creator's options of a draw and their note, UGC Clips' quote, and UGC Clip's\n * warnings, length and Re-render marks (`rerenderPending`: the clips pressed for\n * Re-render that no run has rendered yet — run bookkeeping; the press itself,\n * `rerender`, is a choice).\n *\n * Suno Separate: every stem / take URL a run writes and the run's facts (its\n * engine, a Demucs fallback's refusal and reason, its mode) — not `stemName`,\n * the node's instrument setting that the run only echoes back.\n */\nexport const NODE_TYPE_EXECUTION_DATA_KEYS: Readonly<Record<string, readonly string[]>> = {\n \"ugc-creator\": [\"ugcOutputs\", \"candidates\", \"optionFailed\"],\n \"ugc-script\": [\"ugcOutputs\"],\n \"ugc-clips\": [\"ugcOutputs\", \"quote\"],\n \"ugc-clip\": [\"ugcOutputs\", \"clipWarnings\", \"durationSec\", \"rerenderPending\"],\n \"ugc-cards\": [\"ugcOutputs\"],\n \"suno-separate\": [...SUNO_SEPARATE_RESULT_FIELDS, ...SUNO_SEPARATE_META_FIELDS.filter((key) => key !== \"stemName\")],\n}\n\n/** Is `key` execution data (run state or a run's result) on a node of `type`: global, or that type's own? */\nexport function isExecutionDataKey(key: string, type: string | null | undefined): boolean {\n if (EXECUTION_DATA_KEYS.has(key)) return true\n return typeof type === \"string\" && Object.hasOwn(NODE_TYPE_EXECUTION_DATA_KEYS, type) && NODE_TYPE_EXECUTION_DATA_KEYS[type]!.includes(key)\n}\n\nconst EXECUTION_DATA_KEYS_BY_TYPE = new Map<string, ReadonlySet<string>>(\n Object.entries(NODE_TYPE_EXECUTION_DATA_KEYS).map(([type, keys]) => [type, new Set([...EXECUTION_DATA_KEYS, ...keys])]),\n)\n\n/** Every execution-data key on a node of `type`, as one set: the global ones, plus the type's own. */\nexport function executionDataKeysOf(type: string | null | undefined): ReadonlySet<string> {\n return (typeof type === \"string\" ? EXECUTION_DATA_KEYS_BY_TYPE.get(type) : undefined) ?? EXECUTION_DATA_KEYS\n}\n\n/**\n * The PURE RUN-STATE subset of EXECUTION_DATA_KEYS: per-tick values (status\n * flips, job ids, progress counters, fan-out bookkeeping) that must NEITHER\n * mark the workflow dirty NOR be persisted in the save payload. Everything\n * else in EXECUTION_DATA_KEYS is a RESULT the user expects to survive reload\n * (generated URLs/results, errorMessage, LoRA outputs, collect snapshots).\n *\n * Why this split exists: writing these keys used to set `isDirty`, so job\n * polling phantom-dirtied passive tabs → spurious autosaves → false\n * \"changed in another tab\" banners → the remote-ahead latch froze autosave\n * (the \"not saved for a long time\" report). Consumed by the workflow\n * store's dirty decision and the save-payload sanitizer below.\n *\n * Invariant (guarded by node-runtime-keys.test.ts): subset of\n * EXECUTION_DATA_KEYS — anything transient is also undo-exempt.\n */\nexport const TRANSIENT_RUNTIME_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"jobAwaitingReview\",\n \"jobConnectionLost\",\n \"queueInfo\",\n \"isStreaming\",\n \"subWorkflowProgress\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listRunning\",\n \"__runSkipReason\",\n // A paid run still out, held by the editor tab that started it. Never\n // saved, so a reload, which has no such run, starts without one.\n \"__runsInFlight\",\n \"_upstreamRefresh\",\n \"__upstreamCount\",\n // Video URL node download ticks. They used to dirty the workflow twice a\n // second for the length of the download — the same phantom-save chain the\n // job-progress keys above were moved here to stop. What SURVIVES a reload is\n // `downloadStatus` + `downloadId`; the percent is re-read from the server.\n \"downloadPercent\",\n \"downloadPhase\",\n // A trigger's last run values, shown in the editor after a run (a webhook's\n // body, a Telegram message and its post). Never saved: the workflow is not\n // where a message's content is kept — runs are, under their retention.\n \"__triggerData\",\n // A use-case node's continuation: one run's override, never config (above).\n \"useCaseContinue\",\n // The content rights confirmation a run fetches a Video URL node's link\n // under: one run's override (RUN_ONLY_NODE_FIELDS), never config.\n \"rightsConfirmationId\",\n])\n\n/**\n * Pure save-payload sanitizer: returns new node objects with the transient\n * run-state keys removed from `data`. Nodes without transient keys (or\n * without `data`) are returned by reference — cheap for the common case.\n */\nexport function stripTransientRuntimeData<\n T extends { data?: Record<string, unknown> | undefined },\n>(nodes: readonly T[]): T[] {\n return nodes.map((node) => {\n const data = node.data\n if (!data) return node\n let hasTransient = false\n for (const key of TRANSIENT_RUNTIME_KEYS) {\n if (key in data) {\n hasTransient = true\n break\n }\n }\n if (!hasTransient) return node\n const cleaned: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(data)) {\n if (!TRANSIENT_RUNTIME_KEYS.has(key)) cleaned[key] = value\n }\n return { ...node, data: cleaned }\n })\n}\n","/**\n * Evaluate a dot-notation path against a JSON value.\n *\n * Auto-iterates arrays at any depth: if the current value is an array,\n * the evaluator iterates and applies the remaining path to each element,\n * flattening results. This lets simple paths like \"caption\" work on a\n * top-level array and \"pages.markdown\" work on a nested array without\n * any wildcard syntax.\n *\n * Returns an array of values. Missing properties are skipped (empty for\n * that branch). Null/undefined leaf values are included — callers coerce.\n * Empty path returns `[value]` (a single-element array wrapping the\n * value) when the value is scalar/object, or the array elements flat\n * when the root is an array.\n */\nexport function evaluateJsonPath(value: unknown, path: string): unknown[] {\n const segments = path.length === 0 ? [] : path.split(\".\")\n return walk(value, segments, 0)\n}\n\n/**\n * Coerce an array of unknown values (typically from evaluateJsonPath) to\n * strings, skipping null/undefined. Primitives are stringified; objects\n * are JSON-encoded.\n */\nexport function stringifyPathResults(raw: unknown[]): string[] {\n const out: string[] = []\n for (const v of raw) {\n if (v === null || v === undefined) continue\n if (typeof v === \"string\") out.push(v)\n else if (typeof v === \"number\" || typeof v === \"boolean\") out.push(String(v))\n else out.push(JSON.stringify(v))\n }\n return out\n}\n\nfunction walk(value: unknown, segments: string[], offset: number): unknown[] {\n if (Array.isArray(value)) {\n const results: unknown[] = []\n for (const item of value) {\n for (const v of walk(item, segments, offset)) results.push(v)\n }\n return results\n }\n if (offset >= segments.length) return [value]\n if (value !== null && typeof value === \"object\") {\n const head = segments[offset]\n if (!Object.hasOwn(value as object, head)) return []\n return walk((value as Record<string, unknown>)[head], segments, offset + 1)\n }\n return []\n}\n","/** Pure condition evaluator shared by filter-list and router (conditional mode). */\n\nimport { evaluateJsonPath } from \"./json-path.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\nexport type FilterListOperator =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\" | \"regex\"\n | \"exists\" | \"not_exists\"\n\nexport interface FilterListCondition {\n id?: string\n field?: string\n operator: FilterListOperator\n value?: string\n valueType?: \"static\" | \"variable\"\n /** UI-only hint on the config panel — irrelevant to evaluation. */\n mode?: \"dropdown\" | \"custom\"\n}\n\n/** AND/OR condition bundle used by the router's conditional mode. When a\n * group matches, every routeId is added to activeRoutes. Multiple groups\n * union (deduped). */\nexport interface RouterConditionGroup {\n id?: string\n conditions?: FilterListCondition[]\n conditionLogic?: \"AND\" | \"OR\"\n routeIds?: string[]\n}\n\n/**\n * Options for `evaluateCondition` / `evaluateConditionGroup`.\n */\nexport interface EvaluateConditionOptions {\n /** When `false`, text operators (`contains`, `not_contains`, `starts_with`,\n * `ends_with`, `=`, `!=`) compare case-insensitively using case-folded\n * string equality.\n *\n * Note: `=` and `!=` lose their default numeric-coercion semantics under\n * `caseSensitive: false`. Under the default (case-sensitive), `1 == \"1.0\"`\n * via `valuesEqual`; under `caseSensitive: false`, comparison is pure\n * case-folded string equality, so `\"1\" !== \"1.0\"`.\n *\n * Default (when undefined): `true` (case-sensitive) — preserves existing\n * behavior for all callers.\n *\n * Non-text operators (`>`, `<`, `>=`, `<=`, `exists`, `not_exists`,\n * `regex`) are unaffected by this flag. */\n caseSensitive?: boolean\n /** Label→output map for `{Node Label}` refs inside condition values.\n * Populated from a filter-list / router node's `\"variables\"` target\n * handle. Resolved via `resolveNodeRefs` — unknown labels preserve\n * the original `{...}` text, so JSON-literal values stay intact. */\n variables?: ReadonlyMap<string, string>\n}\n\nexport function tryParseJson(item: unknown): unknown {\n if (typeof item !== \"string\") return item\n const trimmed = item.trim()\n if (!trimmed) return item\n const first = trimmed[0]\n if (first !== \"{\" && first !== \"[\" && first !== \"\\\"\" && !/^-?\\d/.test(trimmed) && trimmed !== \"true\" && trimmed !== \"false\" && trimmed !== \"null\") {\n return item\n }\n try { return JSON.parse(trimmed) } catch { return item }\n}\n\nconst HOUR_MS = 60 * 60 * 1000\nconst DAY_MS = 24 * HOUR_MS\nconst WEEK_MS = 7 * DAY_MS\n\n/** Resolve a relative-window token like `last_N_hours:3` to an ISO timestamp\n * N units before `Date.now()`. Returns undefined for malformed tokens. */\nexport function resolveRelativeWindowToken(key: string): string | undefined {\n const m = /^last_N_(hours|days|weeks):(-?\\d+)$/.exec(key)\n if (!m) return undefined\n const n = parseInt(m[2], 10)\n if (!Number.isFinite(n)) return undefined\n const unitMs = m[1] === \"hours\" ? HOUR_MS : m[1] === \"days\" ? DAY_MS : WEEK_MS\n return new Date(Date.now() - n * unitMs).toISOString()\n}\n\n/**\n * Substitute `{{...}}` template tokens — `{{now}}`, `{{trigger.<path>}}`,\n * and relative-window tokens (`{{last_N_hours:N}}` / days / weeks). Reused\n * by `resolveConditionValue` (filter-list / router) and `resolveSelectorRefs`\n * (selector node) so token semantics stay identical across the workflow-engine\n * ref-resolution surface.\n *\n * Pure: returns a new string. Strings with no `{{...}}` tokens pass through\n * unchanged.\n */\nexport function substituteTriggerTokens(\n raw: string,\n triggerData?: Record<string, unknown>,\n): string {\n if (!/\\{\\{/.test(raw)) return raw\n return raw.replace(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_m, expr) => {\n const key = String(expr).trim()\n if (key === \"now\") return new Date().toISOString()\n if (key === \"trigger.last_triggered_at\") {\n const v = triggerData?.last_triggered_at\n return v == null ? \"\" : String(v)\n }\n if (key.startsWith(\"trigger.\")) {\n const path = key.slice(\"trigger.\".length)\n const v = triggerData?.[path]\n return v == null ? \"\" : String(v)\n }\n const relative = resolveRelativeWindowToken(key)\n if (relative !== undefined) return relative\n return \"\"\n })\n}\n\nexport function resolveConditionValue(\n raw: string,\n valueType: string | undefined,\n triggerData?: Record<string, unknown>,\n variables?: ReadonlyMap<string, string>,\n): string {\n let value = raw\n if (variables && variables.size > 0) {\n value = resolveNodeRefs(value, variables)\n }\n const hasTemplate = /\\{\\{/.test(value)\n if (valueType !== \"variable\" && !hasTemplate) return value\n return substituteTriggerTokens(value, triggerData)\n}\n\nfunction asComparableNumber(v: unknown): number {\n if (typeof v === \"number\") return v\n if (typeof v === \"boolean\") return v ? 1 : 0\n if (typeof v === \"string\") {\n const trimmed = v.trim()\n if (trimmed === \"\") return NaN\n const n = Number(trimmed)\n if (!isNaN(n)) return n\n const d = Date.parse(trimmed)\n if (!isNaN(d)) return d\n }\n return NaN\n}\n\n// Numeric-first ordering compare used by >, <, >=, <=. Falls back to\n// localeCompare when either side can't be parsed as a number.\nfunction compareValues(a: unknown, b: unknown): number {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na - nb\n return String(a ?? \"\").localeCompare(String(b ?? \"\"))\n}\n\n// Numeric-first equality used by = and !=. So \"432\" == 432, and 432 == \"432\".\n// Falls back to strict string equality (null/undefined coerced to \"\") so\n// alpha values still work.\nfunction valuesEqual(a: unknown, b: unknown): boolean {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na === nb\n return String(a ?? \"\") === String(b ?? \"\")\n}\n\nfunction applyCase(s: string, caseSensitive: boolean): string {\n return caseSensitive ? s : s.toLowerCase()\n}\n\nexport function evaluateCondition(\n parsedItem: unknown,\n rawItem: string,\n condition: FilterListCondition,\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const path = (condition.field ?? \"\").trim()\n let fieldValue: unknown\n if (path === \"\") {\n fieldValue = parsedItem ?? rawItem\n } else {\n const matches = evaluateJsonPath(parsedItem ?? rawItem, path)\n fieldValue = matches.length > 0 ? matches[0] : undefined\n }\n\n const targetStr = resolveConditionValue(condition.value ?? \"\", condition.valueType, triggerData, options?.variables)\n // Default to case-sensitive when the flag is not explicitly set. This\n // preserves existing behavior for Router conditional mode and legacy\n // Filter List nodes that don't carry the new `caseSensitive` field.\n const cs = options?.caseSensitive ?? true\n const fieldStr = String(fieldValue ?? \"\")\n\n switch (condition.operator) {\n case \"exists\":\n return fieldValue !== undefined && fieldValue !== null\n case \"not_exists\":\n return fieldValue === undefined || fieldValue === null\n case \"contains\":\n return applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"not_contains\":\n return !applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"starts_with\":\n return applyCase(fieldStr, cs).startsWith(applyCase(targetStr, cs))\n case \"ends_with\":\n return applyCase(fieldStr, cs).endsWith(applyCase(targetStr, cs))\n case \"regex\": {\n if (!targetStr) return false\n try {\n return new RegExp(targetStr).test(fieldStr)\n } catch {\n return false\n }\n }\n case \"=\":\n return cs\n ? valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) === applyCase(targetStr, false)\n case \"!=\":\n return cs\n ? !valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) !== applyCase(targetStr, false)\n case \">\":\n return compareValues(fieldValue, targetStr) > 0\n case \"<\":\n return compareValues(fieldValue, targetStr) < 0\n case \">=\":\n return compareValues(fieldValue, targetStr) >= 0\n case \"<=\":\n return compareValues(fieldValue, targetStr) <= 0\n default:\n return false\n }\n}\n\n/** Evaluate a single AND/OR-joined group against one item. Empty condition\n * list evaluates to `true` — typical when the user has just added a group\n * and hasn't configured any conditions yet. */\nexport function evaluateConditionGroup(\n parsedItem: unknown,\n rawItem: string,\n conditions: readonly FilterListCondition[],\n logic: \"AND\" | \"OR\",\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const effective = conditions.filter((c) => c && c.operator)\n if (effective.length === 0) return true\n const results = effective.map((c) => evaluateCondition(parsedItem, rawItem, c, triggerData, options))\n return logic === \"OR\" ? results.some(Boolean) : results.every(Boolean)\n}\n","/**\n * Edge range utilities for resolving 1-based index expressions\n * and applying range/step slicing to output lists.\n *\n * Used by both frontend DAG executor and backend orchestrator\n * to support edge-level range, step, and item selection.\n */\n\nimport { evaluateCondition, substituteTriggerTokens, tryParseJson } from \"./filter-condition.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\n/** Selector tab on an edge — \"range\" (from/to/step) or \"list\" (expression). */\nexport type SelectorMode = \"range\" | \"list\"\n\n/** Per-edge output mode controlling how upstream results reach downstream. */\nexport type OutputMode = \"last\" | \"each\" | \"all\" | \"item\"\n\n/** Edge-data fields consumed by selectListItems / isDefaultSelectorConfig. */\nexport type SelectorFields = {\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n}\n\n/** Full selector mode set — extends the edge-selector modes with new operators. */\nexport type FullSelectorMode =\n | \"item\"\n | \"range\"\n | \"list\"\n | \"random\"\n | \"modulo\"\n | \"predicate\"\n | \"named-key\"\n\n/** Operator set for predicate mode — reused from filter-list. */\nexport type SelectorPredicateOp =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\"\n | \"regex\"\n | \"exists\" | \"not_exists\"\n\n/** Config consumed by `runSelector` and `resolveSelectorRefs`. */\nexport type SelectorConfig = {\n mode: FullSelectorMode\n // item\n itemIndex?: string\n // range\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n // list\n listExpression?: string\n // random\n seed?: string\n randomCount?: number\n // modulo\n moduloDivisor?: string\n // predicate\n predicateField?: string\n predicateOp?: SelectorPredicateOp\n predicateValue?: string\n predicateMatch?: \"first\" | \"all\"\n predicateCaseSensitive?: boolean\n // named-key\n namedKeyField?: string\n namedKeyValue?: string\n}\n\n/** Result of a selector run. `picked ∪ rest = items`, `picked ∩ rest = ∅`. */\nexport type SelectorResult = { picked: string[]; rest: string[] }\n\n/**\n * Resolves a 1-based index expression to a 0-based array index.\n *\n * Supported expressions:\n * - \"1\", \"2\", ... — absolute 1-based index\n * - \"last\" — last element\n * - \"last-1\", \"last-2\", ... — relative from end\n *\n * Out-of-bounds values are clamped. Malformed input falls back to `defaultExpr`.\n */\nexport function resolveIndex(\n expr: string,\n listLength: number,\n defaultExpr: string = \"1\",\n): number {\n if (listLength <= 0) return 0\n\n const trimmed = expr.trim()\n let index: number\n\n if (trimmed === \"last\") {\n index = listLength - 1\n } else if (trimmed.startsWith(\"last-\")) {\n const offset = parseInt(trimmed.slice(5), 10)\n if (isNaN(offset) || offset < 0) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = listLength - 1 - offset\n } else {\n const n = parseInt(trimmed, 10)\n if (isNaN(n)) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = n - 1\n }\n\n return Math.max(0, Math.min(index, listLength - 1))\n}\n\n/**\n * Applies range and step slicing to a list of strings.\n *\n * `from` and `to` are 1-based index expressions (see `resolveIndex`).\n * `step` controls iteration direction and stride:\n * - positive step: forward iteration (from must be <= to)\n * - negative step: reverse iteration (from must be >= to)\n * - step 0 is treated as step 1\n *\n * Returns empty array if direction mismatches (e.g., from < to with negative step).\n */\nexport function applyRange(\n list: string[],\n from?: string,\n to?: string,\n step?: number,\n): string[] {\n if (list.length === 0) return []\n\n const fromIdx = resolveIndex(from ?? \"1\", list.length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", list.length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n\n const result: string[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(list[i])\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(list[i])\n }\n return result\n}\n\n/**\n * Migrates legacy `item:N` (0-based) outputMode to structured format.\n *\n * Legacy: `{ outputMode: \"item:0\" }` — 0-based index baked into mode string\n * New: `{ outputMode: \"item\", itemIndex: \"1\" }` — 1-based expression\n *\n * Returns the data unchanged if not a legacy item mode.\n */\nexport function migrateEdgeOutputMode(\n data: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!data) return data\n\n const mode = data.outputMode as string | undefined\n if (!mode || !mode.startsWith(\"item:\")) return data\n\n const idx = parseInt(mode.split(\":\")[1], 10)\n return {\n ...data,\n outputMode: \"item\",\n itemIndex: String(isNaN(idx) ? 1 : idx + 1),\n }\n}\n\n/**\n * Builds the edge range label shown as a pill on the edge.\n * Examples:\n * - \"2..last-1 +2\" — range with step 2\n * - \"last..1 -1\" — reversed\n * - \"3\" — item mode, index 3\n * - undefined — \"last\" mode has no label\n */\nexport function buildRangeLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n return buildItemLabel(mode, rangeFrom, rangeTo, rangeStep, itemIndex, selectorMode, listExpression)\n}\n\n/** Internal: builds the item-side label (range / list / item / each). Mode \"last\" returns undefined. */\nfunction buildItemLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n if (mode === \"last\") return undefined\n\n if ((mode === \"each\" || mode === \"all\") && selectorMode === \"list\") {\n const trimmed = (listExpression ?? \"\").trim()\n if (trimmed === \"\") return undefined\n return truncateLabel(trimmed, 18)\n }\n\n if (mode === \"item\") return itemIndex || undefined\n\n const from = rangeFrom ?? \"1\"\n const to = rangeTo ?? \"last\"\n const step = rangeStep ?? 1\n const isDefaultRange = from === \"1\" && to === \"last\"\n const isDefaultStep = step === 1\n if (isDefaultRange && isDefaultStep) return undefined\n\n let label = `${from}..${to}`\n if ((mode === \"each\" || mode === \"all\") && !isDefaultStep) {\n label += step > 0 ? ` +${step}` : ` ${step}`\n }\n return label\n}\n\nfunction truncateLabel(s: string, maxLen: number): string {\n if (s.length <= maxLen) return s\n return s.slice(0, maxLen) + \"…\"\n}\n\n/**\n * Validates a list expression without resolving indices.\n * Used for live UI validation in the List tab input.\n *\n * Returns { ok: true } for empty/whitespace input — matches the\n * \"empty = all items\" runtime semantics.\n */\nexport function parseListExpression(\n expr: string,\n): { ok: true } | { ok: false; error: string } {\n const result = parseListTerms(expr.trim())\n return result.ok ? { ok: true } : { ok: false, error: result.error }\n}\n\n/** Internal: validates a single index token (\"1\", \"last\", \"last-3\"). */\nfunction isValidIndexToken(token: string): boolean {\n if (token === \"last\") return true\n if (/^[1-9]\\d*$/.test(token)) return true\n const m = /^last-(\\d+)$/.exec(token)\n if (m) return !isNaN(parseInt(m[1], 10))\n return false\n}\n\n/**\n * Parses a list expression and returns 0-based indices into the list,\n * in user-specified order. Preserves duplicates.\n *\n * Supported syntax:\n * <expr> := <term> (\",\" <term>)*\n * <term> := <index> | <index> \"..\" <index> (\":\" <step>)?\n * <index> := <number> | \"last\" | \"last-\" <number>\n * <step> := integer (0 coerced to 1)\n *\n * Clamps out-of-bounds indices. Malformed input logs a warning and\n * returns [0..listLength-1] (matches applyRange leniency).\n */\nexport function resolveListExpression(expr: string, listLength: number): number[] {\n if (listLength <= 0) return []\n const result = parseListTerms(expr.trim())\n if (!result.ok) {\n console.warn(\"[edge-range] invalid list expression:\", expr, \"—\", result.error)\n return indexRange(0, listLength - 1, 1)\n }\n if (result.terms.length === 0) return indexRange(0, listLength - 1, 1)\n\n const out: number[] = []\n for (const term of result.terms) {\n if (term.kind === \"index\") {\n out.push(resolveIndex(term.token, listLength))\n } else {\n const from = resolveIndex(term.from, listLength)\n const to = resolveIndex(term.to, listLength)\n for (const idx of indexRange(from, to, term.step)) out.push(idx)\n }\n }\n return out\n}\n\n/** Internal: inclusive index range with step. Returns [] if direction mismatches. */\nfunction indexRange(from: number, to: number, step: number): number[] {\n const out: number[] = []\n if (step > 0) {\n if (from > to) return []\n for (let i = from; i <= to; i += step) out.push(i)\n } else {\n if (from < to) return []\n for (let i = from; i >= to; i += step) out.push(i)\n }\n return out\n}\n\n/**\n * Dispatches to either applyRange() or resolveListExpression() based on\n * edgeData.selectorMode. Returns a new string[] containing the selected\n * subset of items — or `items` unchanged when the edge has no filter.\n */\nexport function selectListItems(\n items: string[],\n edgeData: SelectorFields | undefined,\n): string[] {\n if (items.length === 0) return []\n if (isDefaultSelectorConfig(edgeData)) return items\n if (edgeData?.selectorMode === \"list\") {\n const indices = resolveListExpression(edgeData.listExpression ?? \"\", items.length)\n return indices.map((i) => items[i])\n }\n return applyRange(items, edgeData?.rangeFrom, edgeData?.rangeTo, edgeData?.rangeStep)\n}\n\n/**\n * Returns true when edge data carries no active filter — empty/whitespace list\n * expression in list mode, or defaults (1..last, step 1) in range mode.\n * Callers can skip filtering entirely when this returns true.\n */\nexport function isDefaultSelectorConfig(edgeData: SelectorFields | undefined): boolean {\n if (!edgeData) return true\n if (edgeData.selectorMode === \"list\") {\n return ((edgeData.listExpression ?? \"\").trim()) === \"\"\n }\n const { from, to, step } = canonicalRange(edgeData)\n return from === \"1\" && to === \"last\" && step === 1\n}\n\nexport function describeEdgeBehavior(\n edgeData:\n | {\n outputMode?: string\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n itemIndex?: string\n }\n | undefined,\n): string {\n const mode = edgeData?.outputMode\n return buildBaseSentence(edgeData, mode)\n}\n\nfunction buildBaseSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n mode: string | undefined,\n): string {\n if (mode === \"last\") return \"Passes the selected result.\"\n if (mode === \"item\") return buildItemSentence(edgeData)\n if (mode === \"each\") return buildEachSentence(edgeData)\n if (mode === \"all\") return buildAllSentence(edgeData)\n return \"Passes all items at once.\"\n}\n\nfunction buildItemSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n const canonical = canonicalItemIndex(edgeData?.itemIndex)\n return `Passes only ${itemModeForm(canonical)}.`\n}\n\nfunction buildEachSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Runs the next node one by one, per item.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Runs the next node one by one, per item.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node won't run.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Runs the next node only on ${phrase.itemModeForm}.`\n }\n return `Runs the next node once for ${phrase.text}.`\n}\n\nfunction buildAllSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Passes all items at once.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Passes all items at once.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node will get an empty bundle.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Passes only ${phrase.itemModeForm}.`\n }\n return `Passes ${phrase.text} at once.`\n}\n\ntype CanonicalRange = { from: string; to: string; step: number }\n\nfunction canonicalItemIndex(raw: string | undefined): string {\n const trimmed = (raw ?? \"\").trim()\n if (trimmed === \"\") return \"1\"\n if (!isValidIndexToken(trimmed)) return \"1\"\n return trimmed\n}\n\nfunction canonicalRange(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): CanonicalRange {\n const from = ((edgeData?.rangeFrom ?? \"\").trim() || \"1\")\n const to = ((edgeData?.rangeTo ?? \"\").trim() || \"last\")\n const rawStep = edgeData?.rangeStep\n const step = rawStep === undefined || rawStep === 0 ? 1 : rawStep\n return { from, to, step }\n}\n\n\nfunction itemModeForm(canonical: string): string {\n if (canonical === \"1\") return \"the first item\"\n if (/^\\d+$/.test(canonical)) return `item ${canonical}`\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last item\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last item\"\n if (n === 2) return \"the third-to-last item\"\n if (n === 3) return \"the fourth-to-last item\"\n return `the ${ordinal(n + 1)}-from-last item`\n }\n return \"the first item\"\n}\n\nfunction compactForm(canonical: string): string {\n if (/^\\d+$/.test(canonical)) return canonical\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last one\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last\"\n if (n === 2) return \"the third-to-last\"\n if (n === 3) return \"the fourth-to-last\"\n return `the ${ordinal(n + 1)}-from-last`\n }\n return canonical\n}\n\nfunction ordinal(n: number): string {\n const absN = Math.abs(n)\n const lastTwo = absN % 100\n if (lastTwo >= 11 && lastTwo <= 13) return `${n}th`\n switch (absN % 10) {\n case 1: return `${n}st`\n case 2: return `${n}nd`\n case 3: return `${n}rd`\n default: return `${n}th`\n }\n}\n\ntype SelectionPhrase =\n | { kind: \"items\"; text: string }\n | { kind: \"single-index\"; itemModeForm: string }\n | { kind: \"empty-result\" }\n\nfunction buildSelectionPhrase(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): SelectionPhrase {\n if (edgeData?.selectorMode === \"list\") {\n return buildListSelectionPhrase((edgeData.listExpression ?? \"\").trim())\n }\n return buildRangeSelectionPhrase(canonicalRange(edgeData))\n}\n\nfunction indexKind(token: string): \"concrete\" | \"relative\" | \"invalid\" {\n if (/^[1-9]\\d*$/.test(token)) return \"concrete\"\n if (token === \"last\" || /^last-\\d+$/.test(token)) return \"relative\"\n return \"invalid\"\n}\n\nfunction relativeOffset(token: string): number {\n if (token === \"last\") return 0\n const m = /^last-(\\d+)$/.exec(token)\n return m ? parseInt(m[1], 10) : 0\n}\n\nfunction compareTokens(a: string, b: string): -1 | 0 | 1 | \"indeterminate\" {\n const ka = indexKind(a)\n const kb = indexKind(b)\n if (ka !== kb) return \"indeterminate\"\n if (ka === \"concrete\") {\n const na = parseInt(a, 10)\n const nb = parseInt(b, 10)\n return na < nb ? -1 : na > nb ? 1 : 0\n }\n if (ka === \"relative\") {\n const oa = relativeOffset(a)\n const ob = relativeOffset(b)\n return oa < ob ? 1 : oa > ob ? -1 : 0\n }\n return \"indeterminate\"\n}\n\nfunction buildRangeSelectionPhrase(r: CanonicalRange): SelectionPhrase {\n const { from, to, step } = r\n\n const cmp = compareTokens(from, to)\n if (cmp !== \"indeterminate\") {\n if (step > 0 && cmp === 1) return { kind: \"empty-result\" }\n if (step < 0 && cmp === -1) return { kind: \"empty-result\" }\n }\n\n if (cmp === 0) {\n return { kind: \"single-index\", itemModeForm: itemModeForm(from) }\n }\n\n const absStep = Math.abs(step)\n if (step === -1 && from === \"last\" && to === \"1\") {\n return { kind: \"items\", text: \"all items in reverse order\" }\n }\n\n let text = `items ${compactForm(from)} through ${compactForm(to)}`\n if (absStep === 1 && step < 0) {\n text += \" in reverse order\"\n } else if (absStep > 1 && step > 0) {\n text += ` (every ${ordinal(absStep)} item)`\n } else if (absStep > 1 && step < 0) {\n text += ` (every ${ordinal(absStep)} item, in reverse)`\n }\n return { kind: \"items\", text }\n}\n\ntype ListTerm =\n | { kind: \"index\"; token: string }\n | { kind: \"range\"; from: string; to: string; step: number }\n\ntype ParseResult =\n | { ok: true; terms: ListTerm[] }\n | { ok: false; error: string }\n\n/**\n * Core list-expression parser. Returns structured terms on success or a\n * specific error message on failure. Empty input → zero terms (not an error).\n * Error messages are surfaced unchanged in the edge-config tooltip, so they\n * must stay stable:\n * - \"Empty item between commas\"\n * - \"Invalid index: <token>\"\n * - \"Range missing endpoint: <term>\"\n * - \"Step must be an integer\"\n */\nfunction parseListTerms(expr: string): ParseResult {\n if (expr === \"\") return { ok: true, terms: [] }\n const terms: ListTerm[] = []\n const raw = expr.split(\",\")\n for (const rawTerm of raw) {\n const term = rawTerm.trim()\n if (term === \"\") return { ok: false, error: \"Empty item between commas\" }\n const rangeIdx = term.indexOf(\"..\")\n if (rangeIdx === -1) {\n if (!isValidIndexToken(term)) return { ok: false, error: `Invalid index: ${term}` }\n terms.push({ kind: \"index\", token: term })\n continue\n }\n const left = term.slice(0, rangeIdx).trim()\n const rightWithStep = term.slice(rangeIdx + 2).trim()\n if (left === \"\" || rightWithStep === \"\") {\n return { ok: false, error: `Range missing endpoint: ${term}` }\n }\n const colonIdx = rightWithStep.indexOf(\":\")\n const right = colonIdx === -1 ? rightWithStep : rightWithStep.slice(0, colonIdx).trim()\n const stepStr = colonIdx === -1 ? null : rightWithStep.slice(colonIdx + 1).trim()\n if (right === \"\") return { ok: false, error: `Range missing endpoint: ${term}` }\n if (!isValidIndexToken(left)) return { ok: false, error: `Invalid index: ${left}` }\n if (!isValidIndexToken(right)) return { ok: false, error: `Invalid index: ${right}` }\n let step = 1\n if (stepStr !== null) {\n if (!/^-?\\d+$/.test(stepStr)) return { ok: false, error: \"Step must be an integer\" }\n const parsed = parseInt(stepStr, 10)\n step = parsed === 0 ? 1 : parsed\n }\n terms.push({ kind: \"range\", from: left, to: right, step })\n }\n return { ok: true, terms }\n}\n\nfunction buildListSelectionPhrase(expr: string): SelectionPhrase {\n const result = parseListTerms(expr)\n if (!result.ok) return { kind: \"empty-result\" }\n if (result.terms.length === 0) return { kind: \"items\", text: \"items\" } // unreachable via callers; default-config catches empty\n\n const normalized = result.terms.map<ListTerm>((t) => {\n if (t.kind === \"range\") {\n const cmp = compareTokens(t.from, t.to)\n if (cmp === 0) return { kind: \"index\", token: t.from }\n }\n return t\n })\n\n if (normalized.length === 1 && normalized[0].kind === \"index\") {\n return { kind: \"single-index\", itemModeForm: itemModeForm(normalized[0].token) }\n }\n\n const rendered = normalized.map((t) => {\n if (t.kind === \"index\") return compactForm(t.token)\n let text = `${compactForm(t.from)} through ${compactForm(t.to)}`\n const absStep = Math.abs(t.step)\n if (absStep === 1 && t.step < 0) {\n if (t.from === \"last\" && t.to === \"1\") return \"all items in reverse\"\n text += \" in reverse\"\n } else if (absStep > 1 && t.step > 0) {\n text += ` (every ${ordinal(absStep)})`\n } else if (absStep > 1 && t.step < 0) {\n text += ` (every ${ordinal(absStep)}, in reverse)`\n }\n return text\n })\n\n let joined: string\n if (rendered.length === 1) {\n joined = rendered[0]\n } else if (rendered.length === 2) {\n joined = `${rendered[0]} and ${rendered[1]}`\n } else {\n const head = rendered.slice(0, -1).join(\", \")\n joined = `${head}, and ${rendered[rendered.length - 1]}`\n }\n return { kind: \"items\", text: `items ${joined}` }\n}\n\n/**\n * Run the selector against `items`. Returns the picked subset plus the\n * complement (`rest`). For modes that pick by index, `rest` is computed by\n * index exclusion (not value) so duplicate items are handled correctly.\n */\nexport function runSelector(items: string[], config: SelectorConfig): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n\n switch (config.mode) {\n case \"item\": {\n const idx = resolveIndex(config.itemIndex ?? \"1\", items.length, \"1\")\n return splitByIndices(items, [idx])\n }\n case \"range\": {\n const indices = applyRangeIndices(items.length, config.rangeFrom, config.rangeTo, config.rangeStep)\n return splitByIndices(items, indices)\n }\n case \"list\": {\n const indices = resolveListExpression(config.listExpression ?? \"\", items.length)\n return splitByIndices(items, indices)\n }\n case \"random\":\n return selectRandom(items, config.randomCount ?? 1, config.seed)\n case \"modulo\":\n return selectByModulo(items, config.moduloDivisor)\n case \"predicate\":\n return selectByPredicate(items, config)\n case \"named-key\":\n return selectByNamedKey(items, config.namedKeyField, config.namedKeyValue)\n default:\n return { picked: [], rest: items.slice() }\n }\n}\n\n/**\n * Partition `items` into picked (indices ∈ pickedIndices, in their original\n * order in the source list) and rest (everything else). Deduplicates\n * `pickedIndices` so passing the same index twice doesn't double-count.\n */\nfunction splitByIndices(items: string[], pickedIndices: number[]): SelectorResult {\n const pickedSet = new Set(pickedIndices.filter((i) => i >= 0 && i < items.length))\n const picked: string[] = []\n const rest: string[] = []\n for (let i = 0; i < items.length; i++) {\n if (pickedSet.has(i)) picked.push(items[i])\n else rest.push(items[i])\n }\n return { picked, rest }\n}\n\n/**\n * Returns the indices that `applyRange` would pick. Extracted so `runSelector`\n * range mode can compute the exact picked-index set (`items.indexOf(value)`\n * would return the wrong duplicate when the list contains repeated values).\n */\nexport function applyRangeIndices(\n length: number,\n from?: string,\n to?: string,\n step?: number,\n): number[] {\n if (length === 0) return []\n const fromIdx = resolveIndex(from ?? \"1\", length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n const result: number[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(i)\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(i)\n }\n return result\n}\n\n/** mulberry32 PRNG — deterministic given a seed (any 32-bit signed integer).\n *\n * TWIN WARNING: backend/src/providers/video/audio-fx.ts carries its own\n * private mulberry32 (cosmetically different — `>>> 0` seed masking — but the\n * same sequence). The two are deliberately INDEPENDENT and both frozen: the\n * audio-fx copy seeds every reverb impulse response that the committed\n * characterization goldens (and every customer's rendered reverb waveform)\n * are pinned to. Do NOT \"deduplicate\" them into one shared export or \"sync\"\n * one to match the other — a change to either sequence is a silent behavior\n * change in its domain. */\nfunction mulberry32(seed: number): () => number {\n let a = seed | 0\n return () => {\n a = (a + 0x6D2B79F5) | 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** Hash a seed string to a 32-bit integer (FNV-1a variant). */\nfunction hashSeed(s: string): number {\n let h = 2166136261 | 0\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i)\n h = Math.imul(h, 16777619)\n }\n return h\n}\n\n/**\n * Pick `count` items uniformly at random without replacement.\n * If `seed` is non-empty, the PRNG is seeded deterministically.\n * Otherwise `Math.random` is used (fresh randomness per call).\n */\nexport function selectRandom(items: string[], count: number, seed?: string): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const k = Math.max(0, Math.min(count, items.length))\n const rand = seed && seed.length > 0 ? mulberry32(hashSeed(seed)) : Math.random\n // Partial Fisher-Yates: shuffle the first k positions, pick those indices.\n const indices = items.map((_, i) => i)\n for (let i = 0; i < k; i++) {\n const j = i + Math.floor(rand() * (indices.length - i))\n ;[indices[i], indices[j]] = [indices[j], indices[i]]\n }\n return splitByIndices(items, indices.slice(0, k))\n}\n\n/**\n * Pick a single item at `divisor % items.length`. Non-numeric `divisor`\n * falls back to index 0. Caller is responsible for resolving any\n * `{NodeLabel}` template refs in `divisor` BEFORE calling this — see\n * `resolveSelectorRefs`.\n */\nexport function selectByModulo(items: string[], divisor: string | undefined): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const n = divisor ? Number.parseInt(divisor.trim(), 10) : NaN\n const safeN = Number.isFinite(n) ? n : 0\n const idx = ((safeN % items.length) + items.length) % items.length\n return splitByIndices(items, [idx])\n}\n\n/**\n * Pick items whose parsed JSON satisfies the predicate. `match: \"first\"`\n * (default) stops at the first hit; `\"all\"` collects every hit.\n *\n * Reuses the filter-list condition evaluator so operator semantics\n * (numeric coercion on `=`/`!=`, locale-aware ordering, case-sensitive\n * text ops) stay identical to the Filter List node.\n */\nexport function selectByPredicate(\n items: string[],\n config: SelectorConfig,\n): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n // Default operator to \"=\" so the UI's visual default (selector-config.tsx\n // shows `op={config.predicateOp ?? \"=\"}`) matches runtime; first-time\n // predicate use without explicitly setting an operator used to silently\n // return picked=[].\n // predicateField is intentionally allowed to be empty/undefined —\n // evaluateCondition treats an empty path as \"compare against the whole\n // item\" (filter-condition.ts:161), matching the UI placeholder hint\n // \"blank = whole item\" on the field input.\n const op = config.predicateOp ?? \"=\"\n // Pass caseSensitive explicitly. evaluateCondition defaults undefined to\n // `true` (case-sensitive) to preserve legacy callers, but the selector\n // UI checkbox shows unchecked by default — so undefined config must map\n // to case-INsensitive at runtime to match what the user sees.\n const opts = { caseSensitive: config.predicateCaseSensitive ?? false }\n const matchAll = config.predicateMatch === \"all\"\n const cond = {\n id: \"selector-predicate\",\n field: config.predicateField ?? \"\",\n operator: op,\n value: config.predicateValue ?? \"\",\n valueType: \"static\" as const,\n }\n const matchedIndices: number[] = []\n for (let i = 0; i < items.length; i++) {\n const parsed = tryParseJson(items[i])\n const hit = evaluateCondition(parsed, items[i], cond, undefined, opts)\n if (hit) {\n matchedIndices.push(i)\n if (!matchAll) break\n }\n }\n return splitByIndices(items, matchedIndices)\n}\n\n/**\n * Shortcut for `predicate(op=\"=\", match=\"first\")` — pick the first item\n * whose `field` strictly equals `value`. Implemented as a thin wrapper\n * so the UI can offer a 2-field form (\"look up by name\") instead of the\n * full 4-field predicate form.\n */\nexport function selectByNamedKey(\n items: string[],\n field: string | undefined,\n value: string | undefined,\n): SelectorResult {\n return selectByPredicate(items, {\n mode: \"predicate\",\n predicateField: field,\n predicateOp: \"=\",\n predicateValue: value,\n predicateMatch: \"first\",\n })\n}\n\n/**\n * Returns a new SelectorConfig with `{NodeLabel}` refs and `{{trigger.*}}` /\n * `{{now}}` / `{{last_N_*:N}}` template tokens resolved in the four\n * template-aware fields: moduloDivisor, predicateValue, namedKeyValue, seed.\n * All other fields are passed through unchanged. Callers must build\n * `variables` via `buildConditionVariables` (or equivalent) BEFORE calling.\n *\n * Other selector fields (itemIndex, range/list expressions, randomCount, etc.)\n * are treated as literals — they have their own selector-lib syntax and are\n * not resolved against the variable space.\n *\n * Token resolution matches `resolveConditionValue` exactly (both reuse\n * `substituteTriggerTokens`) so the selector's `{{trigger.foo}}` semantics\n * stay in lockstep with filter-list / router conditions.\n *\n * Pure: returns a new object; the input config is not mutated.\n */\nexport function resolveSelectorRefs(\n config: SelectorConfig,\n triggerData: Record<string, unknown> | undefined,\n variables: ReadonlyMap<string, string>,\n): SelectorConfig {\n const resolve = (v: string | undefined): string | undefined => {\n if (v == null) return v\n const refsResolved = resolveNodeRefs(v, variables)\n return substituteTriggerTokens(refsResolved, triggerData)\n }\n return {\n ...config,\n moduloDivisor: resolve(config.moduloDivisor),\n predicateValue: resolve(config.predicateValue),\n namedKeyValue: resolve(config.namedKeyValue),\n seed: resolve(config.seed),\n }\n}\n"]}
|