@nodaro/sdk 2.34.0 → 2.38.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-CFY6XXOT.cjs → chunk-3WNEIBTH.cjs} +37 -33
- package/dist/chunk-3WNEIBTH.cjs.map +1 -0
- package/dist/{chunk-JMOKD6ZP.js → chunk-7CUWAVWB.js} +3 -3
- package/dist/{chunk-JMOKD6ZP.js.map → chunk-7CUWAVWB.js.map} +1 -1
- package/dist/{chunk-E5BM4BLO.js → chunk-7IWVDWSP.js} +20 -3
- package/dist/chunk-7IWVDWSP.js.map +1 -0
- package/dist/{chunk-RHJRLXKY.cjs → chunk-7XOK277W.cjs} +9 -9
- package/dist/{chunk-RHJRLXKY.cjs.map → chunk-7XOK277W.cjs.map} +1 -1
- package/dist/{chunk-3QBH2VE2.cjs → chunk-A7QSOD2S.cjs} +20 -3
- package/dist/chunk-A7QSOD2S.cjs.map +1 -0
- package/dist/{chunk-VV4TZG5S.js → chunk-AUKHMT53.js} +3 -3
- package/dist/chunk-AUKHMT53.js.map +1 -0
- package/dist/{chunk-CWH642B2.js → chunk-AVOQ5DG4.js} +22 -18
- package/dist/chunk-AVOQ5DG4.js.map +1 -0
- package/dist/{chunk-I6CXC345.js → chunk-D2ILCSOQ.js} +3 -3
- package/dist/{chunk-I6CXC345.js.map → chunk-D2ILCSOQ.js.map} +1 -1
- package/dist/{chunk-4NLVBYMW.js → chunk-DQAYIVVS.js} +42 -8
- package/dist/chunk-DQAYIVVS.js.map +1 -0
- package/dist/chunk-ED3ZOX3M.js +54 -0
- package/dist/chunk-ED3ZOX3M.js.map +1 -0
- package/dist/{chunk-5ALNFATQ.cjs → chunk-EK672FFM.cjs} +2 -2
- package/dist/chunk-EK672FFM.cjs.map +1 -0
- package/dist/{chunk-OXQKE5EG.cjs → chunk-ETX3TLNB.cjs} +43 -9
- package/dist/{chunk-4NLVBYMW.js.map → chunk-ETX3TLNB.cjs.map} +1 -1
- package/dist/{chunk-BRV7Z4GD.cjs → chunk-FHVNTS4E.cjs} +2 -2
- package/dist/{chunk-BRV7Z4GD.cjs.map → chunk-FHVNTS4E.cjs.map} +1 -1
- package/dist/{chunk-N6GLZOE4.cjs → chunk-FM2KM5TY.cjs} +52 -10
- package/dist/chunk-FM2KM5TY.cjs.map +1 -0
- package/dist/{chunk-53SXNN3A.js → chunk-FQNCIP6K.js} +2 -2
- package/dist/chunk-FQNCIP6K.js.map +1 -0
- package/dist/{chunk-KNMW722T.cjs → chunk-FRQJNGJS.cjs} +5 -5
- package/dist/{chunk-KNMW722T.cjs.map → chunk-FRQJNGJS.cjs.map} +1 -1
- package/dist/{chunk-4CXB7RA6.js → chunk-IGMWFEFB.js} +6 -4
- package/dist/chunk-IGMWFEFB.js.map +1 -0
- package/dist/{chunk-5MTCKWKA.cjs → chunk-IISVYX5J.cjs} +5 -5
- package/dist/{chunk-5MTCKWKA.cjs.map → chunk-IISVYX5J.cjs.map} +1 -1
- package/dist/{chunk-6OGGJQVA.js → chunk-ILG5DHQQ.js} +2 -2
- package/dist/chunk-ILG5DHQQ.js.map +1 -0
- package/dist/{chunk-ZQQABQMH.cjs → chunk-JTOEHQQJ.cjs} +12 -2
- package/dist/chunk-JTOEHQQJ.cjs.map +1 -0
- package/dist/{chunk-ZXJQSFIA.js → chunk-JUON5NXA.js} +2 -2
- package/dist/{chunk-ZXJQSFIA.js.map → chunk-JUON5NXA.js.map} +1 -1
- package/dist/{chunk-JGS6YBDW.js → chunk-L6T44A3G.js} +51 -11
- package/dist/chunk-L6T44A3G.js.map +1 -0
- package/dist/{chunk-U4T3Z3K7.cjs → chunk-NKH2UFSD.cjs} +5 -5
- package/dist/chunk-NKH2UFSD.cjs.map +1 -0
- package/dist/{chunk-E2ZXHS6E.js → chunk-OIPPTBW4.js} +2 -2
- package/dist/chunk-OIPPTBW4.js.map +1 -0
- package/dist/{chunk-DKEYSJCE.cjs → chunk-OIYMTGYN.cjs} +2 -2
- package/dist/chunk-OIYMTGYN.cjs.map +1 -0
- package/dist/{chunk-NLQQHJ25.cjs → chunk-OSMKIRKI.cjs} +4 -4
- package/dist/{chunk-NLQQHJ25.cjs.map → chunk-OSMKIRKI.cjs.map} +1 -1
- package/dist/chunk-PG2GBS3K.cjs +4 -0
- package/dist/chunk-PG2GBS3K.cjs.map +1 -0
- package/dist/{chunk-GB724HW2.cjs → chunk-PQ7OKM3E.cjs} +6 -4
- package/dist/chunk-PQ7OKM3E.cjs.map +1 -0
- package/dist/{chunk-VFMWBW2Q.js → chunk-Q6HY2Q5V.js} +4 -4
- package/dist/{chunk-VFMWBW2Q.js.map → chunk-Q6HY2Q5V.js.map} +1 -1
- package/dist/chunk-QGOEQGAE.js +102 -0
- package/dist/chunk-QGOEQGAE.js.map +1 -0
- package/dist/{chunk-EAGD6NEE.cjs → chunk-QZHRXPN5.cjs} +22 -22
- package/dist/chunk-QZHRXPN5.cjs.map +1 -0
- package/dist/{chunk-KGKCAGRD.cjs → chunk-TCLNSVYA.cjs} +2 -2
- package/dist/chunk-TCLNSVYA.cjs.map +1 -0
- package/dist/chunk-U2B7YQ2N.cjs +56 -0
- package/dist/chunk-U2B7YQ2N.cjs.map +1 -0
- package/dist/chunk-VCEYLJ2Q.cjs +104 -0
- package/dist/chunk-VCEYLJ2Q.cjs.map +1 -0
- package/dist/{chunk-VGWOIWRQ.cjs → chunk-VHSMOBU7.cjs} +2 -2
- package/dist/{chunk-VGWOIWRQ.cjs.map → chunk-VHSMOBU7.cjs.map} +1 -1
- package/dist/{chunk-T3SYREY4.js → chunk-WY4QRJZW.js} +12 -2
- package/dist/chunk-WY4QRJZW.js.map +1 -0
- package/dist/chunk-YCVRQZT3.js +3 -0
- package/dist/chunk-YCVRQZT3.js.map +1 -0
- package/dist/{chunk-DPSMVOM3.js → chunk-YSZM3N7Q.js} +2 -2
- package/dist/chunk-YSZM3N7Q.js.map +1 -0
- package/dist/{chunk-5A7J24LN.js → chunk-Z7UZ3FD3.js} +3 -3
- package/dist/{chunk-5A7J24LN.js.map → chunk-Z7UZ3FD3.js.map} +1 -1
- package/dist/{chunk-4JKI6JRC.js → chunk-ZDSC6KBT.js} +3 -3
- package/dist/chunk-ZDSC6KBT.js.map +1 -0
- package/dist/entries/apps.cjs +2 -2
- package/dist/entries/apps.d.cts +4 -0
- package/dist/entries/apps.d.ts +4 -0
- package/dist/entries/apps.js +1 -1
- package/dist/entries/cast-swap.cjs +2 -2
- package/dist/entries/cast-swap.d.cts +271 -18
- package/dist/entries/cast-swap.d.ts +271 -18
- package/dist/entries/cast-swap.js +1 -1
- package/dist/entries/characters.d.cts +2 -2
- package/dist/entries/characters.d.ts +2 -2
- package/dist/entries/client.cjs +25 -24
- package/dist/entries/client.d.cts +5 -2
- package/dist/entries/client.d.ts +5 -2
- package/dist/entries/client.js +20 -19
- package/dist/entries/copilot.cjs +4 -4
- package/dist/entries/copilot.js +3 -3
- package/dist/entries/core.cjs +6 -6
- package/dist/entries/core.js +2 -2
- package/dist/entries/creatures.d.cts +2 -2
- package/dist/entries/creatures.d.ts +2 -2
- package/dist/entries/credits.cjs +2 -2
- package/dist/entries/credits.d.cts +37 -2
- package/dist/entries/credits.d.ts +37 -2
- package/dist/entries/credits.js +1 -1
- package/dist/entries/edit.cjs +7 -7
- package/dist/entries/edit.d.cts +3 -0
- package/dist/entries/edit.d.ts +3 -0
- package/dist/entries/edit.js +2 -2
- package/dist/entries/errors.cjs +30 -22
- package/dist/entries/errors.d.cts +42 -4
- package/dist/entries/errors.d.ts +42 -4
- package/dist/entries/errors.js +1 -1
- package/dist/entries/jobs.cjs +2 -2
- package/dist/entries/jobs.d.cts +76 -4
- package/dist/entries/jobs.d.ts +76 -4
- package/dist/entries/jobs.js +1 -1
- package/dist/entries/locations.d.cts +2 -2
- package/dist/entries/locations.d.ts +2 -2
- package/dist/entries/media.cjs +4 -4
- package/dist/entries/media.d.cts +39 -5
- package/dist/entries/media.d.ts +39 -5
- package/dist/entries/media.js +3 -3
- package/dist/entries/nodes.cjs +3 -3
- package/dist/entries/nodes.d.cts +2 -2
- package/dist/entries/nodes.d.ts +2 -2
- package/dist/entries/nodes.js +2 -2
- package/dist/entries/objects.d.cts +2 -2
- package/dist/entries/objects.d.ts +2 -2
- package/dist/entries/prompt-helper.cjs +2 -2
- package/dist/entries/prompt-helper.d.cts +3 -1
- package/dist/entries/prompt-helper.d.ts +3 -1
- package/dist/entries/prompt-helper.js +1 -1
- package/dist/entries/scene3d.d.cts +3 -3
- package/dist/entries/scene3d.d.ts +3 -3
- package/dist/entries/studio.cjs +5 -5
- package/dist/entries/studio.d.cts +2 -2
- package/dist/entries/studio.d.ts +2 -2
- package/dist/entries/studio.js +2 -2
- package/dist/entries/templates.cjs +2 -2
- package/dist/entries/templates.d.cts +4 -0
- package/dist/entries/templates.d.ts +4 -0
- package/dist/entries/templates.js +1 -1
- package/dist/entries/trends.cjs +13 -0
- package/dist/entries/trends.cjs.map +1 -0
- package/dist/entries/trends.d.cts +295 -0
- package/dist/entries/trends.d.ts +295 -0
- package/dist/entries/trends.js +4 -0
- package/dist/entries/trends.js.map +1 -0
- package/dist/entries/tutorials.cjs +2 -2
- package/dist/entries/tutorials.d.cts +4 -0
- package/dist/entries/tutorials.d.ts +4 -0
- package/dist/entries/tutorials.js +1 -1
- package/dist/entries/uploads.cjs +2 -2
- package/dist/entries/uploads.d.cts +14 -1
- package/dist/entries/uploads.d.ts +14 -1
- package/dist/entries/uploads.js +1 -1
- package/dist/entries/workflows.cjs +2 -2
- package/dist/entries/workflows.d.cts +6 -0
- package/dist/entries/workflows.d.ts +6 -0
- package/dist/entries/workflows.js +1 -1
- package/dist/index.cjs +85 -71
- package/dist/index.d.cts +8 -7
- package/dist/index.d.ts +8 -7
- package/dist/index.js +22 -20
- package/dist/{nodes-D2tbtzt7.d.ts → nodes-9WpYNWtS.d.ts} +13 -1
- package/dist/{nodes-CTujw6Qd.d.cts → nodes-BDUk5Aej.d.cts} +13 -1
- package/dist/{studio-productions-vbCNSbtf.d.ts → studio-productions-DtTE8mdl.d.ts} +35 -1
- package/dist/{studio-productions-DUHvdSvk.d.cts → studio-productions-r2-VZsKj.d.cts} +35 -1
- package/package.json +7 -2
- package/dist/chunk-3QBH2VE2.cjs.map +0 -1
- package/dist/chunk-4CXB7RA6.js.map +0 -1
- package/dist/chunk-4JKI6JRC.js.map +0 -1
- package/dist/chunk-53SXNN3A.js.map +0 -1
- package/dist/chunk-5ALNFATQ.cjs.map +0 -1
- package/dist/chunk-6OGGJQVA.js.map +0 -1
- package/dist/chunk-CFY6XXOT.cjs.map +0 -1
- package/dist/chunk-CWH642B2.js.map +0 -1
- package/dist/chunk-DKEYSJCE.cjs.map +0 -1
- package/dist/chunk-DPSMVOM3.js.map +0 -1
- package/dist/chunk-E2ZXHS6E.js.map +0 -1
- package/dist/chunk-E5BM4BLO.js.map +0 -1
- package/dist/chunk-EAGD6NEE.cjs.map +0 -1
- package/dist/chunk-GB724HW2.cjs.map +0 -1
- package/dist/chunk-GDXS4EJ5.js +0 -28
- package/dist/chunk-GDXS4EJ5.js.map +0 -1
- package/dist/chunk-GVBSOZDI.cjs +0 -30
- package/dist/chunk-GVBSOZDI.cjs.map +0 -1
- package/dist/chunk-JGS6YBDW.js.map +0 -1
- package/dist/chunk-KGKCAGRD.cjs.map +0 -1
- package/dist/chunk-N6GLZOE4.cjs.map +0 -1
- package/dist/chunk-OXQKE5EG.cjs.map +0 -1
- package/dist/chunk-T3SYREY4.js.map +0 -1
- package/dist/chunk-U4T3Z3K7.cjs.map +0 -1
- package/dist/chunk-VV4TZG5S.js.map +0 -1
- package/dist/chunk-ZQQABQMH.cjs.map +0 -1
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// src/resources/trends.ts
|
|
2
|
+
var RESERVED_SLUGS = {
|
|
3
|
+
runs: "the run list; use runs()",
|
|
4
|
+
tags: "the tag list; use tags()"
|
|
5
|
+
};
|
|
6
|
+
function trendPath(slug, rest = "") {
|
|
7
|
+
if (Object.hasOwn(RESERVED_SLUGS, slug)) {
|
|
8
|
+
throw new TypeError(`"${slug}" is not a trend slug (it is reserved for ${RESERVED_SLUGS[slug]})`);
|
|
9
|
+
}
|
|
10
|
+
return `/v1/trends/${encodeURIComponent(slug)}${rest}`;
|
|
11
|
+
}
|
|
12
|
+
var TrendsResource = class {
|
|
13
|
+
constructor(client) {
|
|
14
|
+
this.client = client;
|
|
15
|
+
}
|
|
16
|
+
client;
|
|
17
|
+
/** The published catalog in its curated order (`GET /v1/trends`), a page at a time. */
|
|
18
|
+
list(params = {}) {
|
|
19
|
+
const query = {};
|
|
20
|
+
if (params.q) query.q = params.q;
|
|
21
|
+
if (params.tag) query.tag = params.tag;
|
|
22
|
+
if (params.favorites) query.favorites = "1";
|
|
23
|
+
if (params.locale) query.locale = params.locale;
|
|
24
|
+
if (params.cursor) query.cursor = params.cursor;
|
|
25
|
+
if (params.limit !== void 0) query.limit = String(params.limit);
|
|
26
|
+
return this.client.request("GET", "/v1/trends", { query });
|
|
27
|
+
}
|
|
28
|
+
/** A published trend's page (`GET /v1/trends/:slug`). */
|
|
29
|
+
async get(slug, params = {}) {
|
|
30
|
+
const query = {};
|
|
31
|
+
if (params.locale) query.locale = params.locale;
|
|
32
|
+
const res = await this.client.request("GET", trendPath(slug), { query });
|
|
33
|
+
return res.data;
|
|
34
|
+
}
|
|
35
|
+
/** Quote a run before starting it (`POST /v1/trends/:slug/estimate`); spends nothing. */
|
|
36
|
+
async estimate(slug, request) {
|
|
37
|
+
const res = await this.client.request(
|
|
38
|
+
"POST",
|
|
39
|
+
trendPath(slug, "/estimate"),
|
|
40
|
+
{ body: request }
|
|
41
|
+
);
|
|
42
|
+
return res.data;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Start a run (`POST /v1/trends/:slug/runs`, 202). Returns the job to follow.
|
|
46
|
+
* With `options.idempotencyKey` (sent as the `Idempotency-Key` header) a
|
|
47
|
+
* repeat with the same key answers with the first run's `jobId`.
|
|
48
|
+
*/
|
|
49
|
+
async run(slug, request, options) {
|
|
50
|
+
const res = await this.client.request(
|
|
51
|
+
"POST",
|
|
52
|
+
trendPath(slug, "/runs"),
|
|
53
|
+
{
|
|
54
|
+
body: request,
|
|
55
|
+
...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {}
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
return res.data;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Your trend runs, newest first (`GET /v1/trends/runs`). A Full Quality
|
|
62
|
+
* version of a draft is listed as its own run (`fullQualityOf`).
|
|
63
|
+
*/
|
|
64
|
+
runs(params = {}) {
|
|
65
|
+
const query = {};
|
|
66
|
+
if (params.trend) query.trend = params.trend;
|
|
67
|
+
if (params.cursor) query.cursor = params.cursor;
|
|
68
|
+
if (params.limit !== void 0) query.limit = String(params.limit);
|
|
69
|
+
return this.client.request("GET", "/v1/trends/runs", { query });
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* One of your trend runs by its job id (`GET /v1/trends/runs/:jobId`), in
|
|
73
|
+
* the same shape as `runs()`. A job that is not your own trend run is a
|
|
74
|
+
* `NotFoundError`.
|
|
75
|
+
*/
|
|
76
|
+
async getRun(jobId) {
|
|
77
|
+
const res = await this.client.request("GET", `/v1/trends/runs/${encodeURIComponent(jobId)}`);
|
|
78
|
+
return res.data;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The tags in use on the published catalog, each with its label in the
|
|
82
|
+
* resolved locale (`GET /v1/trends/tags`), most used first.
|
|
83
|
+
*/
|
|
84
|
+
async tags(params = {}) {
|
|
85
|
+
const query = {};
|
|
86
|
+
if (params.locale) query.locale = params.locale;
|
|
87
|
+
const res = await this.client.request("GET", "/v1/trends/tags", { query });
|
|
88
|
+
return res.data;
|
|
89
|
+
}
|
|
90
|
+
/** Add a trend to your favorites (`PUT /v1/trends/:slug/favorite`). */
|
|
91
|
+
async favorite(slug) {
|
|
92
|
+
await this.client.request("PUT", trendPath(slug, "/favorite"));
|
|
93
|
+
}
|
|
94
|
+
/** Remove a trend from your favorites (`DELETE /v1/trends/:slug/favorite`). */
|
|
95
|
+
async unfavorite(slug) {
|
|
96
|
+
await this.client.request("DELETE", trendPath(slug, "/favorite"));
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export { TrendsResource };
|
|
101
|
+
//# sourceMappingURL=chunk-QGOEQGAE.js.map
|
|
102
|
+
//# sourceMappingURL=chunk-QGOEQGAE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/trends.ts"],"names":[],"mappings":";AAoDA,IAAM,cAAA,GAAmD;AAAA,EACvD,IAAA,EAAM,0BAAA;AAAA,EACN,IAAA,EAAM;AACR,CAAA;AAEA,SAAS,SAAA,CAAU,IAAA,EAAc,IAAA,GAAO,EAAA,EAAY;AAClD,EAAA,IAAI,MAAA,CAAO,MAAA,CAAO,cAAA,EAAgB,IAAI,CAAA,EAAG;AACvC,IAAA,MAAM,IAAI,UAAU,CAAA,CAAA,EAAI,IAAI,6CAA6C,cAAA,CAAe,IAAI,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EAClG;AACA,EAAA,OAAO,CAAA,WAAA,EAAc,kBAAA,CAAmB,IAAI,CAAC,GAAG,IAAI,CAAA,CAAA;AACtD;AA2PO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,IAAA,CAAK,MAAA,GAA2B,EAAC,EAAkC;AACjE,IAAA,MAAM,QAAgC,EAAC;AACvC,IAAA,IAAI,MAAA,CAAO,CAAA,EAAG,KAAA,CAAM,CAAA,GAAI,MAAA,CAAO,CAAA;AAC/B,IAAA,IAAI,MAAA,CAAO,GAAA,EAAK,KAAA,CAAM,GAAA,GAAM,MAAA,CAAO,GAA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,MAAA;AACzC,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAA8B,KAAA,EAAO,iBAAA,EAAmB,EAAE,KAAA,EAAO,CAAA;AAC/F,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,SAAS,IAAA,EAA6B;AAC1C,IAAA,MAAM,KAAK,MAAA,CAAO,OAAA,CAAc,OAAO,SAAA,CAAU,IAAA,EAAM,WAAW,CAAC,CAAA;AAAA,EACrE;AAAA;AAAA,EAGA,MAAM,WAAW,IAAA,EAA6B;AAC5C,IAAA,MAAM,KAAK,MAAA,CAAO,OAAA,CAAc,UAAU,SAAA,CAAU,IAAA,EAAM,WAAW,CAAC,CAAA;AAAA,EACxE;AACF","file":"chunk-QGOEQGAE.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Trends — ready-made Cast Swap recipes. A trend is a short clip with slots\n * (the people, pets, products and place you can replace); fill its slots with\n * your own pictures and run it to get the clip back with them in it.\n *\n * Cloud edition only: `/v1/trends` 404s on self-hosted installs. Only\n * published trends exist here: a draft, unpublished or unknown slug is a 404\n * on every route. `\"runs\"` and `\"tags\"` are never slugs (`/v1/trends/runs` is\n * the run list, `/v1/trends/tags` the tag list): the slug methods throw a\n * `TypeError` for them before any request. `run()` answers 202 with a job id; follow it with\n * `client.jobs.get(jobId)` / `client.jobs.getStatus(jobId)` like any other\n * job, or read it back as a trend run with `getRun(jobId)` / `runs()`.\n *\n * Repeats: pass `{ idempotencyKey }` to `run()` and it is sent as the\n * `Idempotency-Key` header. A repeat with the same key answers with the first\n * run's `jobId`; nothing new is started or charged.\n *\n * Refusals (thrown as a `NodaroError` subclass; body `{ error: { code, message } }`):\n * - 400 `validation_error` (the body, a query, or a bad `cursor`);\n * `estimate()` / `run()` only, before anything is charged:\n * `missing_slot` (a required slot without pictures, or an optional one\n * left empty that the chosen example has no pictures for), `unknown_slot`,\n * `invalid_choice` (a chip the slot's kind does not take),\n * `example_out_of_range` (`example` names none, or an optional slot is left\n * empty and the trend has no example to fill it), `preview_unavailable` (the trend offers no\n * preview), `invalid_slot_mention` (a `{slot:<key>}` in `details` naming no\n * slot), `prompt_too_long` (shorten `details`). The slot errors carry the\n * slot's key as `slot`.\n * - 401 `unauthorized`.\n * - 404 `not_found`: the trend is not published (every method), or `run()`'s\n * `sessionId` is not a session you may use.\n * - 502 `engine_error` (`estimate()` / `run()`).\n * - 503 `engine_unsupported` (this platform version cannot run trends yet),\n * `trend_unavailable` (`estimate()` / `run()`), `not_available` (this\n * server has no trend catalog yet).\n * - `estimate()` / `run()` answer the video engine's refusals with the trend\n * routes' OWN codes and fixed messages — never the engine's text or\n * `issues`: 400 `trend_run_rejected` (the inputs could not run), or\n * `clip_out_of_range` / `preview_out_of_range` / `video_unreadable` (this\n * trend's clip), `unsafe_url` (a picture is not a public http(s) address),\n * `raw_reference_token` (`details` holds `{image:` / `{video:` /\n * `{audio:`); 402 `insufficient_credits` (or a workspace cap) as given;\n * 413 `storage_limit_exceeded`; 422 `job_blocked` (the job policy\n * blocked it); 429 `rate_limited`; 503 `engine_unsupported`,\n * `estimate_unavailable`; 502 `engine_error` for anything else. `run()`\n * also answers 400 `validation_error` for an `idempotencyKey` outside\n * 8–200 characters.\n */\n\n/** `/v1/trends/runs` is the run list and `/v1/trends/tags` the tag list, so neither can be a trend's slug. */\nconst RESERVED_SLUGS: Readonly<Record<string, string>> = {\n runs: \"the run list; use runs()\",\n tags: \"the tag list; use tags()\",\n}\n\nfunction trendPath(slug: string, rest = \"\"): string {\n if (Object.hasOwn(RESERVED_SLUGS, slug)) {\n throw new TypeError(`\"${slug}\" is not a trend slug (it is reserved for ${RESERVED_SLUGS[slug]})`)\n }\n return `/v1/trends/${encodeURIComponent(slug)}${rest}`\n}\n\n/** What a slot holds. */\nexport type TrendSlotKind = \"person\" | \"location\" | \"product\" | \"pet\"\n\n/** A chip: make this trait anew from your pictures (`\"new\"`), or keep the clip's (`\"original\"`). */\nexport type TrendChoice = \"new\" | \"original\"\n\n/**\n * The chips a slot can take, by its kind: a person `body` / `outfit` / `hair`,\n * a pet `body` / `coat`, a product `shape` / `finish`, a location none.\n */\nexport interface TrendChips {\n body?: TrendChoice\n outfit?: TrendChoice\n hair?: TrendChoice\n coat?: TrendChoice\n shape?: TrendChoice\n finish?: TrendChoice\n}\n\nexport type TrendResolution = \"480p\" | \"720p\" | \"1080p\"\n\n/** A trend in the catalog (`list()`). Text is in the resolved locale. */\nexport interface TrendCard {\n id: string\n slug: string\n name: string\n description?: string\n tags: string[]\n /** e.g. `\"trending\"`, `\"new\"`. */\n badges: string[]\n /** The trend's first example (never the clip it recasts). */\n cover: { videoUrl: string; posterUrl?: string; width: number; height: number }\n /** How many slots of each kind the trend has. */\n needs: Record<TrendSlotKind, number>\n /** The length of a full run, in seconds. */\n durationSec: number\n isFavorite: boolean\n}\n\n/** One slot of a trend: what it asks you for. */\nexport interface TrendDetailSlot {\n /** The key to fill in {@link TrendRunRequest.slots}, and to mention in `details` as `{slot:<key>}`. */\n key: string\n label: string\n kind: TrendSlotKind\n /** A required slot needs pictures; an optional one left empty takes the chosen example's. */\n required: boolean\n hint?: string\n /** The chips this slot starts with (only its kind's own). */\n defaults?: TrendChips\n}\n\n/** A finished run shown on a trend's page, with the pictures it used per slot. */\nexport interface TrendExample {\n videoUrl: string\n posterUrl?: string\n width: number\n height: number\n /** Slot key → the pictures this example used for it. */\n slots: Record<string, string[]>\n}\n\n/** A trend's page (`get()`). */\nexport interface TrendDetail extends TrendCard {\n /** The published version this page shows. */\n version: number\n /** `4` when the trend offers a 4-second preview run, else `null`. */\n previewSec: 4 | null\n resolutions: TrendResolution[]\n slots: TrendDetailSlot[]\n examples: TrendExample[]\n}\n\n/** What you put in one slot of a run: 1–3 pictures, and the chips of the slot's kind. */\nexport interface TrendRunSlot extends TrendChips {\n images?: string[]\n}\n\n/** The body of `estimate()` and `run()`. */\nexport interface TrendRunRequest {\n /**\n * Slot key → what you put in it. Every required slot needs pictures; an\n * optional slot left out takes the chosen example's. 1–3 pictures per slot.\n */\n slots: Record<string, TrendRunSlot>\n /** 1-based example whose pictures fill the optional slots you leave empty. Default 1. */\n example?: number\n /** Your own words, at most 1,000 characters. Mention a slot as `{slot:<key>}`. */\n details?: string\n /** `true` runs a 4-second preview (only when the trend's `previewSec` is `4`). */\n preview?: boolean\n /** Default `\"480p\"`. */\n resolution?: TrendResolution\n /** A draft run, only at 480p. Default `true` at 480p. */\n draft?: boolean\n /**\n * A generation session of yours. Accepted (and checked: one you may not use\n * is a 404), but not yet applied: trend runs are not filed into sessions yet.\n */\n sessionId?: string\n /** Accepted, but not used by the run today. */\n projectId?: string\n /**\n * A full run's own preview: the `jobId` of a completed preview run of this\n * trend that you started. When the trend masks faces only as needed and that\n * preview needed it, the full run masks them from the start (the quote\n * includes it). Any other job is ignored, without an error. Must be a uuid\n * (else 400 `validation_error`).\n */\n previewJobId?: string\n /**\n * `run()`: your client app's slug (e.g. `\"tools\"`: lowercase letters,\n * digits and `-`, 1–40 characters, starting with a letter or digit), as on\n * any job: the run's job carries it as `input_data.origin`, so\n * `client.jobs.list({ origin })` finds it. Not a slug is a 400\n * `validation_error`; without it the run has no origin. `estimate()`\n * ignores it.\n */\n origin?: string\n}\n\n/** What a run would cost, in credits (`estimate()`). */\nexport interface TrendEstimate {\n /** The charge the run is expected to come to. */\n expectedCredits: number\n /** What is reserved when the run starts; the run is charged what it actually costs. */\n holdCredits: number\n /**\n * The parts of the quote, by name. With `maskingCredits`, `masking` is\n * listed here too but is not part of `holdCredits` or `expectedCredits`.\n */\n breakdown: Record<string, number>\n /**\n * Only for a trend that masks faces only as needed: the extra credits\n * charged if the video model refuses the clip and the run is retried with\n * the faces masked. Not included in `expectedCredits` or `holdCredits`.\n */\n maskingCredits?: number\n}\n\n/** Per-call options for {@link TrendsResource.run}. */\nexport interface TrendRunOptions {\n /**\n * Sent as the `Idempotency-Key` header, unchanged (an empty string sends no\n * header). The server takes 8–200 characters and answers 400 for any other\n * length. Reuse it when retrying the same run.\n */\n idempotencyKey?: string\n}\n\n/** One slot of a past run, as it was run. Labels are English. */\nexport interface TrendRunDisplaySlot extends TrendChips {\n key: string\n label: string\n kind: TrendSlotKind\n images: string[]\n /** `true` when the slot was left empty and the example's pictures filled it. */\n fromExample: boolean\n}\n\n/**\n * One of your trend runs (`runs()`, `getRun()`). Stays readable after the\n * trend moves on or is unpublished.\n *\n * A Full Quality version of a draft is a run of its own, with its own status,\n * result and charge: `fullQualityOf` names the draft it was made from, and it\n * stays listed after that draft is deleted.\n */\nexport interface TrendRun {\n jobId: string\n status: string\n progress: number | null\n /**\n * Why a failed or cancelled run did not finish; `null` otherwise. `code` is\n * `safety-block` or `policy-block` when the job was blocked, `credits` when\n * it ran out of credits partway (it was refunded: ask the person to top up,\n * then run it again), else `cancelled` or `failed`. `message` is the same\n * fixed sentence for every code — branch on `code`, not on the text.\n */\n error: { code?: string; message: string } | null\n createdAt: string\n completedAt: string | null\n /** The trend and version it ran (name in English). */\n trend: { id: string; slug: string; version: number; name: string }\n /** The 1-based example used for empty optional slots. */\n example: number\n slots: TrendRunDisplaySlot[]\n details?: string\n preview: boolean\n resolution: string\n draft: boolean\n /** The result, once completed. */\n videoUrl: string | null\n posterUrl: string | null\n creditsCharged: number | null\n /** A Full Quality version: the job id of the draft run it was made from. `null` for any other run. */\n fullQualityOf: string | null\n /**\n * A draft's newest Full Quality try, if one was started: a pointer only,\n * to know an upgrade exists and how it is going. Its video and charge are on\n * that run, listed on its own (its `fullQualityOf` is this run's `jobId`) —\n * read it there (`getRun(fullQuality.jobId)`). Older tries of the draft (a\n * failed or cancelled one tried again) are not listed by `runs()`;\n * `getRun()` still reads one by its id.\n */\n fullQuality: { jobId: string; status: string } | null\n /** Until when a completed draft can be redone in Full Quality; `null` otherwise. */\n fullQualityUntil: string | null\n}\n\nexport interface ListTrendsParams {\n /** Search text. */\n q?: string\n tag?: string\n /** `true` lists only your favorites. */\n favorites?: boolean\n /** A platform language for names and descriptions; default your profile's, then English. */\n locale?: string\n /** The previous page's `next`. */\n cursor?: string\n /** Page size, 1–60 (server default 30). */\n limit?: number\n}\n\nexport interface ListTrendRunsParams {\n /** Only runs of this trend (its slug). */\n trend?: string\n /** The previous page's `next`. */\n cursor?: string\n /** Page size, 1–60 (server default 30). */\n limit?: number\n}\n\n/** A tag in use on the published catalog (`tags()`). */\nexport interface TrendTag {\n /** The tag itself: pass it as `list({ tag })`. */\n tag: string\n /** The tag's label in the resolved locale; the tag itself when it has none. */\n label: string\n /** How many published trends carry it. */\n count: number\n}\n\nexport interface TrendPage<T> {\n data: T[]\n /** Pass back as `cursor` for the next page; `null` on the last one. */\n next: string | null\n}\n\nexport class TrendsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** The published catalog in its curated order (`GET /v1/trends`), a page at a time. */\n list(params: ListTrendsParams = {}): Promise<TrendPage<TrendCard>> {\n const query: Record<string, string> = {}\n if (params.q) query.q = params.q\n if (params.tag) query.tag = params.tag\n if (params.favorites) query.favorites = \"1\"\n if (params.locale) query.locale = params.locale\n if (params.cursor) query.cursor = params.cursor\n if (params.limit !== undefined) query.limit = String(params.limit)\n return this.client.request(\"GET\", \"/v1/trends\", { query })\n }\n\n /** A published trend's page (`GET /v1/trends/:slug`). */\n async get(slug: string, params: { locale?: string } = {}): Promise<TrendDetail> {\n const query: Record<string, string> = {}\n if (params.locale) query.locale = params.locale\n const res = await this.client.request<{ data: TrendDetail }>(\"GET\", trendPath(slug), { query })\n return res.data\n }\n\n /** Quote a run before starting it (`POST /v1/trends/:slug/estimate`); spends nothing. */\n async estimate(slug: string, request: TrendRunRequest): Promise<TrendEstimate> {\n const res = await this.client.request<{ data: TrendEstimate }>(\n \"POST\",\n trendPath(slug, \"/estimate\"),\n { body: request },\n )\n return res.data\n }\n\n /**\n * Start a run (`POST /v1/trends/:slug/runs`, 202). Returns the job to follow.\n * With `options.idempotencyKey` (sent as the `Idempotency-Key` header) a\n * repeat with the same key answers with the first run's `jobId`.\n */\n async run(slug: string, request: TrendRunRequest, options?: TrendRunOptions): Promise<{ jobId: string }> {\n const res = await this.client.request<{ data: { jobId: string } }>(\n \"POST\",\n trendPath(slug, \"/runs\"),\n {\n body: request,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n },\n )\n return res.data\n }\n\n /**\n * Your trend runs, newest first (`GET /v1/trends/runs`). A Full Quality\n * version of a draft is listed as its own run (`fullQualityOf`).\n */\n runs(params: ListTrendRunsParams = {}): Promise<TrendPage<TrendRun>> {\n const query: Record<string, string> = {}\n if (params.trend) query.trend = params.trend\n if (params.cursor) query.cursor = params.cursor\n if (params.limit !== undefined) query.limit = String(params.limit)\n return this.client.request(\"GET\", \"/v1/trends/runs\", { query })\n }\n\n /**\n * One of your trend runs by its job id (`GET /v1/trends/runs/:jobId`), in\n * the same shape as `runs()`. A job that is not your own trend run is a\n * `NotFoundError`.\n */\n async getRun(jobId: string): Promise<TrendRun> {\n const res = await this.client.request<{ data: TrendRun }>(\"GET\", `/v1/trends/runs/${encodeURIComponent(jobId)}`)\n return res.data\n }\n\n /**\n * The tags in use on the published catalog, each with its label in the\n * resolved locale (`GET /v1/trends/tags`), most used first.\n */\n async tags(params: { locale?: string } = {}): Promise<TrendTag[]> {\n const query: Record<string, string> = {}\n if (params.locale) query.locale = params.locale\n const res = await this.client.request<{ data: TrendTag[] }>(\"GET\", \"/v1/trends/tags\", { query })\n return res.data\n }\n\n /** Add a trend to your favorites (`PUT /v1/trends/:slug/favorite`). */\n async favorite(slug: string): Promise<void> {\n await this.client.request<void>(\"PUT\", trendPath(slug, \"/favorite\"))\n }\n\n /** Remove a trend from your favorites (`DELETE /v1/trends/:slug/favorite`). */\n async unfavorite(slug: string): Promise<void> {\n await this.client.request<void>(\"DELETE\", trendPath(slug, \"/favorite\"))\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkFM2KM5TY_cjs = require('./chunk-FM2KM5TY.cjs');
|
|
4
4
|
var nodes = require('@nodaro/shared/nodes');
|
|
5
5
|
var social = require('@nodaro/shared/social');
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ var DEFAULT_POLL_MS = 2e3;
|
|
|
8
8
|
var DEFAULT_MAX_MS = 15 * 60 * 1e3;
|
|
9
9
|
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
10
10
|
if (signal?.aborted) {
|
|
11
|
-
reject(new
|
|
11
|
+
reject(new chunkFM2KM5TY_cjs.JobAbortedError());
|
|
12
12
|
return;
|
|
13
13
|
}
|
|
14
14
|
const timer = setTimeout(() => {
|
|
@@ -17,20 +17,20 @@ var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
|
17
17
|
}, ms);
|
|
18
18
|
function onAbort() {
|
|
19
19
|
clearTimeout(timer);
|
|
20
|
-
reject(new
|
|
20
|
+
reject(new chunkFM2KM5TY_cjs.JobAbortedError());
|
|
21
21
|
}
|
|
22
22
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
23
23
|
});
|
|
24
24
|
function notRunnable(type, why) {
|
|
25
|
-
return new
|
|
25
|
+
return new chunkFM2KM5TY_cjs.NodaroError(`Node type "${type}" has no route of its own to run it directly: ${why}.`, "node_not_runnable", 0);
|
|
26
26
|
}
|
|
27
|
-
var isRouteNotFound = (err) => err instanceof
|
|
27
|
+
var isRouteNotFound = (err) => err instanceof chunkFM2KM5TY_cjs.NotFoundError && /^Route\b.*\bnot found\b/i.test(err.message);
|
|
28
28
|
function extractJobId(result, label) {
|
|
29
29
|
if (result && typeof result === "object" && "jobId" in result) {
|
|
30
30
|
const jobId = result.jobId;
|
|
31
31
|
if (typeof jobId === "string") return jobId;
|
|
32
32
|
}
|
|
33
|
-
throw new
|
|
33
|
+
throw new chunkFM2KM5TY_cjs.JobFailedError(`${label} did not return a jobId`, "");
|
|
34
34
|
}
|
|
35
35
|
function isImageBatchRequest(type, params) {
|
|
36
36
|
if (type !== "generate-image") return false;
|
|
@@ -41,7 +41,7 @@ function batchJobIds(result) {
|
|
|
41
41
|
return Array.isArray(ids) && ids.every((id) => typeof id === "string") ? ids : null;
|
|
42
42
|
}
|
|
43
43
|
function batchRefusal(detail) {
|
|
44
|
-
return new
|
|
44
|
+
return new chunkFM2KM5TY_cjs.NodaroError(
|
|
45
45
|
`${detail}: this waits for one job \u2014 use nodes.runBatchAndWait() for a batch (count above 1, or models).`,
|
|
46
46
|
"batch_requires_run_batch_and_wait",
|
|
47
47
|
0
|
|
@@ -88,7 +88,7 @@ var NodesResource = class {
|
|
|
88
88
|
return res.data;
|
|
89
89
|
}
|
|
90
90
|
async runAndWait(type, params = {}, opts = {}) {
|
|
91
|
-
if (opts.signal?.aborted) throw new
|
|
91
|
+
if (opts.signal?.aborted) throw new chunkFM2KM5TY_cjs.JobAbortedError();
|
|
92
92
|
if (isImageBatchRequest(type, params)) throw batchRefusal(`${type} with count above 1 or models makes several jobs`);
|
|
93
93
|
const result = await this.run(type, params, { idempotencyKey: opts.idempotencyKey });
|
|
94
94
|
const ids = batchJobIds(result);
|
|
@@ -113,9 +113,9 @@ var NodesResource = class {
|
|
|
113
113
|
* `not_a_batch`) — wait for it with {@link runAndWait}.
|
|
114
114
|
*/
|
|
115
115
|
async runBatchAndWait(type, params, opts = {}) {
|
|
116
|
-
if (opts.signal?.aborted) throw new
|
|
116
|
+
if (opts.signal?.aborted) throw new chunkFM2KM5TY_cjs.JobAbortedError();
|
|
117
117
|
if (!isImageBatchRequest(type, params)) {
|
|
118
|
-
throw new
|
|
118
|
+
throw new chunkFM2KM5TY_cjs.NodaroError(
|
|
119
119
|
"runBatchAndWait waits for a batch \u2014 count above 1, or models; wait for one image with nodes.runAndWait().",
|
|
120
120
|
"not_a_batch",
|
|
121
121
|
0
|
|
@@ -123,7 +123,7 @@ var NodesResource = class {
|
|
|
123
123
|
}
|
|
124
124
|
const result = await this.run(type, params, { idempotencyKey: opts.idempotencyKey });
|
|
125
125
|
const batch = batchResultOf(result);
|
|
126
|
-
if (!batch) throw new
|
|
126
|
+
if (!batch) throw new chunkFM2KM5TY_cjs.JobFailedError(`${type} did not answer with a batch`, "");
|
|
127
127
|
const modelOf = new Map(batch.groups.flatMap((group) => group.jobIds.map((id) => [id, group.model])));
|
|
128
128
|
const results = await Promise.all(
|
|
129
129
|
batch.jobIds.map(async (jobId) => {
|
|
@@ -131,7 +131,7 @@ var NodesResource = class {
|
|
|
131
131
|
try {
|
|
132
132
|
return { jobId, model, status: "completed", output: await this.pollJob(jobId, type, opts) };
|
|
133
133
|
} catch (err) {
|
|
134
|
-
if (err instanceof
|
|
134
|
+
if (err instanceof chunkFM2KM5TY_cjs.JobAbortedError || !(err instanceof chunkFM2KM5TY_cjs.NodaroError)) throw err;
|
|
135
135
|
return { jobId, model, status: "error", error: err };
|
|
136
136
|
}
|
|
137
137
|
})
|
|
@@ -152,13 +152,13 @@ var NodesResource = class {
|
|
|
152
152
|
* @param opts Shared `signal` / `cancelOnAbort` / `onProgress` / `pollMs` / `maxMs`.
|
|
153
153
|
*/
|
|
154
154
|
async runMany(type, paramsList, opts = {}) {
|
|
155
|
-
if (opts.signal?.aborted) throw new
|
|
155
|
+
if (opts.signal?.aborted) throw new chunkFM2KM5TY_cjs.JobAbortedError();
|
|
156
156
|
if (paramsList.some((params) => isImageBatchRequest(type, params))) {
|
|
157
157
|
throw batchRefusal(`a ${type} entry with count above 1 or models makes several jobs`);
|
|
158
158
|
}
|
|
159
159
|
return Promise.all(
|
|
160
160
|
paramsList.map(async (params) => {
|
|
161
|
-
if (opts.signal?.aborted) throw new
|
|
161
|
+
if (opts.signal?.aborted) throw new chunkFM2KM5TY_cjs.JobAbortedError();
|
|
162
162
|
const result = await this.run(type, params);
|
|
163
163
|
const jobId = extractJobId(result, type);
|
|
164
164
|
const output = await this.pollJob(jobId, type, opts);
|
|
@@ -173,9 +173,9 @@ var NodesResource = class {
|
|
|
173
173
|
try {
|
|
174
174
|
return await this.pollUntilSettled(jobId, label, opts);
|
|
175
175
|
} catch (err) {
|
|
176
|
-
if (!(err instanceof
|
|
176
|
+
if (!(err instanceof chunkFM2KM5TY_cjs.JobAbortedError)) throw err;
|
|
177
177
|
if (opts.cancelOnAbort) await this.client.jobs.cancel(jobId).catch(() => void 0);
|
|
178
|
-
throw err.jobId ? err : new
|
|
178
|
+
throw err.jobId ? err : new chunkFM2KM5TY_cjs.JobAbortedError(err.message, jobId);
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
/** Poll an already-kicked job id until it stops moving; resolve output_data
|
|
@@ -187,24 +187,24 @@ var NodesResource = class {
|
|
|
187
187
|
const maxMs = opts.maxMs ?? DEFAULT_MAX_MS;
|
|
188
188
|
const deadline = Date.now() + maxMs;
|
|
189
189
|
for (; ; ) {
|
|
190
|
-
if (opts.signal?.aborted) throw new
|
|
190
|
+
if (opts.signal?.aborted) throw new chunkFM2KM5TY_cjs.JobAbortedError(void 0, jobId);
|
|
191
191
|
const { data } = await this.client.jobs.getStatus(jobId);
|
|
192
192
|
opts.onProgress?.(data);
|
|
193
193
|
if (data.status === "completed") {
|
|
194
194
|
return data.output_data ?? {};
|
|
195
195
|
}
|
|
196
196
|
if (data.status === "failed" || data.status === "cancelled") {
|
|
197
|
-
throw new
|
|
197
|
+
throw new chunkFM2KM5TY_cjs.JobFailedError(
|
|
198
198
|
data.error_message ?? `${label} ${data.status}`,
|
|
199
199
|
jobId,
|
|
200
200
|
data.status
|
|
201
201
|
);
|
|
202
202
|
}
|
|
203
203
|
if (data.status === "pending_review") {
|
|
204
|
-
throw new
|
|
204
|
+
throw new chunkFM2KM5TY_cjs.JobHeldError(`${label} is awaiting review`, jobId);
|
|
205
205
|
}
|
|
206
206
|
if (Date.now() > deadline) {
|
|
207
|
-
throw new
|
|
207
|
+
throw new chunkFM2KM5TY_cjs.JobTimeoutError(`${label} timed out`, jobId, maxMs);
|
|
208
208
|
}
|
|
209
209
|
await sleep(pollMs, opts.signal);
|
|
210
210
|
}
|
|
@@ -212,5 +212,5 @@ var NodesResource = class {
|
|
|
212
212
|
};
|
|
213
213
|
|
|
214
214
|
exports.NodesResource = NodesResource;
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
216
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-QZHRXPN5.cjs.map
|
|
216
|
+
//# sourceMappingURL=chunk-QZHRXPN5.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/nodes.ts"],"names":["JobAbortedError","NodaroError","NotFoundError","JobFailedError","nodeRunRoute","NODE_TYPES_WITHOUT_RUN_ROUTE","SOCIAL_POST_NODE_PLATFORM","NODE_RUN_ROUTES","JobHeldError","JobTimeoutError"],"mappings":";;;;;;AAirBA,IAAM,eAAA,GAAkB,GAAA;AAExB,IAAM,cAAA,GAAiB,KAAK,EAAA,GAAK,GAAA;AAEjC,IAAM,KAAA,GAAQ,CAAC,EAAA,EAAY,MAAA,KACzB,IAAI,OAAA,CAAc,CAAC,SAAS,MAAA,KAAW;AACrC,EAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,IAAA,MAAA,CAAO,IAAIA,mCAAiB,CAAA;AAC5B,IAAA;AAAA,EACF;AACA,EAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,IAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC5C,IAAA,OAAA,EAAQ;AAAA,EACV,GAAG,EAAE,CAAA;AACL,EAAA,SAAS,OAAA,GAAU;AACjB,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,MAAA,CAAO,IAAIA,mCAAiB,CAAA;AAAA,EAC9B;AACA,EAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAC3D,CAAC,CAAA;AAGH,SAAS,WAAA,CAAY,MAAc,GAAA,EAA0B;AAC3D,EAAA,OAAO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Ae,IAAIA,iCAAA,CAAgB,QAAW,KAAK,CAAA;AACpE,MAAA,MAAM,EAAE,MAAK,GAAI,MAAM,KAAK,MAAA,CAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AACvD,MAAA,IAAA,CAAK,aAAa,IAAI,CAAA;AACtB,MAAA,IAAI,IAAA,CAAK,WAAW,WAAA,EAAa;AAC/B,QAAA,OAAQ,IAAA,CAAK,eAAe,EAAC;AAAA,MAC/B;AACA,MAAA,IAAI,IAAA,CAAK,MAAA,KAAW,QAAA,IAAY,IAAA,CAAK,WAAW,WAAA,EAAa;AAC3D,QAAA,MAAM,IAAIG,gCAAA;AAAA,UACR,KAAK,aAAA,IAAiB,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA,CAAA;AAAA,UAC7C,KAAA;AAAA,UACA,IAAA,CAAK;AAAA,SACP;AAAA,MACF;AAMA,MAAA,IAAI,IAAA,CAAK,WAAW,gBAAA,EAAkB;AACpC,QAAA,MAAM,IAAIK,8BAAA,CAAa,CAAA,EAAG,KAAK,uBAAuB,KAAK,CAAA;AAAA,MAC7D;AACA,MAAA,IAAI,IAAA,CAAK,GAAA,EAAI,GAAI,QAAA,EAAU;AACzB,QAAA,MAAM,IAAIC,iCAAA,CAAgB,CAAA,EAAG,KAAK,CAAA,UAAA,CAAA,EAAc,OAAO,KAAK,CAAA;AAAA,MAC9D;AACA,MAAA,MAAM,KAAA,CAAM,MAAA,EAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,IACjC;AAAA,EACF;AACF","file":"chunk-QZHRXPN5.cjs","sourcesContent":["import type { GenerateScene3DParams, EditScene3DParams, RenderScene3DParams, Scene3DJobOutput, Pro3DRenderRunParams, Pro3DRenderJobOutput } from \"./scene3d-types.js\"\nimport type { ImageToImageParams, EditImageParams, SplitImageParams, SplitImageResult, GenerateMaskParams, GenerateMaskJobOutput, ImageJobStarted } from \"./nodes-image-params.js\"\nimport type { VideoToVideoParams, NodeQuote } from \"./nodes-video-params.js\"\nimport type { NodaroClientCore } from \"../core.js\"\nimport type { JobStatusResult, JobsResource } from \"./jobs.js\"\nimport { JobAbortedError, JobFailedError, JobHeldError, JobTimeoutError, NodaroError, NotFoundError } from \"../errors.js\"\nimport { NODE_RUN_ROUTES, NODE_TYPES_WITHOUT_RUN_ROUTE, nodeRunRoute } from \"@nodaro/shared/nodes\"\nimport {\n SOCIAL_POST_NODE_PLATFORM,\n type SocialPost,\n type SocialPlatform,\n type SocialSearchMode,\n type SocialSearchParams\n} from \"@nodaro/shared/social\"\nimport type { ConnectedReference, DescribedReference } from \"@nodaro/shared/types\"\nimport type { VideoCharacterReference } from \"@nodaro/shared/video\"\nimport type { ModelInputAdjustment } from \"@nodaro/shared/model-catalog\"\nimport type { VideoDepthProvider, VideoDepthModelSize, VideoDepthColormap, VideoDepthResolution } from \"@nodaro/shared/media\"\nimport type { DirectionFields, SubjectFields } from \"@nodaro/prompts/prompt-builder\"\n\nexport type NodeCategory =\n | \"input\"\n | \"parameter\"\n | \"ai-image\"\n | \"ai-video\"\n | \"ai-audio\"\n | \"ai-text\"\n | \"processing\"\n | \"composition\"\n | \"trigger\"\n | \"output\"\n | \"control\"\n | \"entity\"\n | \"utility\"\n\nexport type OutputType = \"text\" | \"image\" | \"video\" | \"audio\" | \"data\" | \"none\"\n\n/**\n * Field shape inside a node's `inputSchema.fields[]`. Mirrors\n * `backend/src/lib/node-registry.ts`.\n */\nexport interface NodeInputField {\n key: string\n type: string\n required?: boolean\n options?: string[]\n}\n\nexport interface NodeInputSchema {\n fields: NodeInputField[]\n}\n\n/**\n * A per-unit price on a node descriptor. A run of N units is charged\n * `ceil(N × creditsPerUnit)`, rounded up once — so `GET /v1/credits/model-cost`\n * for `identifier` (one unit, rounded up: the least a run pays) times N can come\n * to more. `<identifier>:<N>u` is the exact price of N units; for a whole run\n * use `POST /v1/credits/estimate-workflow`.\n */\nexport interface NodeCreditRate {\n /** The price id the rate is read from. */\n identifier: string\n /** What one unit is, as a token (`\"1000-frames\"`: one started block of 1,000 sampled frames). */\n unit: string\n /** The credits one unit adds to a run's total — exact, not rounded. */\n creditsPerUnit: number\n /** The fewest units a run is charged for. */\n minUnits: number\n /** `\"ceil-run-total\"`: the run's total is rounded up to a whole credit once, never per unit. */\n rounding: \"ceil-run-total\"\n /** The rule in words. */\n note: string\n}\n\n/**\n * Node descriptor returned by `GET /v1/nodes` and `GET /v1/nodes/:type`.\n * Mirrors `backend/src/lib/node-registry.ts#NodeDescriptor`.\n */\nexport interface NodeDescriptor {\n type: string\n label: string\n category: NodeCategory\n description: string\n outputType: OutputType\n /** The credits a run is charged, the figure on the node's Run button.\n * Number when fixed, string range like \"10-80\" when model-dependent.\n * Undefined when the node is free — or on editions\n * without a credit system (community/business omit the field entirely;\n * it is meaningful on Cloud only). */\n creditCost?: number | string\n /** `creditCost` is an ESTIMATE: a metered LLM node's typical call on its\n * default model, charged its actual usage after the run (shown `~N`).\n * Absent for a fixed price, and under the tier-pricing rollback. A metered\n * LLM node whose default model has no price yet lists `creditCost:\n * \"unpriced\"` (a run on it is refused `llm_model_unpriced`). */\n estimate?: true\n /** A node charged per unit of its own measure (its `creditCost` is a word\n * such as `\"per-1000-frames\"`): the charged price of one unit and how a run\n * rounds. Cloud only, like `creditCost`. */\n creditRate?: NodeCreditRate\n /** Input fields the node exposes for user override (subset of full config). */\n inputSchema?: NodeInputSchema\n /** For AI nodes: list of provider IDs supported. */\n providers?: string[]\n /** Capability flags such as \"supports-reference-image\" or \"supports-end-frame\". */\n capabilities?: string[]\n /** Hard duration ceiling in seconds (e.g. Generate Video Pro's env-configured cap). */\n maxDurationSec?: number\n /** Providers whose segment-duration menu is sparse (off-menu values snap to the nearest entry). */\n sparseProviders?: string[]\n /** Per-provider resolution tiers, e.g. `{ \"minimax-h3\": [\"2K\", \"768P\"] }`. */\n providerResolutions?: Record<string, string[]>\n /** Per-provider map of display resolution → the literal wire value the API expects. */\n providerResolutionWire?: Record<string, Record<string, string>>\n /** Generate Video Pro: the deployed engine accepts the `soundtrack` input (original-audio replay). */\n soundtrack?: boolean\n}\n\n/**\n * Result of a direct node execution. Most node types return `{ jobId }` and\n * are processed asynchronously by a worker — the caller polls\n * `client.jobs.get(jobId)` until status is `completed`/`failed`.\n *\n * Some node types (`meta-ads-scrape`, for one) answer synchronously and\n * return their full result body. The shape is route-specific; consumers\n * should branch on the presence of `jobId`.\n */\n/**\n * One parameter the server corrected because the chosen model does not accept\n * the value you sent (e.g. `gpt-image-2` has no 3:2 aspect ratio). The run\n * proceeds with the corrected value rather than failing — this is how you find\n * out what it actually used.\n *\n * Re-exports `@nodaro/shared`'s `ModelInputAdjustment` — the same shape the\n * server's `normalizeModelInput` / `resolveNormalizedImageGen` populate — under\n * the SDK's naming convention, rather than declaring a second copy of the\n * fields.\n */\nexport type RunNodeAdjustment = ModelInputAdjustment\n\n/**\n * WHO is in the shot, as picker-catalog option ids — the `subject` field of\n * `generate-image` (and `text-to-video`). The platform writes the wording from\n * the ids you send; you never write prompt text for the subject. It composes\n * with `prompt`: the subject clauses are folded in right after your prompt and\n * ahead of any `direction`.\n *\n * A flat map of field → id(s):\n * - **Keys** are the platform's own picker field names — every Person field\n * (`type`, `age`, `ethnicity`, `hairBase`, `lipState`, …), every Styling\n * field (`makeup`, `jewelry`, `outerwear`, …), and the prop keys `heldProp`,\n * `material` and `animal`. They and their ids come from the picker catalogs:\n * `pickerCatalogs.get(\"person\")` / `get(\"styling\")` list each dimension's\n * `field` with its `options[].id`; `get(\"held-prop\")`, `get(\"material\")` and\n * `get(\"animal\")` write their `options[].id` to the catalog's `valueField`.\n * - **Values** are one id or a list of ids. Ids past a dimension's own cap are\n * dropped, not rejected.\n * - **One number:** `customAge` (years, rounded and clamped to 0–120), read only\n * when `age` is `\"age-custom\"`. A number on any other key does nothing.\n * - **Bounds** (without `presetId`): at most 128 keys, 64 characters per key,\n * 8 ids per key and 100 characters per id — a map over any of them is a 400\n * `validation_error`. Unknown keys and unknown ids within them are skipped,\n * and the job's `input_data.subject` records the ids that were used.\n * - **With `presetId`** your `subject` replaces the preset's own and is folded\n * into the preset's prompt, as `direction` and `structured` are: an over-long\n * key, id or list is dropped rather than rejected, and `input_data` does not\n * record the subject.\n *\n * Same type as `@nodaro/prompts`' `SubjectFields`, under the SDK's name.\n */\nexport type Subject = SubjectFields\n\n/**\n * Something you asked for that the run did not send, with why — e.g.\n * `moodboard_images_not_sent`: some of a `moodboard:<id>` direction's images\n * did not fit the model's reference limit after your own references. The run\n * goes ahead; the same warnings are kept on the job's `input_data.warnings`.\n */\nexport interface RunNodeWarning {\n code: string\n message: string\n}\n\nexport type RunNodeResult =\n | { jobId: string; usageLogId?: string; adjustments?: RunNodeAdjustment[]; warnings?: RunNodeWarning[]; [k: string]: unknown }\n | Record<string, unknown>\n\n/**\n * Structured references — the editor's wired-reference shape — shared by\n * `generate-image` and `generate-video`. The route assembles them server-side\n * into per-ref `@image_N` directives and resolves `{image:N}` prompt tokens, so\n * a direct SDK run binds inline references exactly like the canvas. Pass the\n * same `ConnectedReference[]` the editor builds; the route dedupes + caps them\n * to the provider's image-reference limit.\n */\nexport interface StructuredReferenceParams {\n /** Wired references assembled server-side (deduped + capped per provider). */\n connectedReferences?: ConnectedReference[]\n /**\n * References you can NAME and DESCRIBE but have no media for — a cast role no\n * entity is bound to yet, a character that exists only in the script. They\n * carry no url, so nothing is attached and no `@image_N` seat is used: each\n * becomes a `<Name> — <description>.` line, and a name left in the prompt\n * prose reaches the model as a real, described subject. Up to 10.\n */\n describedReferences?: DescribedReference[]\n /** Reorder the assembled reference list by stable ref ids; renumbers `@image_N`. */\n referenceOrder?: string[]\n}\n\n/**\n * Captions for a node's video / audio rail references — INDEX-ALIGNED with\n * `referenceVideoUrls` / `referenceAudioUrls`, so `referenceVideoCaptions[0]`\n * describes `referenceVideoUrls[0]`. Each renders as `@video_N: <caption>.` /\n * `@audio_N: <caption>.` in the assembled prompt and is bounded by the number of\n * rail references that actually ship, so a caption can never bind a slot the\n * payload dropped. A blank entry is a hole in the alignment, not a line.\n */\nexport interface ReferenceCaptionParams {\n referenceVideoCaptions?: string[]\n referenceAudioCaptions?: string[]\n}\n\n/**\n * Typed request body for `nodes.run(\"text-to-speech\", …)` / `runAndWait`.\n * Common fields are typed; any other route field passes through.\n */\nexport interface TextToSpeechParams extends GenerationSessionParams {\n text: string\n /** A premade voice NAME (Rachel, George, …) or a library / custom voice id. */\n voice?: string\n voiceType?: \"premade\" | \"custom\" | \"library\"\n /** `elevenlabs-v4` (the default), `elevenlabs-v3`, `elevenlabs-v4-turbo`, `elevenlabs-turbo`, `elevenlabs-multilingual`. */\n provider?: string\n stability?: number\n similarityBoost?: number\n style?: number\n speed?: number\n languageCode?: string\n /**\n * Continuity across clips: the line spoken just BEFORE this one in the finished piece\n * (the previous clip's text). Context, not spoken — a model that stitches (v4, Turbo, Multilingual; not v3) carries the\n * intonation across the cut; others ignore it. Up to 1,000 characters (a 400 above, on a model that stitches).\n */\n previousText?: string\n /** The line spoken just AFTER this one. Same rule as `previousText`. */\n nextText?: string\n [k: string]: unknown\n}\n\n/**\n * Fields every job-creating request accepts beside its own params, on any\n * route: the platform stamps them on the job it creates. Typed on every\n * generation params type.\n */\nexport interface GenerationSessionParams {\n /** A session from `client.sessions.create()` — the job is born in it and\n * shows in its feed. Must be one of yours (404 otherwise). */\n sessionId?: string\n /** Your app's slug (`create-image`, …): stored on the job, and what\n * `jobs.list({ origin })` filters on. Lowercase letters, digits, dashes. */\n origin?: string\n}\n\n/**\n * Typed request body for `nodes.run(\"generate-image\", …)` / `runAndWait`.\n * Common fields are typed; any other route field passes through via the index\n * signature (the route Zod-validates the full body).\n *\n * `count` above 1 or `models` makes several jobs in one call: the answer is a\n * {@link GenerateImageBatchResult}, and {@link NodesResource.runBatchAndWait}\n * (not `runAndWait`) waits for it.\n */\nexport interface GenerateImageParams extends StructuredReferenceParams, GenerationSessionParams {\n prompt?: string\n /**\n * Apply a node preset (a factory id like `\"generate-image/cinematic-still\"`, from\n * `presets.listFactory(\"generate-image\")`, or one of yours) exactly as the editor does:\n * its prompt and pre/post text, placeholder defaults, style, negative prompt and\n * levers. Fields you pass override it; your `prompt` is wrapped in its pre/post text.\n */\n presetId?: string\n /** Values for the preset's placeholders that have no default, e.g. `{ BRAND: \"Acme\" }`.\n * Without them such a preset answers 400 `preset_variables_required`, naming them. */\n presetVariables?: Record<string, string>\n /** The prompt as your user typed it, when `prompt` is a version your app\n * expanded (filled-in fields, resolved references). Stored on the job as\n * `input_data.userPrompt` to show what the user wrote; never sent to the\n * model. Defaults to `prompt`. */\n userPrompt?: string\n /** Pre & post text wrapped around `prompt` (a preset's words), joined the\n * same way every AI prompt node joins them. */\n promptPrefix?: string\n promptSuffix?: string\n provider?: string\n /** How many images to make, 1–4 — each its own job, one image each, under\n * its own Idempotency-Key (`<key>:<i>`). With `models`, per model. */\n count?: number\n /** 2–4 distinct image model ids: the same request runs on each, instead of\n * `provider`. models × count is at most 8. With `presetId`, the preset is\n * applied once per model. */\n models?: string[]\n /** With `count`, image i gets `seed + i` — one seed would draw the same image every time. */\n seed?: number\n /** Flat reference image URLs — appended after `connectedReferences`. */\n referenceImageUrls?: string[]\n negativePrompt?: string\n /**\n * Cinematic direction as catalog IDS — the route renders the wording. Two\n * keys also take one of YOUR saved resources:\n * - `colorLook: \"palette:<id>\"` (`paletteDirectionId(id)`) — the palette's\n * colours, each by an everyday name and its hex, go into the prompt;\n * - `style: \"moodboard:<id>\"` (`moodboardDirectionId(id)`) — the moodboard's\n * description goes into the prompt and its images go to the model as style\n * references, after your own references and up to the model's reference\n * limit (the answer's `warnings` says when some did not fit). Its images\n * are references, so on models priced per reference the run costs what is\n * sent.\n * A malformed one answers 400; one that is not yours (or was deleted) 404\n * `direction_not_found`. The job keeps the id, so a re-run resolves it again.\n * Not combinable with `presetId` yet (400 `validation_error`).\n */\n direction?: DirectionFields\n /**\n * WHO is in the shot — person, styling and props as picker-catalog ids\n * ({@link Subject}). The platform writes the wording and folds it in after\n * `prompt`, ahead of `direction`. With `presetId`, it replaces the preset's own\n * and is folded into the preset's prompt (over-long values dropped, not 400).\n */\n subject?: Subject\n /**\n * The image to edit. Alone, the run is image-to-image on it (a text-to-image\n * model runs as its image-to-image sibling); with `maskUrl`, an inpaint.\n */\n baseImageUrl?: string\n /**\n * Inpaint mask — white = the area to change, black = keep (what\n * `generate-mask` writes). Needs a base: `baseImageUrl`, else the first\n * `referenceImageUrls` entry. Works on EVERY image model: the result's masked\n * area is composited back over the base, so everything outside the mask is\n * the base's own pixels. On the models whose `IMAGE_MASK_MODE` is `\"prompt\"`\n * (`@nodaro/shared`) the masked area's position is also described in the\n * prompt; the rest rely on the composite alone. (A model that takes the mask\n * itself is on `image-to-image` — `I2I_MASK_SUPPORT`.)\n */\n maskUrl?: string\n /** 0–1: how far the result may move from the base (taken by the models in `I2I_STRENGTH_SUPPORT`). */\n strength?: number\n /** 0–20: prompt adherence (taken by the models in `GUIDANCE_SCALE_SUPPORT`). */\n guidanceScale?: number\n [k: string]: unknown\n}\n\n/** One model's share of a generate-image batch. */\nexport interface GenerateImageBatchGroup {\n /** The model id as requested. */\n model: string\n jobIds: string[]\n /** Credits held for this model's images; absent where nothing is charged. */\n credits?: number\n /** Parameters corrected for this model, as on a single call. */\n adjustments?: RunNodeAdjustment[]\n /** Something asked for that was not sent on this model (e.g. a moodboard past its reference limit), as on a single call. */\n warnings?: RunNodeWarning[]\n}\n\n/**\n * What `nodes.run(\"generate-image\", …)` answers when `count` is above 1 or\n * `models` is set: every job, grouped by model. The whole batch was checked\n * against the balance and created, charged and queued together — or not at\n * all (`InsufficientCreditsError`'s `required` is then the batch's total).\n */\nexport interface GenerateImageBatchResult {\n /** The first job — so code reading the single-image answer keeps working. */\n jobId: string\n /** Every job: model by model, then image by image. */\n jobIds: string[]\n /** On every job of the batch as `input_data.batchId`; `jobs.list({ batchId })` lists them. */\n batchId: string\n groups: GenerateImageBatchGroup[]\n /** The groups' credits summed; absent where nothing is charged. */\n totalCredits?: number\n /** Every job already existed and this request charged nothing: a repeat of an earlier request with the same Idempotency-Key. */\n deduped?: true\n}\n\n/**\n * One job of a batch once {@link NodesResource.runBatchAndWait} stops waiting\n * for it: its output, or the typed error that ended the wait — a\n * `JobFailedError` (failed or cancelled), `JobHeldError` (held for review) or\n * `JobTimeoutError`. One job's error never discards the others' images.\n */\nexport type BatchJobOutcome =\n | { readonly jobId: string; readonly model: string; readonly status: \"completed\"; readonly output: NodeJobOutput }\n | { readonly jobId: string; readonly model: string; readonly status: \"error\"; readonly error: NodaroError }\n\n/** What {@link NodesResource.runBatchAndWait} resolves. */\nexport interface GenerateImageBatchOutput {\n /** The submit's answer: the ids, the groups, the credits. */\n readonly batch: GenerateImageBatchResult\n /** Every job, in `batch.jobIds` order. */\n readonly results: readonly BatchJobOutcome[]\n}\n\n/**\n * Typed request body for `nodes.run(\"generate-video\", …)` / `runAndWait`.\n * Common fields are typed; any other route field passes through.\n */\nexport interface GenerateVideoParams extends StructuredReferenceParams, ReferenceCaptionParams, GenerationSessionParams {\n prompt?: string\n provider?: string\n /** Start-frame image (image-to-video). */\n imageUrl?: string\n /** Closing frame, paired with `imageUrl` on models that support one. */\n endFrameUrl?: string\n referenceImageUrls?: string[]\n referenceVideoUrls?: string[]\n referenceAudioUrls?: string[]\n /**\n * Identity inputs that keep a real person's face — a portrait + description\n * per person, up to 3. Only models with a dedicated character channel take\n * them (Gemini Omni: `gemini-omni-video`, `gemini-omni-flash`); any other\n * model answers `400`. Distinct from `referenceImageUrls`, which a multimodal\n * model treats as loose context. Cannot be combined with a start frame\n * (`imageUrl`); each character uses 1 of the model's 7 input units (2 with a\n * `bodyImageUrl`). Adds no credit charge. Give a character a `voice` to pin one\n * voice persona (a Gemini preset + optional description / example line) across\n * clips — up to 3 distinct voices a request.\n */\n characterReferences?: VideoCharacterReference[]\n /** How a start/end frame is reshaped before the model sees it. Default\n * `\"resolution\"`: resize it to the pixel size that model actually renders,\n * which is what stops the provider reshaping it mid-clip. `\"ratio\"` corrects\n * only the aspect; `\"original\"` sends it untouched. */\n frameFit?: \"original\" | \"ratio\" | \"resolution\"\n /** Whether the frame travels as a real start frame or as a reference image\n * bound in the prompt as the opening frame. Default `\"auto\"`, which picks per\n * model. Ignored by models that take no reference images. */\n frameDelivery?: \"auto\" | \"frame\" | \"reference\"\n /** Seedance Draft (`seedance-2-5` only; ignored elsewhere): render a 480p\n * DRAFT — it costs the same as a 480p run and any `resolution` is replaced\n * by 480p. Finalize the take you like with `nodes.run(\"video-upscale\",\n * { provider: \"seedance-2-5-hd\", sourceJobId })`: the same take, frame for\n * frame, at 1080p. Drafts are kept about 7 days. */\n draft?: boolean\n [k: string]: unknown\n}\n\n/**\n * Typed request body for `nodes.run(\"text-to-video\", …)` / `runAndWait` — the\n * PROMPT-ONLY video lane (`POST /v1/text-to-video`).\n *\n * Which lane takes what: `text-to-video` renders from text (plus optional\n * references) and `prompt` is REQUIRED; frames belong to `generate-video`\n * alone, which is the image-to-video lane (`imageUrl` start frame, `endFrameUrl`\n * closing frame) and where a prompt is optional. A model with no text-to-video\n * mode answers this lane with a `400 image_required` naming itself.\n *\n * Common fields are typed; any other route field passes through.\n */\nexport interface TextToVideoParams extends StructuredReferenceParams, ReferenceCaptionParams, GenerationSessionParams {\n prompt: string\n provider?: string\n duration?: number\n /** Native audio toggle, on the models that render sound. */\n sound?: boolean\n negativePrompt?: string\n aspectRatio?: string\n resolution?: string\n seed?: number\n referenceImageUrls?: string[]\n referenceVideoUrls?: string[]\n referenceAudioUrls?: string[]\n /** Identity inputs that keep a real person's face — see {@link GenerateVideoParams.characterReferences}. */\n characterReferences?: VideoCharacterReference[]\n /** Cinematic direction as catalog IDS — the route renders the wording. */\n direction?: DirectionFields\n /** WHO is in the shot as picker-catalog ids ({@link Subject}), folded ahead of the direction clauses. */\n subject?: Subject\n /** Seedance Draft (`seedance-2-5` only; ignored elsewhere): render a 480p\n * DRAFT — it costs the same as a 480p run and any `resolution` is replaced\n * by 480p. Finalize the take you like with `nodes.run(\"video-upscale\",\n * { provider: \"seedance-2-5-hd\", sourceJobId })`: the same take, frame for\n * frame, at 1080p. Drafts are kept about 7 days. */\n draft?: boolean\n /** Absent / `true`: a copyright refusal is retried once with a reworded\n * prompt. `false` = a copyright refusal fails the job instead of retrying\n * once with a reworded prompt. */\n contentPolicyRewrite?: boolean\n [k: string]: unknown\n}\n\n/**\n * Typed request body for `nodes.run(\"video-upscale\", …)` / `runAndWait`.\n *\n * - `topaz` (default): upscale any `videoUrl` by `upscaleFactor`.\n * - `veo-1080p` / `veo-4k`: re-render a VEO generation by its `taskId`.\n * - `seedance-2-5-hd`: finalize a Seedance 2.5 DRAFT (a `draft: true` run) —\n * the same take re-rendered at 1080p at the draft's own length. Name the\n * draft by `sourceJobId` (its job id) or `taskId` (its providerTaskId). The\n * price comes from the draft (its length, and whether it used a reference\n * video), never from this body. A foreign, unfinished or non-draft source is\n * refused with a 4xx before anything is charged.\n *\n * Any other route field passes through.\n */\nexport interface VideoUpscaleParams extends GenerationSessionParams {\n provider?: \"topaz\" | \"veo-1080p\" | \"veo-4k\" | \"seedance-2-5-hd\"\n videoUrl?: string\n upscaleFactor?: \"1\" | \"2\" | \"4\"\n taskId?: string\n sourceJobId?: string\n [k: string]: unknown\n}\n\n/**\n * Typed request body for `nodes.run(\"assemble-narrated-video\", …)` / `runAndWait`.\n * Assembles blocks of video with audio narration into a single composed video.\n */\nexport interface AssembleNarratedVideoParams extends GenerationSessionParams {\n blocks: { videoUrl: string; audioUrl?: string }[]\n voiceVolume?: number\n clipAudioVolume?: number\n maxSlowdown?: number\n trimStartFrames?: number\n trimEndFrames?: number\n [k: string]: unknown\n}\n\n/**\n * Typed request body for `nodes.run(\"video-depth\", …)` / `runAndWait` — turns a\n * video into a depth video (`POST /v1/video-depth`, near is bright, far is\n * dark). The completed job writes `videoUrl` (MP4) and `thumbnailUrl`.\n *\n * Two providers: `video-depth-anything` (the default, temporally consistent)\n * honours every lever below; `depth-anything-frames` (Depth Anything per\n * frame) takes `modelSize` and `colormap` only, and renders only `grayscale` /\n * `inferno`. A lever the chosen provider does not take is dropped and a\n * colormap it cannot render becomes `grayscale` — coerced, never rejected (a\n * value outside the vocabularies below is still a `400 validation_error`).\n *\n * The clip is measured before any credits are reserved. Too long answers\n * `400 video_too_long` (`video-depth-anything`: more than 2,400 frames or\n * 300 s; `depth-anything-frames`: more than 80 s); a clip that cannot be read\n * answers `400 video_unreadable`; a provider the deployment has turned off\n * answers `403 model_not_available`.\n *\n * Common fields are typed; any other route field passes through.\n */\nexport interface VideoDepthParams extends GenerationSessionParams {\n /** The source video — a public http(s) URL. */\n videoUrl: string\n /** Default `video-depth-anything`. */\n provider?: VideoDepthProvider\n /** `small` / `base` / `large` (the default) — larger is more detailed and slower. */\n modelSize?: VideoDepthModelSize\n /** Default `grayscale`. `depth-anything-frames` renders only `grayscale` / `inferno`. */\n colormap?: VideoDepthColormap\n /** `video-depth-anything` only. Default `auto`. */\n resolution?: VideoDepthResolution\n /** `video-depth-anything` only: render the original and the depth next to each other. */\n sideBySide?: boolean\n [k: string]: unknown\n}\n\n/**\n * The `output_data` shape a finalized generation job writes. Every async\n * generation node persists one (or more) of these media URLs to\n * `jobs.output_data` on completion — `generate-image` → `imageUrl`,\n * `generate-video` / `combine-videos` / `merge-video-audio` / `video-upscale` /\n * `video-depth` → `videoUrl` (+ `thumbnailUrl`), `text-to-speech` / `generate-music` →\n * `audioUrl` (a `text-to-speech` run with `withTimestamps: true` on a model\n * that returns timings, and every `text-to-dialogue` run on one, also carries\n * `transcript`). Resolved by {@link NodesResource.runAndWait}. Extra fields may be\n * present, so the index signature is open.\n */\n/**\n * The completed `social-search` job's `output_data`: EVERY post the search\n * found, in the order it asked for (Social Search, Nodaro Cloud). Picking the\n * posts a workflow passes on is an editor step; a direct caller gets them all.\n */\nexport interface SocialSearchJobOutput extends NodeJobOutput {\n readonly json: readonly SocialPost[]\n readonly platform: SocialPlatform\n readonly mode: SocialSearchMode\n readonly query: string\n /** Non-fatal notes (\"only part of the results could be loaded\"). */\n readonly warnings?: readonly string[]\n}\n\nexport interface NodeJobOutput {\n /** `text-to-speech` / `generate-music` / audio nodes write here. For\n * `audio-separation` this is the primary stem (vocals). */\n readonly audioUrl?: string\n /** `audio-separation` (Demucs) per-stem URLs. `vocalUrl`/`instrumentalUrl`\n * in vocal/instrumental mode; the rest in full-stems mode. */\n readonly vocalUrl?: string\n readonly instrumentalUrl?: string\n readonly drumsUrl?: string\n readonly bassUrl?: string\n readonly otherUrl?: string\n readonly guitarUrl?: string\n readonly pianoUrl?: string\n /** `generate-video` / `combine-videos` / `merge-video-audio` / `video-upscale` / `video-depth` write here. */\n readonly videoUrl?: string\n /** `generate-image` / `edit-image` / `extract-frame` write here. */\n readonly imageUrl?: string\n /** Every image, when the job made more than one; `imageUrl` is the first. */\n readonly imageUrls?: readonly string[]\n /**\n * The output's pixel size. On an image job: the size of `imageUrl` as it is\n * stored — what you download, a free-tier watermark included — with EXIF\n * orientation applied, so the size a browser shows. Lay a grid tile out\n * before the image loads, or show and sort by size.\n *\n * Present on image jobs completed after this release (and on the jobs that\n * always recorded it: image overlay, video overlay, video mask, mask\n * composite). Absent when the size could not be read — never half a size.\n */\n readonly width?: number\n readonly height?: number\n /**\n * Beside `imageUrls`: each image with its pixel size, index-aligned\n * (`images[i]` is `imageUrls[i]`). Present on image jobs completed after\n * this release when at least one size was read; an entry whose size could\n * not be read has its `url` and no `width` / `height`.\n */\n readonly images?: readonly JobOutputImage[]\n /** Poster frame for video outputs. */\n readonly thumbnailUrl?: string\n readonly [k: string]: unknown\n}\n\n/** One image of a job that made several — see {@link NodeJobOutput.images}. */\nexport interface JobOutputImage {\n readonly url: string\n /** Pixel size as stored, EXIF orientation applied. Absent when it could not be read. */\n readonly width?: number\n readonly height?: number\n}\n\n/** Options for {@link NodesResource.runAndWait} and {@link NodesResource.runMany}. */\nexport interface RunAndWaitOptions {\n /**\n * Abort the run/poll loop. Aborting (or passing an already-aborted signal)\n * stops polling and rejects with {@link JobAbortedError}, whose `jobId`\n * names the job once it was submitted. Aborting stops the WAITING only: the\n * job keeps running and is charged, unless {@link cancelOnAbort} is set.\n */\n readonly signal?: AbortSignal\n /**\n * Also cancel the job when `signal` aborts after it was submitted\n * (`POST /v1/jobs/:id/cancel`, which refunds its credit hold — except a\n * metered LLM job whose call has started: it answers `inFlight: true`,\n * finishes, and is charged what it used). Best effort:\n * a failed cancel still rejects with the {@link JobAbortedError}. Default\n * `false` — aborting only stops waiting.\n */\n readonly cancelOnAbort?: boolean\n /** Called with each lean status the poll loop observes (running → terminal). */\n readonly onProgress?: (status: JobStatusResult) => void\n /** Poll interval in ms. Default 2000. */\n readonly pollMs?: number\n /** Wall-clock cap before giving up, in ms. Default ~15 min (900_000). */\n readonly maxMs?: number\n /**\n * `Idempotency-Key` for the submit half. Reuse the same value when retrying a\n * call that timed out, so the run is not started or charged twice. Omitted →\n * no key, which is the historical behaviour for every node that does not\n * require one.\n */\n readonly idempotencyKey?: string\n}\n\n/** Per-call transport controls for {@link NodesResource.run}. */\nexport interface RunNodeOptions {\n /** `Idempotency-Key` header. See {@link RunAndWaitOptions.idempotencyKey}. */\n readonly idempotencyKey?: string\n}\n\n/** One settled result from {@link NodesResource.runMany}. */\nexport interface RunManyResult {\n readonly jobId: string\n readonly output: NodeJobOutput\n}\n\n// Terminal statuses (poll loop stops on these) are handled explicitly in\n// `pollJob`: `completed` resolves output_data, `failed`/`cancelled` throw a\n// JobFailedError — matching studio's `completed | failed | cancelled` set.\nconst DEFAULT_POLL_MS = 2000\n/** Safety cap so a stuck job can't poll forever (~15 min at 2s). */\nconst DEFAULT_MAX_MS = 15 * 60 * 1000\n\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new JobAbortedError())\n return\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort)\n resolve()\n }, ms)\n function onAbort() {\n clearTimeout(timer)\n reject(new JobAbortedError())\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true })\n })\n\n/** The error for a node type that cannot be run on its own. */\nfunction notRunnable(type: string, why: string): NodaroError {\n return new NodaroError(`Node type \"${type}\" has no route of its own to run it directly: ${why}.`, \"node_not_runnable\", 0)\n}\n\n/** A 404 for the route itself (the server has no such path), not for a missing resource. */\nconst isRouteNotFound = (err: unknown): boolean => err instanceof NotFoundError && /^Route\\b.*\\bnot found\\b/i.test(err.message)\n\n/** Pull a `{ jobId }` off a run result, or throw a labelled JobFailedError. */\nfunction extractJobId(result: RunNodeResult, label: string): string {\n if (result && typeof result === \"object\" && \"jobId\" in result) {\n const jobId = (result as { jobId: unknown }).jobId\n if (typeof jobId === \"string\") return jobId\n }\n // No jobId means the node ran inline/synchronously (meta-ads-scrape, etc.) or\n // the route shape changed — runAndWait is for async jobs, so this is an error.\n throw new JobFailedError(`${label} did not return a jobId`, \"\")\n}\n\n/** Whether a generate-image request makes several jobs: `count` above 1, or `models`. */\nfunction isImageBatchRequest(type: string, params: Record<string, unknown>): boolean {\n if (type !== \"generate-image\") return false\n return (typeof params.count === \"number\" && params.count > 1) || Array.isArray(params.models)\n}\n\n/** The job ids of a batch answer (several jobs from one call), or null for a single job. */\nfunction batchJobIds(result: RunNodeResult): string[] | null {\n const ids = (result as { jobIds?: unknown } | null)?.jobIds\n return Array.isArray(ids) && ids.every((id) => typeof id === \"string\") ? (ids as string[]) : null\n}\n\n/** A wait-for-one-job method asked to wait for a batch. */\nfunction batchRefusal(detail: string): NodaroError {\n return new NodaroError(\n `${detail}: this waits for one job — use nodes.runBatchAndWait() for a batch (count above 1, or models).`,\n \"batch_requires_run_batch_and_wait\",\n 0,\n )\n}\n\n/** The batch answer of a generate-image call, checked, or null. */\nfunction batchResultOf(result: RunNodeResult): GenerateImageBatchResult | null {\n const r = result as Partial<GenerateImageBatchResult> | null\n if (!r || typeof r.batchId !== \"string\" || !batchJobIds(result) || !Array.isArray(r.groups)) return null\n return r as GenerateImageBatchResult\n}\n\nexport class NodesResource {\n /** Runs poll through `jobs`, so the client must carry that resource too. */\n constructor(private client: NodaroClientCore & { readonly jobs: JobsResource }) {}\n\n /** List all known node descriptors. Server caches publicly for 5 minutes. */\n list(): Promise<{ data: NodeDescriptor[] }> {\n return this.client.request(\"GET\", \"/v1/nodes\")\n }\n\n /** Get a single node descriptor by type slug (e.g. \"generate-image\"). */\n get(type: string): Promise<{ data: NodeDescriptor }> {\n return this.client.request(\"GET\", `/v1/nodes/${encodeURIComponent(type)}`)\n }\n\n /**\n * Run a single node directly without wrapping it in a workflow. Posts\n * `params` as the request body to the node's API route. Most use\n * `POST /v1/<type>`; the rest are listed in `NODE_RUN_ROUTES` (exported by\n * `@nodaro/shared`): scene authoring uses `/v1/3d-scene/generate|edit`,\n * `llm-chat` uses `/v1/llm-chat/generate`, the Suno nodes `/v1/suno/…`, the\n * social post nodes `/v1/social/publish` (a per-platform node fills in its\n * `platform` when you leave it out), and render-video with a planType uses\n * `/v1/render-video/plan`.\n *\n * A node type with no route of its own (`NODE_TYPES_WITHOUT_RUN_ROUTE`, e.g.\n * `modify-image`, which runs through `image-to-image`) rejects with a\n * {@link NodaroError} of code `node_not_runnable` naming what to run\n * instead, without calling the API. A type that runs only inside a workflow\n * (an input, trigger, utility or parameter node such as `upload-image`)\n * rejects the same way once the API answers that it has no such route; a\n * 404 about a missing resource stays a `NotFoundError`.\n *\n * This is the SDK equivalent of the MCP server's verb tools — and the\n * path the Nodaro CLI uses for `nodaro nodes run <type>`.\n *\n * Most node types are async: the response includes `{ jobId }` and the\n * actual generation runs on a worker. Poll `client.jobs.get(jobId)` until\n * completed. Synchronous node types (`meta-ads-scrape`, etc.) return their\n * full result without a `jobId` field.\n *\n * @param type Node type slug — must match an entry in the registry\n * returned by `list()` (e.g. \"generate-image\").\n * @param params Request body. Field names must match the node's\n * `inputSchema` (see `get(type).inputSchema`).\n */\n run(type: \"generate-3d-scene\", params: GenerateScene3DParams): Promise<RunNodeResult>\n run(type: \"edit-3d-scene\", params: EditScene3DParams): Promise<RunNodeResult>\n run(type: \"render-video\", params: RenderScene3DParams): Promise<RunNodeResult>\n run(type: \"pro-3d-render\", params: Pro3DRenderRunParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"generate-image\", params: GenerateImageParams & ({ count: 2 | 3 | 4 } | { models: string[] }), options?: RunNodeOptions): Promise<GenerateImageBatchResult>\n run(type: \"generate-image\", params?: GenerateImageParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"text-to-speech\", params: TextToSpeechParams): Promise<RunNodeResult>\n run(type: \"generate-video\", params?: GenerateVideoParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"text-to-video\", params: TextToVideoParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"video-to-video\", params: VideoToVideoParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"video-upscale\", params: VideoUpscaleParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"assemble-narrated-video\", params?: AssembleNarratedVideoParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"social-search\", params: SocialSearchParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"video-depth\", params: VideoDepthParams, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: \"image-to-image\", params: ImageToImageParams, options?: RunNodeOptions): Promise<ImageJobStarted>\n run(type: \"edit-image\", params: EditImageParams, options?: RunNodeOptions): Promise<ImageJobStarted>\n run(type: \"generate-mask\", params: GenerateMaskParams, options?: RunNodeOptions): Promise<ImageJobStarted>\n /** Synchronous and free: answers the tiles, no job. */\n run(type: \"split-image\", params: SplitImageParams, options?: RunNodeOptions): Promise<SplitImageResult>\n run(type: string, params?: Record<string, unknown>, options?: RunNodeOptions): Promise<RunNodeResult>\n run(type: string, params: Record<string, unknown> = {}, options: RunNodeOptions = {}): Promise<RunNodeResult | GenerateImageBatchResult> {\n // The route comes from the table the platform's workflow engine uses\n // too; only render-video's plan route depends on the body.\n const route = type === \"render-video\" && typeof params.planType === \"string\" ? \"/v1/render-video/plan\" : nodeRunRoute(type)\n if (!route) return Promise.reject(notRunnable(type, NODE_TYPES_WITHOUT_RUN_ROUTE[type]!))\n // A per-platform social node publishes through the shared route, which\n // needs the platform the node type stands for.\n const platform = SOCIAL_POST_NODE_PLATFORM[type]\n const body = platform && params.platform === undefined ? { ...params, platform } : params\n // Only a type on the `/v1/<type>` convention is relabelled: a listed\n // route that 404s means a platform that predates it, not a node that\n // cannot run.\n const conventional = !Object.prototype.hasOwnProperty.call(NODE_RUN_ROUTES, type)\n return this.client\n .request<RunNodeResult>(\"POST\", route, {\n body,\n // Transport-level retry safety, opt-in per call. The platform reads the\n // standard header, so a caller that reuses a key on a retry gets the\n // same run back instead of a second charge.\n ...(options.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n })\n .catch((err: unknown) => {\n if (conventional && isRouteNotFound(err)) throw notRunnable(type, \"it runs only inside a workflow (client.workflows.run)\")\n throw err\n })\n }\n\n /**\n * The price of a run before it starts (`POST /v1/quote`). Send exactly the\n * body you would send to {@link run}: the platform prices it with the same\n * code the run route reserves with — validation, measuring reference clips,\n * the price id and the credit amount — but starts nothing and charges\n * nothing.\n *\n * `reserve` is what the run will hold when it starts; `expected`, when\n * present, is what it should actually cost (a Seedance edit renders the\n * source clip's length). A run settles to what was generated, never above\n * `reserve`. Rejects with the same `400` the run would answer for an\n * invalid body. Typed for the video lanes; any other node type takes its\n * run body as-is.\n *\n * @param type Node type slug, as for {@link run}.\n * @param params The run body.\n */\n quote(type: \"text-to-video\", params: TextToVideoParams): Promise<NodeQuote>\n quote(type: \"generate-video\", params: GenerateVideoParams): Promise<NodeQuote>\n quote(type: \"video-to-video\", params: VideoToVideoParams): Promise<NodeQuote>\n /** A Seedance 2.5 draft's 1080p finalize (`seedance-2-5-hd`) is priced from\n * the draft itself, including the clips it was made with. */\n quote(type: \"video-upscale\", params: VideoUpscaleParams): Promise<NodeQuote>\n quote(type: string, params?: Record<string, unknown>): Promise<NodeQuote>\n async quote(type: string, params: Record<string, unknown> = {}): Promise<NodeQuote> {\n const res = await this.client.request<{ data: NodeQuote }>(\"POST\", \"/v1/quote\", { body: { type, params } })\n return res.data\n }\n\n /**\n * Run a single async node to completion: {@link run} it, extract the\n * `{ jobId }`, then client-poll `jobs.getStatus(jobId)` every `pollMs`\n * (default 2000) until a terminal status, up to `maxMs` (default ~15 min).\n *\n * Resolves the job's typed `output_data` ({@link NodeJobOutput}) on\n * `completed`. Throws (all typed, catchable by `instanceof`):\n * - {@link InsufficientCreditsError} / {@link StorageExceededError} etc. —\n * surfaced by the underlying {@link run} on 402/413/… before any poll.\n * - {@link JobFailedError} — terminal `failed`/`cancelled` (carries the\n * job's `error_message` + `jobId`).\n * - {@link JobTimeoutError} — `maxMs` deadline exceeded before terminal.\n * - {@link JobAbortedError} — `signal` fired (or was already aborted);\n * polling stops immediately.\n * - {@link JobHeldError} — the job entered `pending_review` on a deployment\n * that registers a job policy. Ends the poll on the FIRST held tick (that\n * status waits on a human, not on the job) and does NOT cancel it.\n * - {@link JobBlockedError} — a 422 from {@link run} before any poll: the\n * deployment's job policy refused the request outright.\n *\n * Polling is fully client-side (no server function blocks) — the same model\n * thin clients use, lifted out of their hand-rolled run→poll loops.\n *\n * @param type Node type slug (e.g. \"generate-video\"). See {@link run}.\n * @param params Request body — field names match the node's `inputSchema`.\n * @param opts `signal` / `onProgress` / `pollMs` / `maxMs`.\n */\n runAndWait(type: \"generate-3d-scene\", params: GenerateScene3DParams, options?: RunAndWaitOptions): Promise<Scene3DJobOutput>\n runAndWait(type: \"edit-3d-scene\", params: EditScene3DParams, options?: RunAndWaitOptions): Promise<Scene3DJobOutput>\n runAndWait(type: \"render-video\", params: RenderScene3DParams, options?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"pro-3d-render\", params: Pro3DRenderRunParams, options?: RunAndWaitOptions): Promise<Pro3DRenderJobOutput>\n runAndWait(type: \"generate-image\", params?: GenerateImageParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"text-to-speech\", params: TextToSpeechParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"generate-video\", params?: GenerateVideoParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"text-to-video\", params: TextToVideoParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"video-to-video\", params: VideoToVideoParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"video-upscale\", params: VideoUpscaleParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"assemble-narrated-video\", params?: AssembleNarratedVideoParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"social-search\", params: SocialSearchParams, opts?: RunAndWaitOptions): Promise<SocialSearchJobOutput>\n runAndWait(type: \"video-depth\", params: VideoDepthParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"image-to-image\", params: ImageToImageParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"edit-image\", params: EditImageParams, opts?: RunAndWaitOptions): Promise<NodeJobOutput>\n runAndWait(type: \"generate-mask\", params: GenerateMaskParams, opts?: RunAndWaitOptions): Promise<GenerateMaskJobOutput>\n runAndWait<T extends string>(type: T, params?: Record<string, unknown>, opts?: RunAndWaitOptions): Promise<T extends \"pro-3d-render\" ? Pro3DRenderJobOutput : T extends \"generate-3d-scene\" | \"edit-3d-scene\" ? Scene3DJobOutput : T extends \"generate-mask\" ? GenerateMaskJobOutput : NodeJobOutput>\n async runAndWait(\n type: string,\n params: Record<string, unknown> = {},\n opts: RunAndWaitOptions = {},\n ): Promise<NodeJobOutput> {\n if (opts.signal?.aborted) throw new JobAbortedError()\n // A batch would be waited on as its first job alone — refused before\n // anything is submitted or charged.\n if (isImageBatchRequest(type, params)) throw batchRefusal(`${type} with count above 1 or models makes several jobs`)\n const result = await this.run(type, params, { idempotencyKey: opts.idempotencyKey })\n const ids = batchJobIds(result)\n if (ids && ids.length > 1) throw batchRefusal(`${type} started ${ids.length} jobs (${ids.join(\", \")}), which keep running`)\n const jobId = extractJobId(result, type)\n return this.pollJob(jobId, type, opts)\n }\n\n /**\n * Run a generate-image BATCH — `count` above 1 and/or `models` — to the end:\n * submit it once ({@link run}, with your `idempotencyKey` if any), then wait\n * for every job at once, each the way {@link runAndWait} waits.\n *\n * Resolves `{ batch, results }`: the submit's answer\n * ({@link GenerateImageBatchResult} — ids, groups by model, credits) and one\n * {@link BatchJobOutcome} per job, in `batch.jobIds` order — its output, or the\n * typed error that ended the wait for it. One image failing never discards the\n * others. Rejects only before any job exists (the submit's own errors, e.g.\n * `InsufficientCreditsError` with the batch total as `required`), and on\n * `signal` ({@link JobAbortedError}; `cancelOnAbort` cancels every job).\n *\n * A request for one image is refused before anything is sent (code\n * `not_a_batch`) — wait for it with {@link runAndWait}.\n */\n async runBatchAndWait(\n type: \"generate-image\",\n params: GenerateImageParams,\n opts: RunAndWaitOptions = {},\n ): Promise<GenerateImageBatchOutput> {\n if (opts.signal?.aborted) throw new JobAbortedError()\n if (!isImageBatchRequest(type, params)) {\n throw new NodaroError(\n \"runBatchAndWait waits for a batch — count above 1, or models; wait for one image with nodes.runAndWait().\",\n \"not_a_batch\",\n 0,\n )\n }\n const result = await this.run(type, params, { idempotencyKey: opts.idempotencyKey })\n const batch = batchResultOf(result)\n if (!batch) throw new JobFailedError(`${type} did not answer with a batch`, \"\")\n const modelOf = new Map(batch.groups.flatMap((group) => group.jobIds.map((id) => [id, group.model] as const)))\n const results = await Promise.all(\n batch.jobIds.map(async (jobId): Promise<BatchJobOutcome> => {\n const model = modelOf.get(jobId) ?? \"\"\n try {\n return { jobId, model, status: \"completed\", output: await this.pollJob(jobId, type, opts) }\n } catch (err) {\n if (err instanceof JobAbortedError || !(err instanceof NodaroError)) throw err\n return { jobId, model, status: \"error\", error: err }\n }\n }),\n )\n return { batch, results }\n }\n\n /**\n * Fan out N async runs of the same node `type` to completion concurrently —\n * the candidate-grid path (generate N stills/clips in parallel). Each runs\n * via {@link runAndWait}; resolves once ALL settle, to an array of\n * `{ jobId, output }` in input order. Rejects (and the rejection wins) if any\n * single run rejects — same typed errors as {@link runAndWait}, including\n * {@link JobHeldError} when one candidate is held for review while the\n * others complete. A shared `signal` aborts the whole batch.\n *\n * @param type Node type slug, applied to every entry.\n * @param paramsList One request body per candidate.\n * @param opts Shared `signal` / `cancelOnAbort` / `onProgress` / `pollMs` / `maxMs`.\n */\n async runMany(\n type: string,\n paramsList: Record<string, unknown>[],\n opts: RunAndWaitOptions = {},\n ): Promise<RunManyResult[]> {\n if (opts.signal?.aborted) throw new JobAbortedError()\n // Each entry is waited on as one job: a batch entry is refused up front.\n if (paramsList.some((params) => isImageBatchRequest(type, params))) {\n throw batchRefusal(`a ${type} entry with count above 1 or models makes several jobs`)\n }\n return Promise.all(\n paramsList.map(async (params) => {\n if (opts.signal?.aborted) throw new JobAbortedError()\n const result = await this.run(type, params)\n const jobId = extractJobId(result, type)\n const output = await this.pollJob(jobId, type, opts)\n return { jobId, output }\n }),\n )\n }\n\n /** {@link pollUntilSettled}, plus what an abort does to the job: it keeps\n * running unless `cancelOnAbort` asks to cancel it too, and the rejection\n * always names it (an abort landing mid-sleep carries no id of its own). */\n private async pollJob(\n jobId: string,\n label: string,\n opts: RunAndWaitOptions,\n ): Promise<NodeJobOutput> {\n try {\n return await this.pollUntilSettled(jobId, label, opts)\n } catch (err) {\n if (!(err instanceof JobAbortedError)) throw err\n if (opts.cancelOnAbort) await this.client.jobs.cancel(jobId).catch(() => undefined)\n throw err.jobId ? err : new JobAbortedError(err.message, jobId)\n }\n }\n\n /** Poll an already-kicked job id until it stops moving; resolve output_data\n * or throw. Two non-terminal statuses end the loop: an abort, and\n * `pending_review` (a job policy held the output for a human — see\n * {@link JobHeldError}). */\n private async pollUntilSettled(\n jobId: string,\n label: string,\n opts: RunAndWaitOptions,\n ): Promise<NodeJobOutput> {\n const pollMs = opts.pollMs ?? DEFAULT_POLL_MS\n const maxMs = opts.maxMs ?? DEFAULT_MAX_MS\n const deadline = Date.now() + maxMs\n for (;;) {\n if (opts.signal?.aborted) throw new JobAbortedError(undefined, jobId)\n const { data } = await this.client.jobs.getStatus(jobId)\n opts.onProgress?.(data)\n if (data.status === \"completed\") {\n return (data.output_data ?? {}) as NodeJobOutput\n }\n if (data.status === \"failed\" || data.status === \"cancelled\") {\n throw new JobFailedError(\n data.error_message ?? `${label} ${data.status}`,\n jobId,\n data.status,\n )\n }\n // `pending_review` is in-flight but PARKED ON A HUMAN — it does not\n // progress on its own, so continuing the loop would burn `maxMs` (15 min\n // by default) and then report a `JobTimeoutError` that misdescribes what\n // happened. End here instead, without cancelling: the output exists, the\n // reservation stays reserved, and a reviewer resolves it.\n if (data.status === \"pending_review\") {\n throw new JobHeldError(`${label} is awaiting review`, jobId)\n }\n if (Date.now() > deadline) {\n throw new JobTimeoutError(`${label} timed out`, jobId, maxMs)\n }\n await sleep(pollMs, opts.signal)\n }\n }\n}\n"]}
|
|
@@ -18,5 +18,5 @@ var PromptHelperResource = class {
|
|
|
18
18
|
};
|
|
19
19
|
|
|
20
20
|
exports.PromptHelperResource = PromptHelperResource;
|
|
21
|
-
//# sourceMappingURL=chunk-
|
|
22
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
//# sourceMappingURL=chunk-TCLNSVYA.cjs.map
|
|
22
|
+
//# sourceMappingURL=chunk-TCLNSVYA.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/prompt-helper.ts"],"names":[],"mappings":";;;AAuEO,IAAM,uBAAN,MAA2B;AAAA,EAChC,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA,EAEpB,QAAQ,KAAA,EAA6C;AACnD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,0BAAA,EAA4B,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,GAAG,KAAA,IAAS,CAAA;AAAA,EAC1G;AAAA,EAEA,SAAS,KAAA,EAA6C;AACpD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,0BAAA,EAA4B,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,UAAA,EAAY,GAAG,KAAA,IAAS,CAAA;AAAA,EAC3G;AAAA,EAEA,QAAQ,KAAA,EAA4C;AAClD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,0BAAA,EAA4B,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,GAAG,KAAA,IAAS,CAAA;AAAA,EAC1G;AACF","file":"chunk-TCLNSVYA.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { WizardQuestion, WizardSelection, RecommendedModel, WizardNodeContext } from \"@nodaro/prompts/doctrine\"\nexport type { WizardQuestion, WizardOption, WizardSelection, RecommendedModel, WizardNodeContext } from \"@nodaro/prompts/doctrine\"\n\n// Re-export the canonical wizard types (SSOT in @nodaro/shared).\n\ninterface CommonInput {\n nodeType: string\n provider?: string\n style?: string\n aspectRatio?: string\n duration?: number\n llmModel?: string\n /** Reasoning effort level (model-dependent). */\n reasoningEffort?: string\n /**\n * Gemini and Claude models. Runs the request on the provider's own API so\n * `temperature`, `maxTokens` and the full reasoning range actually take\n * effect — on the default lane those levers are not reliably honoured.\n * The call is charged its actual usage at the vendor's direct rate (the price key ends `:direct`), so\n * it usually costs more than the default lane; where the server prices LLM calls by tier instead, it\n * bills one credit rung up (a premium model moves to premium-direct). A model without a direct lane returns\n * `400 advanced_mode_unsupported`.\n */\n advancedMode?: boolean\n /** Sampling temperature. Only honoured when `advancedMode` is true. */\n temperature?: number\n /** Output token cap. Only honoured when `advancedMode` is true. */\n maxTokens?: number\n nodeContext?: WizardNodeContext\n userPreference?: string\n /** Associates this call with a workflow execution. Read server-side before Zod. */\n workflowId?: string\n}\n\nexport interface AnalyzeInput extends CommonInput {\n /** The user's rough idea. Omit to build questions from scratch. */\n prompt?: string\n}\nexport interface AnalyzeResult {\n jobId: string\n questions: WizardQuestion[]\n}\n\nexport interface GenerateInput extends CommonInput {\n /** The chosen answers from analyze. */\n selections: WizardSelection[]\n /** The user's original rough idea, woven into the generated prompt. */\n originalPrompt?: string\n}\n\nexport interface EnhanceInput extends CommonInput {\n /** The rough idea to improve one-shot. Omit to build from scratch. */\n prompt?: string\n}\n\nexport interface PromptResult {\n jobId: string\n prompt: string\n recommendedModel?: RecommendedModel\n}\n\n/**\n * AI Prompt Wizard — help write/improve prompts for generation nodes.\n *\n * - `analyze` -> guided questions, `generate` -> prompt from selections (the\n * 2-step human flow), or `enhance` -> one-shot \"improve this prompt\".\n *\n * All three delegate to `POST /v1/prompt-helper/wizard`. Throws `NodaroError`\n * on 4xx/5xx (e.g. `validation_error`, `malformed_response`).\n */\nexport class PromptHelperResource {\n constructor(private client: NodaroClientCore) {}\n\n analyze(input: AnalyzeInput): Promise<AnalyzeResult> {\n return this.client.request(\"POST\", \"/v1/prompt-helper/wizard\", { body: { action: \"analyze\", ...input } })\n }\n\n generate(input: GenerateInput): Promise<PromptResult> {\n return this.client.request(\"POST\", \"/v1/prompt-helper/wizard\", { body: { action: \"generate\", ...input } })\n }\n\n enhance(input: EnhanceInput): Promise<PromptResult> {\n return this.client.request(\"POST\", \"/v1/prompt-helper/wizard\", { body: { action: \"enhance\", ...input } })\n }\n}\n"]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/resources/cast-swap.ts
|
|
4
|
+
var CastSwapResource = class {
|
|
5
|
+
constructor(client) {
|
|
6
|
+
this.client = client;
|
|
7
|
+
}
|
|
8
|
+
client;
|
|
9
|
+
/**
|
|
10
|
+
* Start a Cast Swap run (`POST /v1/cast-swap`, 202 `{ jobId }`). Returns the
|
|
11
|
+
* job to follow. With `options.idempotencyKey` (sent as the
|
|
12
|
+
* `Idempotency-Key` header; 8–200 characters, else 400) a repeat with the
|
|
13
|
+
* same key within about 10 s answers 200 `{ jobId, deduped: true }`, a later
|
|
14
|
+
* one 202 with the first run's `jobId`; nothing new starts.
|
|
15
|
+
*/
|
|
16
|
+
run(params, options) {
|
|
17
|
+
return this.client.request("POST", "/v1/cast-swap", {
|
|
18
|
+
body: params,
|
|
19
|
+
...options?.idempotencyKey ? { headers: { "Idempotency-Key": options.idempotencyKey } } : {}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** Quote a run before starting it (`POST /v1/cast-swap/estimate`); spends nothing. */
|
|
23
|
+
estimate(params) {
|
|
24
|
+
return this.client.request("POST", "/v1/cast-swap/estimate", { body: params });
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Quote finishing a draft at Full Quality (`POST
|
|
28
|
+
* /v1/cast-swap/:jobId/full-quality/estimate`); spends nothing. `jobId` is a
|
|
29
|
+
* finished DRAFT run (a Cast Swap or trend run made as a draft). The quote
|
|
30
|
+
* does not look for a Full Quality already running: when one is,
|
|
31
|
+
* {@link fullQuality} answers it (`existing: true`) and charges nothing.
|
|
32
|
+
* Refusals: {@link CastSwapFullQualityRefusalCode}.
|
|
33
|
+
*/
|
|
34
|
+
fullQualityEstimate(jobId) {
|
|
35
|
+
return this.client.request("POST", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality/estimate`, { body: {} });
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Finish a draft at Full Quality (`POST /v1/cast-swap/:jobId/full-quality`):
|
|
39
|
+
* the same take re-rendered at 1080p, with the clip's audio, as a new job
|
|
40
|
+
* linked to the draft. SPENDS CREDITS: quote it first with
|
|
41
|
+
* {@link fullQualityEstimate}. Answers 202 `{ jobId }`, or 200
|
|
42
|
+
* `{ jobId, existing: true }` when this draft's Full Quality is already
|
|
43
|
+
* running or done (one per draft; a failed one may be asked again). Follow
|
|
44
|
+
* the job with `client.jobs.get(jobId)`. No `Idempotency-Key` is taken: the
|
|
45
|
+
* server keys the job by the draft. The new job keeps the draft's origin.
|
|
46
|
+
* Refusals: {@link CastSwapFullQualityRefusalCode}.
|
|
47
|
+
*/
|
|
48
|
+
fullQuality(jobId, params = {}) {
|
|
49
|
+
const body = params.sessionId !== void 0 ? { sessionId: params.sessionId } : {};
|
|
50
|
+
return this.client.request("POST", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality`, { body });
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
exports.CastSwapResource = CastSwapResource;
|
|
55
|
+
//# sourceMappingURL=chunk-U2B7YQ2N.cjs.map
|
|
56
|
+
//# sourceMappingURL=chunk-U2B7YQ2N.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/cast-swap.ts"],"names":[],"mappings":";;;AA4WO,IAAM,mBAAN,MAAuB;AAAA,EAC5B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASpB,GAAA,CAAI,QAAwB,OAAA,EAA6E;AACvG,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,eAAA,EAAiB;AAAA,MAClD,IAAA,EAAM,MAAA;AAAA,MACN,GAAI,OAAA,EAAS,cAAA,GAAiB,EAAE,OAAA,EAAS,EAAE,iBAAA,EAAmB,OAAA,CAAQ,cAAA,EAAe,EAAE,GAAI;AAAC,KAC7F,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,SAAS,MAAA,EAAmD;AAC1D,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,0BAA0B,EAAE,IAAA,EAAM,QAAQ,CAAA;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,oBAAoB,KAAA,EAAqD;AACvE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,CAAA,cAAA,EAAiB,kBAAA,CAAmB,KAAK,CAAC,CAAA,sBAAA,CAAA,EAA0B,EAAE,IAAA,EAAM,IAAI,CAAA;AAAA,EACrH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,WAAA,CAAY,KAAA,EAAe,MAAA,GAAoC,EAAC,EAAuC;AACrG,IAAA,MAAM,IAAA,GAAO,OAAO,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,GAAI,EAAC;AACjF,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,CAAA,cAAA,EAAiB,kBAAA,CAAmB,KAAK,CAAC,CAAA,aAAA,CAAA,EAAiB,EAAE,IAAA,EAAM,CAAA;AAAA,EACxG;AACF","file":"chunk-U2B7YQ2N.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Cast Swap — replace the people, pets, products and/or the location in a\n * short video with your own references, keeping its motion, framing, timing\n * and sound (the clip's audio is kept, and the result is the clip's length).\n *\n * Before the video, each person, pet and product role's photos are turned\n * into one clean reference picture by an image model. This costs extra\n * credits (`breakdown.references` in the estimate), charged when it runs, even\n * if the video then fails; it adds about a minute, falls back to your own\n * photos if it fails, and is turned off with `prepareReferences: false`.\n * Locations are not prepared.\n *\n * Cloud edition only: `/v1/cast-swap` is served by the cloud plugin and 404s\n * on self-hosted installs. `run()` answers 202 with a job id; follow it with\n * `client.jobs.get(jobId)` / `client.jobs.getStatus(jobId)` like any other job.\n *\n * Repeats: pass `{ idempotencyKey }` to `run()` and it is sent as the\n * `Idempotency-Key` header. A repeat with the same key within the credit\n * guard's dedup window (about 10 s) answers 200 `{ jobId, deduped: true }` with\n * an `X-Dedup-Hit` header; a later one answers 202 with the first run's\n * `jobId`. Nothing new is started or charged.\n *\n * Refusals (thrown as a `NodaroError` subclass; body `{ error: { code, message } }`), before\n * anything is charged: 400 `validation_error` (the body: no role with images,\n * no reference and no `prePrompt` or `postPrompt`, more roles of a kind\n * than allowed, more than 30 images in all, `draft: true` above 480p, a\n * `prePrompt` or `postPrompt` over 4,000 characters, a `faceMasking` setting\n * out of range), `raw_reference_token` (also in a reference's `line`),\n * `invalid_role_mention` (also any `{role:N}` in a reference's `line`),\n * `unsafe_url`, `video_unreadable`, `clip_out_of_range` (4–30 s),\n * `preview_out_of_range`, `no_roles_in_preview` (a preview with every role\n * `inPreview: false`, always refused even with a prompt, or with no role kept\n * in it that has images and no `prePrompt` or `postPrompt`), `prompt_too_long`\n * (the prompt would build too long: a `{role:N}` reads as the role's name when\n * it sends no images); 401; 402 `insufficient_credits` (`run()` only); 404\n * (a `sessionId` you may not use, `run()` only); 422 `job_blocked` (`run()`\n * only); 503 `host_too_old` (both); 503 `estimate_unavailable` (`estimate()`\n * only).\n */\n\n/** Whether a swapped subject takes this trait from the references (`\"new\"`) or keeps the video's (`\"original\"`). */\nexport type CastSwapTraitSource = \"new\" | \"original\"\n\n/**\n * Preview-only settings, on every role kind; a full run (`preview` not `true`)\n * ignores both.\n */\nexport interface CastSwapRolePreviewSettings {\n /** The name used instead of `name` in a preview. Same rules as `name` (1–200 characters). */\n previewName?: string\n /**\n * `false` leaves this role out of the preview: its reference images are not\n * sent, not prepared and not charged, and a `{role:N}` naming it reads as its\n * `previewName`, else its `name`. Default `true`. A preview with every role\n * left out (always refused, even with a prompt), or with no role kept in it\n * that has images and no pre / post prompt, answers 400 `no_roles_in_preview`.\n */\n inPreview?: boolean\n}\n\n/** A person in the video to recast. */\nexport interface CastSwapPersonRole extends CastSwapRolePreviewSettings {\n kind: \"person\"\n /** How the person is told apart in the video, e.g. `\"the woman that attacks\"`. */\n name: string\n /** 0–3 images of ONE person. Empty or `null` keeps the original person. */\n images: string[] | null\n /** Body from the references or the video. Default `\"new\"`. */\n body?: CastSwapTraitSource\n /** Outfit from the references or the video. Default `\"new\"`. */\n outfit?: CastSwapTraitSource\n /** Hairstyle and haircut from the references or the video. Default `\"new\"`. */\n hair?: CastSwapTraitSource\n}\n\n/** The place the video happens in. */\nexport interface CastSwapLocationRole extends CastSwapRolePreviewSettings {\n kind: \"location\"\n /** How the place is named. Default `\"the setting\"`. */\n name?: string\n /** 0–3 images of ONE place. Empty or `null` keeps the original place. */\n images: string[] | null\n}\n\n/** An animal in the video to recast. */\nexport interface CastSwapPetRole extends CastSwapRolePreviewSettings {\n kind: \"pet\"\n /** How the animal is told apart in the video, e.g. `\"the dog\"`. */\n name: string\n /** 0–3 images of ONE animal. Empty or `null` keeps the original animal. */\n images: string[] | null\n /** Body (shape, size and build) from the references or the video. Default `\"new\"`. */\n body?: CastSwapTraitSource\n /** Coat (fur, colors and markings) from the references or the video. Default `\"new\"`. */\n coat?: CastSwapTraitSource\n}\n\n/** An object in the video to recast. */\nexport interface CastSwapProductRole extends CastSwapRolePreviewSettings {\n kind: \"product\"\n /** How the object is told apart in the video, e.g. `\"the can\"`. */\n name: string\n /** 0–3 images of ONE product. Empty or `null` keeps the original object. */\n images: string[] | null\n /** Shape and proportions from the references or the video. Default `\"new\"`. */\n shape?: CastSwapTraitSource\n /** Finish (colors, materials, label and markings) from the references or the video. Default `\"new\"`. */\n finish?: CastSwapTraitSource\n}\n\nexport type CastSwapRole = CastSwapPersonRole | CastSwapLocationRole | CastSwapPetRole | CastSwapProductRole\n\n/**\n * A fixed reference: 1–3 images of ONE thing that no role replaces, and the\n * line that says what it is (`\"the glass she drinks from\"`). Sent as given,\n * never prepared; its images count toward the 30.\n */\nexport interface CastSwapReference {\n /** 1–3 http(s) image URLs of one thing. */\n images: string[]\n /**\n * What it is, 1–500 characters. `{image}` in the line stands for this\n * reference's first image (`\"Use {image} for the sky\"`); a line without it\n * gets it appended. A `{role:N}` or a raw `{image:` / `{video:` / `{audio:`\n * token answers 400.\n */\n line: string\n}\n\n/**\n * Margins of the frame, each 0–49 % (default 0): a face whose centre lies in a\n * margin is not masked, so only faces inside the inner rectangle are.\n */\nexport interface CastSwapFaceMaskingZone {\n /** % of the frame's width from the left edge. Default 0. */\n leftPct?: number\n /** % of the frame's width from the right edge. Default 0. */\n rightPct?: number\n /** % of the frame's height from the top edge. Default 0. */\n topPct?: number\n /** % of the frame's height from the bottom edge. Default 0. */\n bottomPct?: number\n}\n\n/**\n * Face masking: the faces in the source clip are covered before the video\n * model sees it, keeping their movement and lip timing while the rest of the\n * clip is sent as it is.\n *\n * - `\"off\"` (the same as leaving `faceMasking` out): the clip is sent as it is.\n * - `\"always\"`: the faces are masked before the first attempt. Its credits are\n * in the quote (`breakdown.masking`, counted in `totalCredits`).\n * - `\"auto\"`: the run starts unmasked; only if the video model refuses the\n * source clip is it retried once with the faces masked. Any other failure is\n * not retried. The extra credits, charged only when that retry runs, are the\n * estimate's `maskingCredits` (not in `totalCredits`).\n *\n * A completed job's output carries `faceMasking: { applied, reason }`:\n * `applied` is whether the video was made from the masked clip, and `reason`\n * is `\"always\"` (masked before the first attempt), `\"input_refused\"` (`auto`\n * retried after the source clip was refused), `\"no_faces\"` (no face was left\n * to mask after the filters: an `always` run continues unmasked; an `auto`\n * run fails with the original refusal instead) or `\"off\"`.\n */\nexport interface CastSwapFaceMasking {\n mode: \"off\" | \"always\" | \"auto\"\n /** What covers a masked face: `\"blur\"` (default) or `\"depth\"` (a depth-color view of it). */\n fill?: \"blur\" | \"depth\"\n /** Mask only faces at least this % of the frame's height, 0–100. Default 15. */\n minFaceHeightPct?: number\n /**\n * Mask only faces at most this % of the frame's height, 0–100. Default 0 (no\n * limit). When above 0 it must be at least `minFaceHeightPct` (else 400).\n */\n maxFaceHeightPct?: number\n /** Leave out faces near the edges of the frame. Default: no margins. */\n zone?: CastSwapFaceMaskingZone\n /** The blur's strength, 0.1–5 % of the frame's width (`fill: \"blur\"`). Default 2. */\n blurStrengthPct?: number\n /** How sure the face finder must be, 0.05–0.95: lower finds more faces. Default 0.5. */\n threshold?: number\n}\n\n/** The body of `POST /v1/cast-swap` and `POST /v1/cast-swap/estimate`. */\nexport interface CastSwapParams {\n /** The source clip, 4–30 seconds. */\n videoUrl: string\n /**\n * Who and what to swap: at most 6 person roles, 1 location role, 3 pet roles\n * and 3 product roles, with at most 30 images in all. A role with no images\n * is skipped (that subject or place stays as in the video). At least one role\n * with images, or a `prePrompt` or `postPrompt`, is required.\n */\n roles: CastSwapRole[]\n /**\n * Fixed references (at most 5): things the video should show that no role\n * replaces, each with the line that names it. Their images count toward the\n * 30. A reference alone is enough for a run (no role needs images).\n */\n references?: CastSwapReference[]\n /**\n * Your own words placed at the start of the prompt, before the role\n * instructions; at most 4,000 characters. Mention a role as `{role:N}`, as in\n * `postPrompt`; the same 400 refusals apply (an N outside 1..`roles.length`,\n * a raw `{image:` / `{video:` / `{audio:` token).\n */\n prePrompt?: string\n /**\n * Extra instructions in your own words, at most 4,000 characters. Mention a\n * role as `{role:N}`, where N is its 1-based position in `roles`\n * (`{role:1}` is `roles[0]`; empty roles count).\n *\n * The route answers 400, before charging, for an N outside 1..`roles.length`,\n * for a raw `{image:` / `{video:` / `{audio:` token in the pre or post prompt\n * or a role's `name`, for a clip outside 4–30 s, and for a preview past the clip's\n * end (`previewStart + 4` > its length).\n */\n postPrompt?: string\n /** `true` runs on 4 seconds of the clip, starting at `previewStart`: a cheap check of the roles and choices. */\n preview?: boolean\n /** Where the preview starts, in seconds. Default 0. */\n previewStart?: number\n /** The output resolution. Default `\"480p\"`. */\n resolution?: \"480p\" | \"720p\" | \"1080p\"\n /**\n * Render as a draft. Defaults to `true` at 480p and `false` above it; `true`\n * with `\"720p\"` or `\"1080p\"` answers 400 (draft is 480p only).\n */\n draft?: boolean\n /**\n * Turn each person, pet and product role's photos into one clean reference\n * picture before the video (extra credits, shown in `breakdown.references`;\n * about a minute longer; falls back to your own photos if it fails).\n * Default `true`.\n */\n prepareReferences?: boolean\n /** Mask the faces in the source clip (see {@link CastSwapFaceMasking}). Default: off. */\n faceMasking?: CastSwapFaceMasking\n /**\n * `\"draft\"` means 480p draft.\n * @deprecated use `resolution` + `draft`.\n */\n quality?: \"draft\"\n /** A generation session to file the result in. */\n sessionId?: string\n /** The client app that sent the run (stored on the job as `input_data.origin`). */\n origin?: string\n}\n\n/** What a run would cost, in credits. */\nexport interface CastSwapEstimate {\n /**\n * The quote in credits: `breakdown.castSwap + breakdown.seedance +\n * breakdown.references`, plus `breakdown.masking` with face masking\n * `\"always\"`.\n */\n totalCredits: number\n /**\n * `castSwap`: the run itself; `seedance`: the video model it calls;\n * `references`: preparing the reference pictures (0 when `prepareReferences`\n * is off or there is nothing to prepare); `masking`: masking the faces,\n * present only when `faceMasking` is on. With `\"auto\"` it equals\n * `maskingCredits` and is not added to `totalCredits`.\n */\n breakdown: { castSwap: number; seedance: number; references: number; masking?: number }\n /**\n * Face masking `\"auto\"` only: the extra credits charged if the source clip\n * is refused and the run is retried with the faces masked. Not in\n * `totalCredits`; `run()` needs credits for both (else 402).\n */\n maskingCredits?: number\n /** `true` when the video is made at Auto length: the final charge is expected to come out lower than this quote. */\n settlesLower: boolean\n}\n\n/** Per-call options for {@link CastSwapResource.run}. */\nexport interface CastSwapRunOptions {\n /**\n * Sent as the `Idempotency-Key` header, unchanged (the SDK checks nothing;\n * an empty string sends no header, like no key).\n * The server takes 8–200 characters and answers 400 for any other length.\n * Reuse the same value when retrying the same run: within about 10 s the\n * repeat answers 200 `{ jobId, deduped: true }`, later 202 with the first\n * run's `jobId`. Nothing new is started or charged.\n */\n idempotencyKey?: string\n}\n\n/**\n * What finishing a draft at Full Quality would cost\n * (`POST /v1/cast-swap/:jobId/full-quality/estimate`).\n */\nexport interface CastSwapFullQualityEstimate {\n /** The quote in credits: `breakdown.castSwap + breakdown.seedanceHd`. */\n totalCredits: number\n /**\n * `castSwap`: the Full Quality job's own steps; `seedanceHd`: the 1080p\n * render of the draft's take (0 when an earlier try of this draft already\n * finished that render, which is then reused).\n */\n breakdown: { castSwap: number; seedanceHd: number }\n /** ISO time until which the draft can be finished at Full Quality (7 days after it completed). */\n availableUntil: string\n}\n\n/** Options for {@link CastSwapResource.fullQuality}. */\nexport interface CastSwapFullQualityParams {\n /** A generation session to file the Full Quality result in. */\n sessionId?: string\n}\n\n/** The Full Quality job (`POST /v1/cast-swap/:jobId/full-quality`). */\nexport interface CastSwapFullQualityResult {\n jobId: string\n /** `true` when this draft's Full Quality was already running or done: that job is answered, nothing new is started or charged. */\n existing?: boolean\n}\n\n/**\n * The `code` of a Full Quality refusal (`NodaroError.code`), all before\n * anything is charged:\n * - `unauthorized` (401): no authenticated user;\n * - `not_found` (404): not your job, or not a Cast Swap run; also a\n * `sessionId` you may not use;\n * - `not_completed` (409): the run has not finished;\n * - `not_a_draft` (409): the run was not made as a draft;\n * - `draft_expired` (410): more than 7 days after the draft completed, or\n * the draft can no longer be finished at Full Quality;\n * - `full_quality_pending` (409, `details.retryable: true`): not final — an\n * earlier try's 1080p render of this draft is being reviewed, or has not\n * started yet; try again later (once the review ends). The only refusal\n * that ends on its own;\n * - `full_quality_unavailable` (409): final — nothing kept to re-render, no\n * readable completion time, or the 1080p finalize refuses this draft; on\n * the start only, also \"failed too many times\" (every try failed) or no\n * try can be started for this run;\n * - `insufficient_credits` (402), or in a workspace `budget_exceeded`,\n * `member_cap_exceeded` or `user_allowance_exceeded`;\n * - `job_blocked` (422): the request was blocked by the job policy;\n * - `job_read_failed` (503, retryable), `estimate_unavailable` (503, try\n * again shortly), `host_too_old` (503).\n *\n * Open-ended: a code not listed here may still arrive.\n */\nexport type CastSwapFullQualityRefusalCode =\n | \"unauthorized\"\n | \"not_found\"\n | \"not_completed\"\n | \"not_a_draft\"\n | \"draft_expired\"\n | \"full_quality_pending\"\n | \"full_quality_unavailable\"\n | \"insufficient_credits\"\n | \"budget_exceeded\"\n | \"member_cap_exceeded\"\n | \"user_allowance_exceeded\"\n | \"job_blocked\"\n | \"job_read_failed\"\n | \"estimate_unavailable\"\n | \"host_too_old\"\n | (string & {})\n\nexport class CastSwapResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * Start a Cast Swap run (`POST /v1/cast-swap`, 202 `{ jobId }`). Returns the\n * job to follow. With `options.idempotencyKey` (sent as the\n * `Idempotency-Key` header; 8–200 characters, else 400) a repeat with the\n * same key within about 10 s answers 200 `{ jobId, deduped: true }`, a later\n * one 202 with the first run's `jobId`; nothing new starts.\n */\n run(params: CastSwapParams, options?: CastSwapRunOptions): Promise<{ jobId: string; deduped?: boolean }> {\n return this.client.request(\"POST\", \"/v1/cast-swap\", {\n body: params,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n })\n }\n\n /** Quote a run before starting it (`POST /v1/cast-swap/estimate`); spends nothing. */\n estimate(params: CastSwapParams): Promise<CastSwapEstimate> {\n return this.client.request(\"POST\", \"/v1/cast-swap/estimate\", { body: params })\n }\n\n /**\n * Quote finishing a draft at Full Quality (`POST\n * /v1/cast-swap/:jobId/full-quality/estimate`); spends nothing. `jobId` is a\n * finished DRAFT run (a Cast Swap or trend run made as a draft). The quote\n * does not look for a Full Quality already running: when one is,\n * {@link fullQuality} answers it (`existing: true`) and charges nothing.\n * Refusals: {@link CastSwapFullQualityRefusalCode}.\n */\n fullQualityEstimate(jobId: string): Promise<CastSwapFullQualityEstimate> {\n return this.client.request(\"POST\", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality/estimate`, { body: {} })\n }\n\n /**\n * Finish a draft at Full Quality (`POST /v1/cast-swap/:jobId/full-quality`):\n * the same take re-rendered at 1080p, with the clip's audio, as a new job\n * linked to the draft. SPENDS CREDITS: quote it first with\n * {@link fullQualityEstimate}. Answers 202 `{ jobId }`, or 200\n * `{ jobId, existing: true }` when this draft's Full Quality is already\n * running or done (one per draft; a failed one may be asked again). Follow\n * the job with `client.jobs.get(jobId)`. No `Idempotency-Key` is taken: the\n * server keys the job by the draft. The new job keeps the draft's origin.\n * Refusals: {@link CastSwapFullQualityRefusalCode}.\n */\n fullQuality(jobId: string, params: CastSwapFullQualityParams = {}): Promise<CastSwapFullQualityResult> {\n const body = params.sessionId !== undefined ? { sessionId: params.sessionId } : {}\n return this.client.request(\"POST\", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality`, { body })\n }\n}\n"]}
|