@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.
Files changed (195) hide show
  1. package/dist/{chunk-CFY6XXOT.cjs → chunk-3WNEIBTH.cjs} +37 -33
  2. package/dist/chunk-3WNEIBTH.cjs.map +1 -0
  3. package/dist/{chunk-JMOKD6ZP.js → chunk-7CUWAVWB.js} +3 -3
  4. package/dist/{chunk-JMOKD6ZP.js.map → chunk-7CUWAVWB.js.map} +1 -1
  5. package/dist/{chunk-E5BM4BLO.js → chunk-7IWVDWSP.js} +20 -3
  6. package/dist/chunk-7IWVDWSP.js.map +1 -0
  7. package/dist/{chunk-RHJRLXKY.cjs → chunk-7XOK277W.cjs} +9 -9
  8. package/dist/{chunk-RHJRLXKY.cjs.map → chunk-7XOK277W.cjs.map} +1 -1
  9. package/dist/{chunk-3QBH2VE2.cjs → chunk-A7QSOD2S.cjs} +20 -3
  10. package/dist/chunk-A7QSOD2S.cjs.map +1 -0
  11. package/dist/{chunk-VV4TZG5S.js → chunk-AUKHMT53.js} +3 -3
  12. package/dist/chunk-AUKHMT53.js.map +1 -0
  13. package/dist/{chunk-CWH642B2.js → chunk-AVOQ5DG4.js} +22 -18
  14. package/dist/chunk-AVOQ5DG4.js.map +1 -0
  15. package/dist/{chunk-I6CXC345.js → chunk-D2ILCSOQ.js} +3 -3
  16. package/dist/{chunk-I6CXC345.js.map → chunk-D2ILCSOQ.js.map} +1 -1
  17. package/dist/{chunk-4NLVBYMW.js → chunk-DQAYIVVS.js} +42 -8
  18. package/dist/chunk-DQAYIVVS.js.map +1 -0
  19. package/dist/chunk-ED3ZOX3M.js +54 -0
  20. package/dist/chunk-ED3ZOX3M.js.map +1 -0
  21. package/dist/{chunk-5ALNFATQ.cjs → chunk-EK672FFM.cjs} +2 -2
  22. package/dist/chunk-EK672FFM.cjs.map +1 -0
  23. package/dist/{chunk-OXQKE5EG.cjs → chunk-ETX3TLNB.cjs} +43 -9
  24. package/dist/{chunk-4NLVBYMW.js.map → chunk-ETX3TLNB.cjs.map} +1 -1
  25. package/dist/{chunk-BRV7Z4GD.cjs → chunk-FHVNTS4E.cjs} +2 -2
  26. package/dist/{chunk-BRV7Z4GD.cjs.map → chunk-FHVNTS4E.cjs.map} +1 -1
  27. package/dist/{chunk-N6GLZOE4.cjs → chunk-FM2KM5TY.cjs} +52 -10
  28. package/dist/chunk-FM2KM5TY.cjs.map +1 -0
  29. package/dist/{chunk-53SXNN3A.js → chunk-FQNCIP6K.js} +2 -2
  30. package/dist/chunk-FQNCIP6K.js.map +1 -0
  31. package/dist/{chunk-KNMW722T.cjs → chunk-FRQJNGJS.cjs} +5 -5
  32. package/dist/{chunk-KNMW722T.cjs.map → chunk-FRQJNGJS.cjs.map} +1 -1
  33. package/dist/{chunk-4CXB7RA6.js → chunk-IGMWFEFB.js} +6 -4
  34. package/dist/chunk-IGMWFEFB.js.map +1 -0
  35. package/dist/{chunk-5MTCKWKA.cjs → chunk-IISVYX5J.cjs} +5 -5
  36. package/dist/{chunk-5MTCKWKA.cjs.map → chunk-IISVYX5J.cjs.map} +1 -1
  37. package/dist/{chunk-6OGGJQVA.js → chunk-ILG5DHQQ.js} +2 -2
  38. package/dist/chunk-ILG5DHQQ.js.map +1 -0
  39. package/dist/{chunk-ZQQABQMH.cjs → chunk-JTOEHQQJ.cjs} +12 -2
  40. package/dist/chunk-JTOEHQQJ.cjs.map +1 -0
  41. package/dist/{chunk-ZXJQSFIA.js → chunk-JUON5NXA.js} +2 -2
  42. package/dist/{chunk-ZXJQSFIA.js.map → chunk-JUON5NXA.js.map} +1 -1
  43. package/dist/{chunk-JGS6YBDW.js → chunk-L6T44A3G.js} +51 -11
  44. package/dist/chunk-L6T44A3G.js.map +1 -0
  45. package/dist/{chunk-U4T3Z3K7.cjs → chunk-NKH2UFSD.cjs} +5 -5
  46. package/dist/chunk-NKH2UFSD.cjs.map +1 -0
  47. package/dist/{chunk-E2ZXHS6E.js → chunk-OIPPTBW4.js} +2 -2
  48. package/dist/chunk-OIPPTBW4.js.map +1 -0
  49. package/dist/{chunk-DKEYSJCE.cjs → chunk-OIYMTGYN.cjs} +2 -2
  50. package/dist/chunk-OIYMTGYN.cjs.map +1 -0
  51. package/dist/{chunk-NLQQHJ25.cjs → chunk-OSMKIRKI.cjs} +4 -4
  52. package/dist/{chunk-NLQQHJ25.cjs.map → chunk-OSMKIRKI.cjs.map} +1 -1
  53. package/dist/chunk-PG2GBS3K.cjs +4 -0
  54. package/dist/chunk-PG2GBS3K.cjs.map +1 -0
  55. package/dist/{chunk-GB724HW2.cjs → chunk-PQ7OKM3E.cjs} +6 -4
  56. package/dist/chunk-PQ7OKM3E.cjs.map +1 -0
  57. package/dist/{chunk-VFMWBW2Q.js → chunk-Q6HY2Q5V.js} +4 -4
  58. package/dist/{chunk-VFMWBW2Q.js.map → chunk-Q6HY2Q5V.js.map} +1 -1
  59. package/dist/chunk-QGOEQGAE.js +102 -0
  60. package/dist/chunk-QGOEQGAE.js.map +1 -0
  61. package/dist/{chunk-EAGD6NEE.cjs → chunk-QZHRXPN5.cjs} +22 -22
  62. package/dist/chunk-QZHRXPN5.cjs.map +1 -0
  63. package/dist/{chunk-KGKCAGRD.cjs → chunk-TCLNSVYA.cjs} +2 -2
  64. package/dist/chunk-TCLNSVYA.cjs.map +1 -0
  65. package/dist/chunk-U2B7YQ2N.cjs +56 -0
  66. package/dist/chunk-U2B7YQ2N.cjs.map +1 -0
  67. package/dist/chunk-VCEYLJ2Q.cjs +104 -0
  68. package/dist/chunk-VCEYLJ2Q.cjs.map +1 -0
  69. package/dist/{chunk-VGWOIWRQ.cjs → chunk-VHSMOBU7.cjs} +2 -2
  70. package/dist/{chunk-VGWOIWRQ.cjs.map → chunk-VHSMOBU7.cjs.map} +1 -1
  71. package/dist/{chunk-T3SYREY4.js → chunk-WY4QRJZW.js} +12 -2
  72. package/dist/chunk-WY4QRJZW.js.map +1 -0
  73. package/dist/chunk-YCVRQZT3.js +3 -0
  74. package/dist/chunk-YCVRQZT3.js.map +1 -0
  75. package/dist/{chunk-DPSMVOM3.js → chunk-YSZM3N7Q.js} +2 -2
  76. package/dist/chunk-YSZM3N7Q.js.map +1 -0
  77. package/dist/{chunk-5A7J24LN.js → chunk-Z7UZ3FD3.js} +3 -3
  78. package/dist/{chunk-5A7J24LN.js.map → chunk-Z7UZ3FD3.js.map} +1 -1
  79. package/dist/{chunk-4JKI6JRC.js → chunk-ZDSC6KBT.js} +3 -3
  80. package/dist/chunk-ZDSC6KBT.js.map +1 -0
  81. package/dist/entries/apps.cjs +2 -2
  82. package/dist/entries/apps.d.cts +4 -0
  83. package/dist/entries/apps.d.ts +4 -0
  84. package/dist/entries/apps.js +1 -1
  85. package/dist/entries/cast-swap.cjs +2 -2
  86. package/dist/entries/cast-swap.d.cts +271 -18
  87. package/dist/entries/cast-swap.d.ts +271 -18
  88. package/dist/entries/cast-swap.js +1 -1
  89. package/dist/entries/characters.d.cts +2 -2
  90. package/dist/entries/characters.d.ts +2 -2
  91. package/dist/entries/client.cjs +25 -24
  92. package/dist/entries/client.d.cts +5 -2
  93. package/dist/entries/client.d.ts +5 -2
  94. package/dist/entries/client.js +20 -19
  95. package/dist/entries/copilot.cjs +4 -4
  96. package/dist/entries/copilot.js +3 -3
  97. package/dist/entries/core.cjs +6 -6
  98. package/dist/entries/core.js +2 -2
  99. package/dist/entries/creatures.d.cts +2 -2
  100. package/dist/entries/creatures.d.ts +2 -2
  101. package/dist/entries/credits.cjs +2 -2
  102. package/dist/entries/credits.d.cts +37 -2
  103. package/dist/entries/credits.d.ts +37 -2
  104. package/dist/entries/credits.js +1 -1
  105. package/dist/entries/edit.cjs +7 -7
  106. package/dist/entries/edit.d.cts +3 -0
  107. package/dist/entries/edit.d.ts +3 -0
  108. package/dist/entries/edit.js +2 -2
  109. package/dist/entries/errors.cjs +30 -22
  110. package/dist/entries/errors.d.cts +42 -4
  111. package/dist/entries/errors.d.ts +42 -4
  112. package/dist/entries/errors.js +1 -1
  113. package/dist/entries/jobs.cjs +2 -2
  114. package/dist/entries/jobs.d.cts +76 -4
  115. package/dist/entries/jobs.d.ts +76 -4
  116. package/dist/entries/jobs.js +1 -1
  117. package/dist/entries/locations.d.cts +2 -2
  118. package/dist/entries/locations.d.ts +2 -2
  119. package/dist/entries/media.cjs +4 -4
  120. package/dist/entries/media.d.cts +39 -5
  121. package/dist/entries/media.d.ts +39 -5
  122. package/dist/entries/media.js +3 -3
  123. package/dist/entries/nodes.cjs +3 -3
  124. package/dist/entries/nodes.d.cts +2 -2
  125. package/dist/entries/nodes.d.ts +2 -2
  126. package/dist/entries/nodes.js +2 -2
  127. package/dist/entries/objects.d.cts +2 -2
  128. package/dist/entries/objects.d.ts +2 -2
  129. package/dist/entries/prompt-helper.cjs +2 -2
  130. package/dist/entries/prompt-helper.d.cts +3 -1
  131. package/dist/entries/prompt-helper.d.ts +3 -1
  132. package/dist/entries/prompt-helper.js +1 -1
  133. package/dist/entries/scene3d.d.cts +3 -3
  134. package/dist/entries/scene3d.d.ts +3 -3
  135. package/dist/entries/studio.cjs +5 -5
  136. package/dist/entries/studio.d.cts +2 -2
  137. package/dist/entries/studio.d.ts +2 -2
  138. package/dist/entries/studio.js +2 -2
  139. package/dist/entries/templates.cjs +2 -2
  140. package/dist/entries/templates.d.cts +4 -0
  141. package/dist/entries/templates.d.ts +4 -0
  142. package/dist/entries/templates.js +1 -1
  143. package/dist/entries/trends.cjs +13 -0
  144. package/dist/entries/trends.cjs.map +1 -0
  145. package/dist/entries/trends.d.cts +295 -0
  146. package/dist/entries/trends.d.ts +295 -0
  147. package/dist/entries/trends.js +4 -0
  148. package/dist/entries/trends.js.map +1 -0
  149. package/dist/entries/tutorials.cjs +2 -2
  150. package/dist/entries/tutorials.d.cts +4 -0
  151. package/dist/entries/tutorials.d.ts +4 -0
  152. package/dist/entries/tutorials.js +1 -1
  153. package/dist/entries/uploads.cjs +2 -2
  154. package/dist/entries/uploads.d.cts +14 -1
  155. package/dist/entries/uploads.d.ts +14 -1
  156. package/dist/entries/uploads.js +1 -1
  157. package/dist/entries/workflows.cjs +2 -2
  158. package/dist/entries/workflows.d.cts +6 -0
  159. package/dist/entries/workflows.d.ts +6 -0
  160. package/dist/entries/workflows.js +1 -1
  161. package/dist/index.cjs +85 -71
  162. package/dist/index.d.cts +8 -7
  163. package/dist/index.d.ts +8 -7
  164. package/dist/index.js +22 -20
  165. package/dist/{nodes-D2tbtzt7.d.ts → nodes-9WpYNWtS.d.ts} +13 -1
  166. package/dist/{nodes-CTujw6Qd.d.cts → nodes-BDUk5Aej.d.cts} +13 -1
  167. package/dist/{studio-productions-vbCNSbtf.d.ts → studio-productions-DtTE8mdl.d.ts} +35 -1
  168. package/dist/{studio-productions-DUHvdSvk.d.cts → studio-productions-r2-VZsKj.d.cts} +35 -1
  169. package/package.json +7 -2
  170. package/dist/chunk-3QBH2VE2.cjs.map +0 -1
  171. package/dist/chunk-4CXB7RA6.js.map +0 -1
  172. package/dist/chunk-4JKI6JRC.js.map +0 -1
  173. package/dist/chunk-53SXNN3A.js.map +0 -1
  174. package/dist/chunk-5ALNFATQ.cjs.map +0 -1
  175. package/dist/chunk-6OGGJQVA.js.map +0 -1
  176. package/dist/chunk-CFY6XXOT.cjs.map +0 -1
  177. package/dist/chunk-CWH642B2.js.map +0 -1
  178. package/dist/chunk-DKEYSJCE.cjs.map +0 -1
  179. package/dist/chunk-DPSMVOM3.js.map +0 -1
  180. package/dist/chunk-E2ZXHS6E.js.map +0 -1
  181. package/dist/chunk-E5BM4BLO.js.map +0 -1
  182. package/dist/chunk-EAGD6NEE.cjs.map +0 -1
  183. package/dist/chunk-GB724HW2.cjs.map +0 -1
  184. package/dist/chunk-GDXS4EJ5.js +0 -28
  185. package/dist/chunk-GDXS4EJ5.js.map +0 -1
  186. package/dist/chunk-GVBSOZDI.cjs +0 -30
  187. package/dist/chunk-GVBSOZDI.cjs.map +0 -1
  188. package/dist/chunk-JGS6YBDW.js.map +0 -1
  189. package/dist/chunk-KGKCAGRD.cjs.map +0 -1
  190. package/dist/chunk-N6GLZOE4.cjs.map +0 -1
  191. package/dist/chunk-OXQKE5EG.cjs.map +0 -1
  192. package/dist/chunk-T3SYREY4.js.map +0 -1
  193. package/dist/chunk-U4T3Z3K7.cjs.map +0 -1
  194. package/dist/chunk-VV4TZG5S.js.map +0 -1
  195. package/dist/chunk-ZQQABQMH.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkN6GLZOE4_cjs = require('./chunk-N6GLZOE4.cjs');
3
+ var chunkFM2KM5TY_cjs = require('./chunk-FM2KM5TY.cjs');
4
4
  var organizations = require('@nodaro/shared/organizations');
5
5
 
6
6
  // src/binary-response.ts
@@ -36,7 +36,7 @@ async function readBinaryResponse(response, maxBytes) {
36
36
  }
37
37
  return bytes.buffer;
38
38
  }
39
- var SDK_VERSION = "2.34.0" ;
39
+ var SDK_VERSION = "2.38.0" ;
40
40
  var CLIENT_HEADER = "X-Nodaro-Client";
41
41
  var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
42
42
  var NodaroClientCore = class {
@@ -107,7 +107,7 @@ var NodaroClientCore = class {
107
107
  errBody = await res.json();
108
108
  } catch {
109
109
  }
110
- chunkN6GLZOE4_cjs.throwFromResponse(res.status, errBody);
110
+ chunkFM2KM5TY_cjs.throwFromResponse(res.status, errBody);
111
111
  }
112
112
  return await read(res);
113
113
  } finally {
@@ -229,5 +229,5 @@ exports.CallbackAuth = CallbackAuth;
229
229
  exports.NodaroClientCore = NodaroClientCore;
230
230
  exports.StaticTokenAuth = StaticTokenAuth;
231
231
  exports.supabaseAuth = supabaseAuth;
232
- //# sourceMappingURL=chunk-5MTCKWKA.cjs.map
233
- //# sourceMappingURL=chunk-5MTCKWKA.cjs.map
232
+ //# sourceMappingURL=chunk-IISVYX5J.cjs.map
233
+ //# sourceMappingURL=chunk-IISVYX5J.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":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AoC;AAC/D,EAAA,OAAO;AAAA,IACL,MAAM,QAAA,GAAW;AACf,MAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,QAAA,CAAS,KAAK,UAAA,EAAW;AAChD,MAAA,OAAO,IAAA,CAAK,SAAS,YAAA,IAAgB,IAAA;AAAA,IACvC;AAAA,GACF;AACF","file":"chunk-5MTCKWKA.cjs","sourcesContent":["/** Bound decoded response bytes even when Content-Length is absent or compressed. */\nexport async function readBinaryResponse(response: Response, maxBytes: number): Promise<ArrayBuffer> {\n const advertised = response.headers.get(\"content-length\")\n if (advertised !== null && (!/^\\d+$/.test(advertised) || Number(advertised) > maxBytes)) {\n await response.body?.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n if (!response.body) return new ArrayBuffer(0)\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n length += next.value.byteLength\n if (length > maxBytes) {\n await reader.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n chunks.push(next.value)\n }\n } finally { reader.releaseLock() }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }\n return bytes.buffer\n}\n","/**\n * The client core: configuration, auth, the request transport and the\n * account-identity calls — everything a resource needs, and none of the\n * resources themselves.\n *\n * {@link NodaroClient} (`createClient`) extends it with every resource. An app\n * that uses only a few resources can extend it with just those, so it loads\n * (and its tests depend on) only the resource modules it actually uses:\n *\n * class AppClient extends NodaroClientCore {\n * readonly jobs = new JobsResource(this)\n * readonly nodes = new NodesResource(this) // needs `jobs` on the same client\n * }\n *\n * A resource that calls another one through the client says so in its\n * constructor type (`NodesResource` takes a core that also has `jobs`), so a\n * client missing it fails to compile rather than at run time.\n */\nimport { readBinaryResponse } from \"./binary-response.js\"\nimport { throwFromResponse } from \"./errors.js\"\nimport type { Auth } from \"./auth.js\"\nimport type { DeveloperAppKind, DeveloperAppScope } from \"./resources/developer-apps.js\"\nimport { WORKSPACE_HEADER, type MeOrganizations } from \"@nodaro/shared/organizations\"\n\n/** Replaced at build time by tsup `define` from package.json. The fallback\n * keeps `tsx`/vitest runs of the source working, where no define applies. */\ndeclare const __SDK_VERSION__: string | undefined\nconst SDK_VERSION = typeof __SDK_VERSION__ === \"string\" ? __SDK_VERSION__ : \"0.0.0-dev\"\n\n/**\n * Identifies the calling package to the backend, which records it as the job's\n * provenance (`jobs.source` / `source_detail`) so an operator can tell a CLI\n * run from an SDK integration from a browser session.\n *\n * Only `sdk/…` and `cli/…` are honoured server-side; anything else is ignored\n * rather than trusted, since this is an unauthenticated header.\n */\nexport const CLIENT_HEADER = \"X-Nodaro-Client\"\n\n/**\n * In a browser the header is redundant AND a liability, so it is not sent.\n *\n * Redundant: the browser already sends `Origin`, which names the actual product\n * (`studio.nodaro.ai`) rather than merely the library it used — and the backend\n * deliberately prefers Origin over this header, so a browser-sent value is\n * discarded on arrival.\n *\n * A liability: `X-Nodaro-Client` is not a CORS-safelisted request header, so a\n * browser sending it requires an exact match in the server's\n * `Access-Control-Allow-Headers`. Any deployment whose backend predates that\n * allowlist entry would fail the PREFLIGHT — breaking every API call from the\n * app, not just its provenance. Self-hosted and lagging deployments make that a\n * real risk, and nothing in a browser app would reveal the cause.\n *\n * An EXPLICIT `clientLabel` is always sent regardless: a caller that names\n * itself has opted in deliberately, and that intent outranks this default.\n */\nconst isBrowser = (): boolean => typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\nexport interface ClientOptions {\n /** Backend base URL, e.g. \"https://nodaro.example.com\" or empty string for same-origin. */\n baseUrl: string\n /** Auth provider. Use StaticTokenAuth, supabaseAuth, or CallbackAuth. */\n auth: Auth\n /** Optional fetch override (for tests or custom transports). */\n fetch?: typeof fetch\n /** Default request timeout in ms. Default 60s. */\n timeoutMs?: number\n /**\n * Overrides the `X-Nodaro-Client` label. Defaults to `sdk/<version>`.\n *\n * Exists for `@nodaro/cli`, which is a wrapper AROUND this SDK: without an\n * override every CLI invocation would be recorded as an SDK call and the two\n * surfaces could never be told apart.\n */\n clientLabel?: string\n /**\n * The workspace every request acts in — sent as `X-Nodaro-Workspace`.\n *\n * It selects which workspace a LIST reads from and where a CREATE lands.\n * It never authorizes: reading, updating, deleting or running an\n * identified object is decided by that object's own workspace, so a\n * forgotten header cannot hide work and a forged one cannot reach anyone\n * else's. Omit it to work in the caller's personal space.\n *\n * Prefer {@link NodaroClient.withWorkspace} for anything short-lived — one\n * client per workspace, no shared mutable selection to get wrong.\n */\n workspaceId?: string\n}\n\ninterface RequestOptions {\n body?: unknown\n query?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n signal?: AbortSignal\n}\n\n/**\n * The authenticated user's canonical identity (`GET /v1/me`). A token-\n * introspection primitive: any valid bearer token (first-party Supabase JWT or\n * a developer-app OAuth token) resolves to its owner's identity. Mirrors the\n * `profiles` identity columns server-side — the route is the source of truth.\n */\nexport interface UserIdentity {\n /** Nodaro user id (= the Supabase auth user id). */\n readonly id: string\n readonly email: string\n /** Human-readable display name (from `profiles.full_name`); `null` if unset. */\n readonly displayName: string | null\n /** Avatar URL; `null` if unset. */\n readonly avatarUrl: string | null\n /** Subscription tier (e.g. \"free\", \"pro\"). */\n readonly tier: string\n /**\n * Whether the user holds an admin role. DESCRIPTIVE only — use it to decide\n * whether to render admin surfaces without capability-probing an admin\n * endpoint; every admin API stays enforced server-side regardless.\n */\n readonly isAdmin: boolean\n}\n\n/**\n * An app the user let into their account through OAuth (`GET\n * /v1/me/connected-apps`): a developer app, an AI assistant's MCP connector, or\n * a self-hosted install. One entry per grant still in force.\n */\nexport interface ConnectedApp {\n /** The grant's id — what {@link NodaroClient.revokeConnectedApp} takes. */\n readonly authorizationId: string\n /** The app's name; `null` if it has none. A `dynamic_mcp` client chose its own. */\n readonly name: string | null\n /**\n * How the app came to exist: `user` (a developer app someone registered),\n * `first_party_mcp`, `dynamic_mcp` (an MCP client that registered itself) or\n * `community_instance` (a self-hosted install).\n */\n readonly kind: DeveloperAppKind | (string & {})\n readonly homepageUrl: string | null\n /** The scopes this grant holds. */\n readonly scopes: readonly DeveloperAppScope[]\n /** When the user granted access (ISO 8601). */\n readonly connectedAt: string\n /** The latest use of any token issued under the grant; `null` if never used. */\n readonly lastUsedAt: string | null\n}\n\nexport class NodaroClientCore {\n readonly baseUrl: string\n readonly auth: Auth\n readonly timeoutMs: number\n /** Value sent as `X-Nodaro-Client`; recorded by the backend as job provenance. */\n readonly clientLabel: string\n /** Whether to actually send it — see the note on {@link CLIENT_HEADER}. */\n private readonly sendClientHeader: boolean\n private readonly fetchOverride: typeof fetch | undefined\n\n /**\n * Resolved lazily so consumers can swap `globalThis.fetch` after the\n * client has been constructed (e.g. test mocks). Always rebound to the\n * global object — native fetch throws \"Illegal invocation\" when its\n * `this` is anything else.\n */\n get fetch(): typeof fetch {\n return this.fetchOverride ?? globalThis.fetch.bind(globalThis)\n }\n\n /** The workspace this client acts in; undefined = the personal space. */\n readonly workspaceId: string | undefined\n\n constructor(opts: ClientOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\") // strip trailing slash\n this.auth = opts.auth\n this.fetchOverride = opts.fetch\n this.timeoutMs = opts.timeoutMs ?? 60_000\n this.clientLabel = opts.clientLabel ?? `sdk/${SDK_VERSION}`\n this.workspaceId = opts.workspaceId\n // Explicit label = deliberate opt-in, always sent. The default is suppressed\n // in browsers — see the note on CLIENT_HEADER.\n this.sendClientHeader = opts.clientLabel !== undefined || !isBrowser()\n }\n\n /**\n * The transport: build the request, send it, throw the typed error on a\n * non-2xx via {@link throwFromResponse}, then read the body via `read` — all\n * inside the abort timer, so `timeoutMs` bounds the body download too (a\n * stalled CSV stream aborts, it does not hang forever). Both the JSON path\n * ({@link request}) and the text path ({@link requestText}) go through here.\n */\n private async send<T>(\n method: string,\n path: string,\n options: RequestOptions,\n read: (res: Response) => Promise<T>,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query)\n\n const token = await this.auth.getToken()\n // A `FormData` body is a multipart upload: let the runtime set\n // `Content-Type: multipart/form-data; boundary=…` itself (a manual JSON\n // content-type corrupts the boundary), and send the body as-is rather than\n // JSON-stringifying it. Every other body stays JSON, exactly as before.\n const isFormData =\n typeof FormData !== \"undefined\" && options.body instanceof FormData\n const headers: Record<string, string> = {\n ...(isFormData ? {} : { \"Content-Type\": \"application/json\" }),\n ...(this.sendClientHeader ? { [CLIENT_HEADER]: this.clientLabel } : {}),\n // Before per-request headers: a resource that needs to reach outside\n // this client's workspace says so explicitly and wins.\n ...(this.workspaceId ? { [WORKSPACE_HEADER]: this.workspaceId } : {}),\n ...(options.headers ?? {}),\n }\n if (token) headers[\"Authorization\"] = `Bearer ${token}`\n\n const ac = new AbortController()\n const timeoutId = setTimeout(() => ac.abort(), this.timeoutMs)\n const abort = () => ac.abort(options.signal?.reason)\n options.signal?.addEventListener(\"abort\", abort, { once: true })\n if (options.signal?.aborted) abort()\n\n try {\n ac.signal.throwIfAborted()\n const res = await this.fetch(url, {\n method,\n headers,\n body:\n options.body === undefined\n ? undefined\n : isFormData\n ? (options.body as FormData)\n : JSON.stringify(options.body),\n signal: ac.signal,\n })\n\n if (!res.ok) {\n let errBody: Record<string, unknown> = {}\n try {\n errBody = await res.json() as Record<string, unknown>\n } catch {\n // Empty/non-JSON body — fall through with empty errBody\n }\n throwFromResponse(res.status, errBody)\n }\n\n return await read(res)\n } finally {\n clearTimeout(timeoutId)\n options.signal?.removeEventListener(\"abort\", abort)\n }\n }\n\n /** Authenticated, bounded binary reads through the normal timeout/error transport. */\n async requestBytes(method: string, path: string, options: RequestOptions & { maxBytes: number }): Promise<ArrayBuffer> {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) throw new Error(\"maxBytes must be a positive integer\")\n return this.send(method, path, options, (response) => readBinaryResponse(response, options.maxBytes))\n }\n\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n return this.send(method, path, options, async (res) =>\n // 204 No Content\n res.status === 204 ? (undefined as T) : ((await res.json()) as T),\n )\n }\n\n /**\n * Like {@link request}, for endpoints that answer text (CSV exports). Errors\n * are still the JSON envelope and throw the same typed errors, and the read is\n * bounded by the same timeout as the request.\n */\n async requestText(method: string, path: string, options: RequestOptions = {}): Promise<string> {\n return this.send(method, path, options, (res) => res.text())\n }\n\n /**\n * `GET /v1/me` → the authenticated user's identity (see {@link UserIdentity}).\n * Unwraps the `{ data }` envelope. Throws `UnauthorizedError` (401) when the\n * token is missing/invalid, and the SDK's other typed errors as usual.\n *\n * On an instance with organizations it also carries what the caller belongs\n * to. THREE states, and collapsing them is wrong in a way users feel: the\n * organization fields ABSENT means this instance has no organizations at\n * all; present and empty means the account belongs to none; and\n * `organizationsUnavailable` means the lookup failed — keep whatever\n * selection you already had rather than concluding the person was removed\n * from everything.\n */\n async me(): Promise<UserIdentity & MeOrganizations> {\n const res = await this.request<{ data: UserIdentity & MeOrganizations }>(\"GET\", \"/v1/me\")\n return res.data\n }\n\n /**\n * `GET /v1/me/connected-apps` → every app with access to the signed-in\n * user's account (see {@link ConnectedApp}), newest grant first.\n *\n * **A signed-in browser session only.** The route answers a Supabase\n * session token (`supabaseAuth(…)`, `createSharedSupabaseClient`, or a\n * `StaticTokenAuth` holding one) and refuses every other credential with\n * `UnauthorizedError` (\"Sign in required\"): an app token or an API key must\n * not list the grants it lives under. Build your \"Connected apps\" settings\n * screen on this; a server-side integration cannot call it.\n */\n async connectedApps(): Promise<ConnectedApp[]> {\n const res = await this.request<{ apps: ConnectedApp[] }>(\"GET\", \"/v1/me/connected-apps\")\n return res.apps\n }\n\n /**\n * `POST /v1/me/connected-apps/:authorizationId/revoke` — ends an app's\n * access: the grant and every token issued under it, at once (the app's next\n * call is a 401). Resolves when done.\n *\n * A signed-in browser session only, like {@link connectedApps}. Throws\n * `NotFoundError` when the grant is not the user's or is already revoked.\n */\n async revokeConnectedApp(authorizationId: string): Promise<void> {\n await this.request(\"POST\", `/v1/me/connected-apps/${encodeURIComponent(authorizationId)}/revoke`)\n }\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n const base = this.baseUrl || (typeof window !== \"undefined\" ? window.location.origin : \"http://placeholder\")\n const url = new URL(path, base)\n // If baseUrl was empty, strip the placeholder origin\n const fullUrl = this.baseUrl ? url.toString() : url.pathname + url.search\n if (query) {\n const u = new URL(this.baseUrl ? fullUrl : fullUrl, base)\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) u.searchParams.set(k, String(v))\n }\n return this.baseUrl ? u.toString() : u.pathname + u.search\n }\n return fullUrl\n }\n}\n","/**\n * Auth provides the token used for `Authorization: Bearer <token>` on each request.\n * Implementations:\n * - StaticTokenAuth — fixed string (server-side, OAuth access token, API token)\n * - CallbackAuth — caller-supplied async function (BYO logic)\n * - supabaseAuth — pulls JWT from a Supabase client live (browser frontends)\n */\nexport interface Auth {\n /** Returns the current Bearer token, or null if not authenticated. */\n getToken(): Promise<string | null>\n}\n\nexport class StaticTokenAuth implements Auth {\n constructor(private token: string) {}\n async getToken() {\n return this.token\n }\n}\n\nexport class CallbackAuth implements Auth {\n constructor(private fn: () => string | null | Promise<string | null>) {}\n async getToken() {\n return this.fn()\n }\n}\n\ninterface SupabaseLikeClient {\n auth: {\n getSession(): Promise<{ data: { session: { access_token: string } | null } }>\n }\n}\n\n/** Pulls a JWT from a Supabase v2 client. Caller supplies their own supabase. */\nexport function supabaseAuth(supabase: SupabaseLikeClient): Auth {\n return {\n async getToken() {\n const { data } = await supabase.auth.getSession()\n return data.session?.access_token ?? null\n },\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/binary-response.ts","../src/core.ts","../src/auth.ts"],"names":["WORKSPACE_HEADER","throwFromResponse"],"mappings":";;;;;;AACA,eAAsB,kBAAA,CAAmB,UAAoB,QAAA,EAAwC;AACnG,EAAA,MAAM,UAAA,GAAa,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA;AACxD,EAAA,IAAI,UAAA,KAAe,IAAA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["/** Bound decoded response bytes even when Content-Length is absent or compressed. */\nexport async function readBinaryResponse(response: Response, maxBytes: number): Promise<ArrayBuffer> {\n const advertised = response.headers.get(\"content-length\")\n if (advertised !== null && (!/^\\d+$/.test(advertised) || Number(advertised) > maxBytes)) {\n await response.body?.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n if (!response.body) return new ArrayBuffer(0)\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n length += next.value.byteLength\n if (length > maxBytes) {\n await reader.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n chunks.push(next.value)\n }\n } finally { reader.releaseLock() }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }\n return bytes.buffer\n}\n","/**\n * The client core: configuration, auth, the request transport and the\n * account-identity calls — everything a resource needs, and none of the\n * resources themselves.\n *\n * {@link NodaroClient} (`createClient`) extends it with every resource. An app\n * that uses only a few resources can extend it with just those, so it loads\n * (and its tests depend on) only the resource modules it actually uses:\n *\n * class AppClient extends NodaroClientCore {\n * readonly jobs = new JobsResource(this)\n * readonly nodes = new NodesResource(this) // needs `jobs` on the same client\n * }\n *\n * A resource that calls another one through the client says so in its\n * constructor type (`NodesResource` takes a core that also has `jobs`), so a\n * client missing it fails to compile rather than at run time.\n */\nimport { readBinaryResponse } from \"./binary-response.js\"\nimport { throwFromResponse } from \"./errors.js\"\nimport type { Auth } from \"./auth.js\"\nimport type { DeveloperAppKind, DeveloperAppScope } from \"./resources/developer-apps.js\"\nimport { WORKSPACE_HEADER, type MeOrganizations } from \"@nodaro/shared/organizations\"\n\n/** Replaced at build time by tsup `define` from package.json. The fallback\n * keeps `tsx`/vitest runs of the source working, where no define applies. */\ndeclare const __SDK_VERSION__: string | undefined\nconst SDK_VERSION = typeof __SDK_VERSION__ === \"string\" ? __SDK_VERSION__ : \"0.0.0-dev\"\n\n/**\n * Identifies the calling package to the backend, which records it as the job's\n * provenance (`jobs.source` / `source_detail`) so an operator can tell a CLI\n * run from an SDK integration from a browser session.\n *\n * Only `sdk/…` and `cli/…` are honoured server-side; anything else is ignored\n * rather than trusted, since this is an unauthenticated header.\n */\nexport const CLIENT_HEADER = \"X-Nodaro-Client\"\n\n/**\n * In a browser the header is redundant AND a liability, so it is not sent.\n *\n * Redundant: the browser already sends `Origin`, which names the actual product\n * (`studio.nodaro.ai`) rather than merely the library it used — and the backend\n * deliberately prefers Origin over this header, so a browser-sent value is\n * discarded on arrival.\n *\n * A liability: `X-Nodaro-Client` is not a CORS-safelisted request header, so a\n * browser sending it requires an exact match in the server's\n * `Access-Control-Allow-Headers`. Any deployment whose backend predates that\n * allowlist entry would fail the PREFLIGHT — breaking every API call from the\n * app, not just its provenance. Self-hosted and lagging deployments make that a\n * real risk, and nothing in a browser app would reveal the cause.\n *\n * An EXPLICIT `clientLabel` is always sent regardless: a caller that names\n * itself has opted in deliberately, and that intent outranks this default.\n */\nconst isBrowser = (): boolean => typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\nexport interface ClientOptions {\n /** Backend base URL, e.g. \"https://nodaro.example.com\" or empty string for same-origin. */\n baseUrl: string\n /** Auth provider. Use StaticTokenAuth, supabaseAuth, or CallbackAuth. */\n auth: Auth\n /** Optional fetch override (for tests or custom transports). */\n fetch?: typeof fetch\n /** Default request timeout in ms. Default 60s. */\n timeoutMs?: number\n /**\n * Overrides the `X-Nodaro-Client` label. Defaults to `sdk/<version>`.\n *\n * Exists for `@nodaro/cli`, which is a wrapper AROUND this SDK: without an\n * override every CLI invocation would be recorded as an SDK call and the two\n * surfaces could never be told apart.\n */\n clientLabel?: string\n /**\n * The workspace every request acts in — sent as `X-Nodaro-Workspace`.\n *\n * It selects which workspace a LIST reads from and where a CREATE lands.\n * It never authorizes: reading, updating, deleting or running an\n * identified object is decided by that object's own workspace, so a\n * forgotten header cannot hide work and a forged one cannot reach anyone\n * else's. Omit it to work in the caller's personal space.\n *\n * Prefer {@link NodaroClient.withWorkspace} for anything short-lived — one\n * client per workspace, no shared mutable selection to get wrong.\n */\n workspaceId?: string\n}\n\ninterface RequestOptions {\n body?: unknown\n query?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n signal?: AbortSignal\n}\n\n/**\n * The authenticated user's canonical identity (`GET /v1/me`). A token-\n * introspection primitive: any valid bearer token (first-party Supabase JWT or\n * a developer-app OAuth token) resolves to its owner's identity. Mirrors the\n * `profiles` identity columns server-side — the route is the source of truth.\n */\nexport interface UserIdentity {\n /** Nodaro user id (= the Supabase auth user id). */\n readonly id: string\n readonly email: string\n /** Human-readable display name (from `profiles.full_name`); `null` if unset. */\n readonly displayName: string | null\n /** Avatar URL; `null` if unset. */\n readonly avatarUrl: string | null\n /** Subscription tier (e.g. \"free\", \"pro\"). */\n readonly tier: string\n /**\n * Whether the user holds an admin role. DESCRIPTIVE only — use it to decide\n * whether to render admin surfaces without capability-probing an admin\n * endpoint; every admin API stays enforced server-side regardless.\n */\n readonly isAdmin: boolean\n}\n\n/**\n * An app the user let into their account through OAuth (`GET\n * /v1/me/connected-apps`): a developer app, an AI assistant's MCP connector, or\n * a self-hosted install. One entry per grant still in force.\n */\nexport interface ConnectedApp {\n /** The grant's id — what {@link NodaroClient.revokeConnectedApp} takes. */\n readonly authorizationId: string\n /** The app's name; `null` if it has none. A `dynamic_mcp` client chose its own. */\n readonly name: string | null\n /**\n * How the app came to exist: `user` (a developer app someone registered),\n * `first_party_mcp`, `dynamic_mcp` (an MCP client that registered itself) or\n * `community_instance` (a self-hosted install).\n */\n readonly kind: DeveloperAppKind | (string & {})\n readonly homepageUrl: string | null\n /** The scopes this grant holds. */\n readonly scopes: readonly DeveloperAppScope[]\n /** When the user granted access (ISO 8601). */\n readonly connectedAt: string\n /** The latest use of any token issued under the grant; `null` if never used. */\n readonly lastUsedAt: string | null\n}\n\nexport class NodaroClientCore {\n readonly baseUrl: string\n readonly auth: Auth\n readonly timeoutMs: number\n /** Value sent as `X-Nodaro-Client`; recorded by the backend as job provenance. */\n readonly clientLabel: string\n /** Whether to actually send it — see the note on {@link CLIENT_HEADER}. */\n private readonly sendClientHeader: boolean\n private readonly fetchOverride: typeof fetch | undefined\n\n /**\n * Resolved lazily so consumers can swap `globalThis.fetch` after the\n * client has been constructed (e.g. test mocks). Always rebound to the\n * global object — native fetch throws \"Illegal invocation\" when its\n * `this` is anything else.\n */\n get fetch(): typeof fetch {\n return this.fetchOverride ?? globalThis.fetch.bind(globalThis)\n }\n\n /** The workspace this client acts in; undefined = the personal space. */\n readonly workspaceId: string | undefined\n\n constructor(opts: ClientOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\") // strip trailing slash\n this.auth = opts.auth\n this.fetchOverride = opts.fetch\n this.timeoutMs = opts.timeoutMs ?? 60_000\n this.clientLabel = opts.clientLabel ?? `sdk/${SDK_VERSION}`\n this.workspaceId = opts.workspaceId\n // Explicit label = deliberate opt-in, always sent. The default is suppressed\n // in browsers — see the note on CLIENT_HEADER.\n this.sendClientHeader = opts.clientLabel !== undefined || !isBrowser()\n }\n\n /**\n * The transport: build the request, send it, throw the typed error on a\n * non-2xx via {@link throwFromResponse}, then read the body via `read` — all\n * inside the abort timer, so `timeoutMs` bounds the body download too (a\n * stalled CSV stream aborts, it does not hang forever). Both the JSON path\n * ({@link request}) and the text path ({@link requestText}) go through here.\n */\n private async send<T>(\n method: string,\n path: string,\n options: RequestOptions,\n read: (res: Response) => Promise<T>,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query)\n\n const token = await this.auth.getToken()\n // A `FormData` body is a multipart upload: let the runtime set\n // `Content-Type: multipart/form-data; boundary=…` itself (a manual JSON\n // content-type corrupts the boundary), and send the body as-is rather than\n // JSON-stringifying it. Every other body stays JSON, exactly as before.\n const isFormData =\n typeof FormData !== \"undefined\" && options.body instanceof FormData\n const headers: Record<string, string> = {\n ...(isFormData ? {} : { \"Content-Type\": \"application/json\" }),\n ...(this.sendClientHeader ? { [CLIENT_HEADER]: this.clientLabel } : {}),\n // Before per-request headers: a resource that needs to reach outside\n // this client's workspace says so explicitly and wins.\n ...(this.workspaceId ? { [WORKSPACE_HEADER]: this.workspaceId } : {}),\n ...(options.headers ?? {}),\n }\n if (token) headers[\"Authorization\"] = `Bearer ${token}`\n\n const ac = new AbortController()\n const timeoutId = setTimeout(() => ac.abort(), this.timeoutMs)\n const abort = () => ac.abort(options.signal?.reason)\n options.signal?.addEventListener(\"abort\", abort, { once: true })\n if (options.signal?.aborted) abort()\n\n try {\n ac.signal.throwIfAborted()\n const res = await this.fetch(url, {\n method,\n headers,\n body:\n options.body === undefined\n ? undefined\n : isFormData\n ? (options.body as FormData)\n : JSON.stringify(options.body),\n signal: ac.signal,\n })\n\n if (!res.ok) {\n let errBody: Record<string, unknown> = {}\n try {\n errBody = await res.json() as Record<string, unknown>\n } catch {\n // Empty/non-JSON body — fall through with empty errBody\n }\n throwFromResponse(res.status, errBody)\n }\n\n return await read(res)\n } finally {\n clearTimeout(timeoutId)\n options.signal?.removeEventListener(\"abort\", abort)\n }\n }\n\n /** Authenticated, bounded binary reads through the normal timeout/error transport. */\n async requestBytes(method: string, path: string, options: RequestOptions & { maxBytes: number }): Promise<ArrayBuffer> {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) throw new Error(\"maxBytes must be a positive integer\")\n return this.send(method, path, options, (response) => readBinaryResponse(response, options.maxBytes))\n }\n\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n return this.send(method, path, options, async (res) =>\n // 204 No Content\n res.status === 204 ? (undefined as T) : ((await res.json()) as T),\n )\n }\n\n /**\n * Like {@link request}, for endpoints that answer text (CSV exports). Errors\n * are still the JSON envelope and throw the same typed errors, and the read is\n * bounded by the same timeout as the request.\n */\n async requestText(method: string, path: string, options: RequestOptions = {}): Promise<string> {\n return this.send(method, path, options, (res) => res.text())\n }\n\n /**\n * `GET /v1/me` → the authenticated user's identity (see {@link UserIdentity}).\n * Unwraps the `{ data }` envelope. Throws `UnauthorizedError` (401) when the\n * token is missing/invalid, and the SDK's other typed errors as usual.\n *\n * On an instance with organizations it also carries what the caller belongs\n * to. THREE states, and collapsing them is wrong in a way users feel: the\n * organization fields ABSENT means this instance has no organizations at\n * all; present and empty means the account belongs to none; and\n * `organizationsUnavailable` means the lookup failed — keep whatever\n * selection you already had rather than concluding the person was removed\n * from everything.\n */\n async me(): Promise<UserIdentity & MeOrganizations> {\n const res = await this.request<{ data: UserIdentity & MeOrganizations }>(\"GET\", \"/v1/me\")\n return res.data\n }\n\n /**\n * `GET /v1/me/connected-apps` → every app with access to the signed-in\n * user's account (see {@link ConnectedApp}), newest grant first.\n *\n * **A signed-in browser session only.** The route answers a Supabase\n * session token (`supabaseAuth(…)`, `createSharedSupabaseClient`, or a\n * `StaticTokenAuth` holding one) and refuses every other credential with\n * `UnauthorizedError` (\"Sign in required\"): an app token or an API key must\n * not list the grants it lives under. Build your \"Connected apps\" settings\n * screen on this; a server-side integration cannot call it.\n */\n async connectedApps(): Promise<ConnectedApp[]> {\n const res = await this.request<{ apps: ConnectedApp[] }>(\"GET\", \"/v1/me/connected-apps\")\n return res.apps\n }\n\n /**\n * `POST /v1/me/connected-apps/:authorizationId/revoke` — ends an app's\n * access: the grant and every token issued under it, at once (the app's next\n * call is a 401). Resolves when done.\n *\n * A signed-in browser session only, like {@link connectedApps}. Throws\n * `NotFoundError` when the grant is not the user's or is already revoked.\n */\n async revokeConnectedApp(authorizationId: string): Promise<void> {\n await this.request(\"POST\", `/v1/me/connected-apps/${encodeURIComponent(authorizationId)}/revoke`)\n }\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n const base = this.baseUrl || (typeof window !== \"undefined\" ? window.location.origin : \"http://placeholder\")\n const url = new URL(path, base)\n // If baseUrl was empty, strip the placeholder origin\n const fullUrl = this.baseUrl ? url.toString() : url.pathname + url.search\n if (query) {\n const u = new URL(this.baseUrl ? fullUrl : fullUrl, base)\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) u.searchParams.set(k, String(v))\n }\n return this.baseUrl ? u.toString() : u.pathname + u.search\n }\n return fullUrl\n }\n}\n","/**\n * Auth provides the token used for `Authorization: Bearer <token>` on each request.\n * Implementations:\n * - StaticTokenAuth — fixed string (server-side, OAuth access token, API token)\n * - CallbackAuth — caller-supplied async function (BYO logic)\n * - supabaseAuth — pulls JWT from a Supabase client live (browser frontends)\n */\nexport interface Auth {\n /** Returns the current Bearer token, or null if not authenticated. */\n getToken(): Promise<string | null>\n}\n\nexport class StaticTokenAuth implements Auth {\n constructor(private token: string) {}\n async getToken() {\n return this.token\n }\n}\n\nexport class CallbackAuth implements Auth {\n constructor(private fn: () => string | null | Promise<string | null>) {}\n async getToken() {\n return this.fn()\n }\n}\n\ninterface SupabaseLikeClient {\n auth: {\n getSession(): Promise<{ data: { session: { access_token: string } | null } }>\n }\n}\n\n/** Pulls a JWT from a Supabase v2 client. Caller supplies their own supabase. */\nexport function supabaseAuth(supabase: SupabaseLikeClient): Auth {\n return {\n async getToken() {\n const { data } = await supabase.auth.getSession()\n return data.session?.access_token ?? null\n },\n }\n}\n"]}
@@ -21,5 +21,5 @@ var TemplatesResource = class {
21
21
  };
22
22
 
23
23
  export { TemplatesResource };
24
- //# sourceMappingURL=chunk-6OGGJQVA.js.map
25
- //# sourceMappingURL=chunk-6OGGJQVA.js.map
24
+ //# sourceMappingURL=chunk-ILG5DHQQ.js.map
25
+ //# sourceMappingURL=chunk-ILG5DHQQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/templates.ts"],"names":[],"mappings":";AA4GO,IAAM,oBAAN,MAAwB;AAAA,EAC7B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,MAAA,CAAO,MAAA,GAAgC,EAAC,EAAmC;AACzE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,sBAAA,EAAwB,EAAE,KAAA,EAAO,EAAE,GAAG,MAAA,EAAO,EAAG,CAAA;AAAA,EACpF;AAAA;AAAA,EAGA,IAAI,IAAA,EAAiC;AACnC,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,KAAA,EAAO,iBAAiB,kBAAA,CAAmB,IAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/E;AAAA;AAAA,EAGA,KAAA,CAAM,MAAc,MAAA,EAA2D;AAC7E,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,iBAAiB,kBAAA,CAAmB,IAAI,CAAC,CAAA,MAAA,CAAA,EAAU;AAAA,MACpF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACF","file":"chunk-ILG5DHQQ.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Workflow-template marketplace — the PUBLIC-BY-DESIGN surfaces only:\n * browse cards, a single template with its full snapshot, and the free\n * clone-into-my-project action. Creator/admin surfaces (publish, mine,\n * favorites, metadata patch, tutorial flags) are deliberately NOT part of\n * the public SDK contract; first-party apps reach them via\n * `client.request()`.\n */\n\n/** Card returned by the marketplace browse (no snapshot payload). */\nexport interface TemplateBrowseCard {\n id: string\n slug: string\n name: string\n description: string | null\n /** The listed price; when `estimatedPerMinuteCredits` is above 0, its fixed part. */\n estimatedCredits: number\n /** The listed price holds a metered LLM call's ESTIMATE (its model's typical\n * call, charged its actual usage per token): show it `~N`. Absent for a\n * fixed price, and on a deployment running the tier-pricing rollback. */\n estimatedCreditsIsEstimate?: true\n /**\n * Credits per minute of the recording the template is given, when its price\n * follows that recording's length (an Apply EDL render of a whole episode,\n * an Edit Plan pass): the price is `estimatedCredits` plus this per minute.\n * 0 or absent when the price does not depend on a recording's length.\n */\n estimatedPerMinuteCredits?: number\n /**\n * The listed price is a range: `estimatedCredits` / `estimatedPerMinuteCredits`\n * are \"from\" (the saved settings), these \"up to\" — the most a run can cost over\n * the template's exposed fields. Present only when they differ from \"from\".\n */\n maxEstimatedCredits?: number\n maxEstimatedPerMinuteCredits?: number\n category: string\n outputTypes: string[]\n tags: string[]\n nodeTypesUsed: string[]\n providersUsed: string[]\n nodeCount: number\n complexity: string\n previewMediaUrl: string | null\n previewMediaType: \"image\" | \"video\" | null\n creatorId: string\n creatorDisplayName: string | null\n cloneCount: number\n favoriteCount: number\n createdAt: string\n}\n\nexport type TemplateSort = \"newest\" | \"popular\" | \"most-favorited\"\n\nexport interface BrowseTemplatesParams {\n /** Opaque cursor from the previous page's `nextCursor`. */\n cursor?: string\n limit?: number\n category?: string\n outputType?: string\n tag?: string\n /** Full-text search over name/description/tags. */\n search?: string\n sort?: TemplateSort\n /** Only templates using this node type. */\n nodeType?: string\n /** Only templates using this provider/model id. */\n provider?: string\n complexity?: string\n}\n\nexport interface BrowseTemplatesResult {\n data: TemplateBrowseCard[]\n /** Pass back as `cursor` to fetch the next page; `null` on the last page. */\n nextCursor: string | null\n}\n\n/**\n * A single public template (`GET /v1/templates/:slug`) — the browse-card\n * fields plus the full workflow snapshot the viewer/clone consume. The route\n * returns the whole camelCased row, so additional columns may appear beyond\n * the ones typed here; the index signature keeps them reachable without\n * casting.\n */\nexport interface Template extends TemplateBrowseCard {\n markdownDescription: string | null\n /** React Flow node snapshots (generic node JSON, execution data stripped on clone). */\n snapshotNodes: unknown[]\n snapshotEdges: unknown[]\n snapshotSettings: Record<string, unknown>\n /** Channels the template is listed in (e.g. \"marketplace\", \"tutorial\"). */\n listedIn: string[]\n readonly [key: string]: unknown\n}\n\nexport interface CloneTemplateParams {\n /** Target project (must belong to the caller). */\n projectId: string\n /** Optional name for the cloned workflow; defaults to the template's name. */\n name?: string\n}\n\nexport interface CloneTemplateResult {\n workflowId: string\n projectId: string\n}\n\nexport class TemplatesResource {\n constructor(private client: NodaroClientCore) {}\n\n /** Browse the public template marketplace (cursor-paginated, no auth required). */\n browse(params: BrowseTemplatesParams = {}): Promise<BrowseTemplatesResult> {\n return this.client.request(\"GET\", \"/v1/templates/browse\", { query: { ...params } })\n }\n\n /** Fetch one public template by slug, including its full workflow snapshot. */\n get(slug: string): Promise<Template> {\n return this.client.request(\"GET\", `/v1/templates/${encodeURIComponent(slug)}`)\n }\n\n /** Clone a template into one of the caller's projects. Free — no credits charged. */\n clone(slug: string, params: CloneTemplateParams): Promise<CloneTemplateResult> {\n return this.client.request(\"POST\", `/v1/templates/${encodeURIComponent(slug)}/clone`, {\n body: params,\n })\n }\n}\n"]}
@@ -24,8 +24,18 @@ var UploadsResource = class {
24
24
  );
25
25
  return res.data;
26
26
  }
27
+ /**
28
+ * Store a JSON document (`POST /v1/upload-json`, up to 25 MB) and get its
29
+ * public URL — e.g. an image editor's design state, passed to
30
+ * `client.jobs.fromUpload` as `editStateUrl` so the edit can be reopened.
31
+ * The URL is unguessable but public: never store a secret in it. Creates no
32
+ * library item.
33
+ */
34
+ uploadJson(json) {
35
+ return this.client.request("POST", "/v1/upload-json", { body: json });
36
+ }
27
37
  };
28
38
 
29
39
  exports.UploadsResource = UploadsResource;
30
- //# sourceMappingURL=chunk-ZQQABQMH.cjs.map
31
- //# sourceMappingURL=chunk-ZQQABQMH.cjs.map
40
+ //# sourceMappingURL=chunk-JTOEHQQJ.cjs.map
41
+ //# sourceMappingURL=chunk-JTOEHQQJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/uploads.ts"],"names":[],"mappings":";;;AA4BO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUpB,MAAM,OAAO,IAAA,EAAmC;AAC9C,IAAA,MAAM,IAAA,GAAO,IAAI,QAAA,EAAS;AAC1B,IAAA,IAAA,CAAK,MAAA,CAAO,QAAQ,IAAI,CAAA;AACxB,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA;AAAA,MAC5B,MAAA;AAAA,MACA,YAAA;AAAA,MACA,EAAE,MAAM,IAAA;AAAK,KACf;AACA,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,WAAW,IAAA,EAA+E;AACxF,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAA0B,MAAA,EAAQ,mBAAmB,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,EACxF;AACF","file":"chunk-JTOEHQQJ.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Result of a successful `POST /v1/upload`. Mirrors the route's `data` envelope\n * (`backend/src/routes/upload.ts`), the source of truth — keep in sync if that\n * response changes. The route also returns loosely-typed extracted `metadata`;\n * it is omitted here until a consumer needs a typed shape (add it shaped to\n * that need rather than inventing `Record<string, unknown>` surface now).\n */\nexport interface UploadResult {\n /** Public R2 URL of the stored asset (always present on success). */\n readonly url: string\n /** Storage row id; `null` when no asset row was written (e.g. unauthenticated). */\n readonly assetId: string | null\n /** Generated thumbnail URL (images/video); `null` for audio or on failure. */\n readonly thumbnailUrl: string | null\n /** Server-classified asset category (e.g. \"image\" | \"video\" | \"audio\"). */\n readonly category: string\n /** Display filename (server override or the original). */\n readonly filename: string\n /** Final MIME type after server normalization. */\n readonly mimeType: string\n /** Stored byte size. */\n readonly sizeBytes: number\n /** R2 object key. */\n readonly r2Key: string\n}\n\nexport class UploadsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * Upload one file (`POST /v1/upload`, multipart — the file rides the `file`\n * field). The SDK's `request` detects the `FormData` body and lets the\n * runtime set the multipart boundary. Returns the persisted asset's public\n * URL + storage metadata (unwraps the `{ data }` envelope). Throws\n * `StorageExceededError` (413) over the storage cap and the SDK's other typed\n * errors on the usual statuses.\n */\n async upload(file: File): Promise<UploadResult> {\n const form = new FormData()\n form.append(\"file\", file)\n const res = await this.client.request<{ data: UploadResult }>(\n \"POST\",\n \"/v1/upload\",\n { body: form },\n )\n return res.data\n }\n\n /**\n * Store a JSON document (`POST /v1/upload-json`, up to 25 MB) and get its\n * public URL — e.g. an image editor's design state, passed to\n * `client.jobs.fromUpload` as `editStateUrl` so the edit can be reopened.\n * The URL is unguessable but public: never store a secret in it. Creates no\n * library item.\n */\n uploadJson(json: Record<string, unknown> | readonly unknown[]): Promise<UploadJsonResult> {\n return this.client.request<UploadJsonResult>(\"POST\", \"/v1/upload-json\", { body: json })\n }\n}\n\n/** Result of {@link UploadsResource.uploadJson}. */\nexport interface UploadJsonResult {\n /** Public URL of the stored JSON document. */\n readonly url: string\n}\n"]}
@@ -196,5 +196,5 @@ var WorkflowsResource = class {
196
196
  };
197
197
 
198
198
  export { WorkflowsResource };
199
- //# sourceMappingURL=chunk-ZXJQSFIA.js.map
200
- //# sourceMappingURL=chunk-ZXJQSFIA.js.map
199
+ //# sourceMappingURL=chunk-JUON5NXA.js.map
200
+ //# sourceMappingURL=chunk-JUON5NXA.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resources/workflows.ts"],"names":[],"mappings":";AAmQO,IAAM,gCAAN,MAAoC;AAAA,EACzC,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,KAAK,UAAA,EAAuD;AAC1D,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,KAAA;AAAA,MACA,CAAA,cAAA,EAAiB,kBAAA,CAAmB,UAAU,CAAC,CAAA,cAAA;AAAA,KACjD;AAAA,EACF;AAAA;AAAA,EAGA,GAAA,CACE,YACA,KAAA,EAC+D;AAC/D,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,MAAA;AAAA,MACA,CAA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AAA,EAAW,GAAG,YAAA,EAAa,GAAI,KAAA;AACvC,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,sBAAA,EAAwB;AAAA,MACzD,IAAA,EAAM,EAAE,SAAA,EAAW,aAAA,EAAe,YAAA;AAAa,KAChD,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,aAAA,CAAc,IAAY,UAAA,EAA6D;AACrF,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,OAAA,EAAS,iBAAiB,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC7E,IAAA,EAAM,EAAE,UAAA;AAAW,KACpB,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAA,CACE,IACA,MAAA,EAC0E;AAC1E,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,iBAAiB,kBAAA,CAAmB,EAAE,CAAC,CAAA,KAAA,CAAA,EAAS;AAAA,MACjF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAA,GAAoD;AAClD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,8BAA8B,CAAA;AAAA,EAClE;AACF","file":"chunk-ZXJQSFIA.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type {\n GenericNode,\n GenericEdge,\n} from \"@nodaro/shared/types\"\nimport type {\n WorkflowExport,\n WorkflowImportReport,\n} from \"@nodaro/shared/workflow\"\nimport type {\n WorkflowVisibility,\n CollaboratorRole,\n} from \"@nodaro/shared/organizations\"\n\n/**\n * Workflow metadata + (when fetched as a single record) full nodes/edges/settings.\n *\n * The list endpoint returns metadata only; `get`, `create`, and `update` return the\n * full record. `nodes`, `edges`, `settings`, and `sourcePrompt` are present only on\n * full records and omitted in list responses.\n */\nexport interface Workflow {\n id: string\n projectId: string | null\n userId: string\n name: string\n description?: string | null\n folderId?: string | null\n isTemplate?: boolean\n version?: number\n thumbnailUrl?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string | null\n createdAt: string\n updatedAt: string\n}\n\nexport interface ListWorkflowsParams {\n /** Required — list endpoint is `/v1/projects/:projectId/workflows`. */\n projectId: string\n}\n\nexport interface CreateWorkflowInput {\n /** Required — workflow is created under this project. */\n projectId: string\n name: string\n description?: string\n folderId?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string\n}\n\nexport interface UpdateWorkflowInput {\n name?: string\n description?: string\n folderId?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string\n thumbnailUrl?: string | null\n /**\n * Optimistic concurrency: the `updatedAt` your copy of the workflow was\n * loaded with. When the row has since been written by another tab/device,\n * the update is rejected with HTTP 409 `workflow_conflict`\n * (`WorkflowConflictError`) carrying the current record — re-read/merge and\n * retry instead of last-writer-wins clobbering the other writer's changes.\n * Omit for the legacy unconditional replace.\n */\n expectedUpdatedAt?: string\n /**\n * Optimistic concurrency by monotonic version — preferred over\n * `expectedUpdatedAt` (integer bumped by the DB on every content change).\n */\n expectedVersion?: number\n}\n\nexport interface RunWorkflowParams {\n /**\n * Optional subset of node IDs to execute. Omit to run the full workflow.\n * With `continueMode: \"from-failed\"`, the nodes to consider (default: the\n * nodes the run's chain was first started on, plus every node left failed or\n * held back; see `continueMode`); the run executes only those the failed run\n * did not complete. Every id sent counts as named: a node of work no run of\n * the chain ever ran (each only handed on its saved results) runs and is\n * priced, while a source, trigger, parameter picker or container keeps what\n * the run handed on and a node set to skip never runs.\n */\n nodeIds?: string[]\n /**\n * Per-node field overrides for this run only, `{ [nodeId]: { field: value } }`,\n * shallow-merged over each node's saved data (the node's saved results are\n * not used). A run through the API has nobody to review a Preview render, so\n * a workflow whose Apply EDL render is set to Preview is refused\n * (`preview_review_required`) unless the run sets it to Final:\n * `{ [renderNodeId]: { quality: \"final\" } }`. A node with Review before\n * render on (Tighten Episode, Trailer) is refused the same way (turn its\n * review off). A failed execution records what held it —\n * `preview_review_required` / `preview_render_nested` (a render),\n * `…_review_on` (a review-on node) or `…_mixed` (both); match all six with\n * `isPreviewRefusalCode` from `@nodaro/shared`. A review-on Tighten Episode\n * fed by a List is refused with `use_case_review_list_driven`; a Trailer fed\n * by a List, with `use_case_list_driven`.\n */\n inputOverrides?: Record<string, Record<string, unknown>>\n /**\n * Continue from an earlier execution of this workflow — Render final after a\n * run that stopped at its preview, or (with `continueMode: \"from-failed\"`) a\n * failed run from where it stopped. The run executes `nodeIds` only\n * (required with this field, except with `continueMode`); every other node\n * hands on what that execution produced, not the workflow's saved results,\n * and an Edit Plan hands on its plan with the person's review applied. The\n * execution must be your own `completed` run of this workflow (`failed`,\n * with `continueMode`), not of a published app version. Refused with\n * `continuation_subset_required`, `continuation_not_found` (404),\n * `continuation_workflow_mismatch`, `continuation_version_mismatch` or\n * `continuation_not_completed` (409). A continuation its payer cannot cover\n * (with or without `continueMode`, priced on the nodes it runs) throws\n * `InsufficientCreditsError` before any execution exists, checked as a\n * {@link WorkflowsResource.renderFinal} is.\n */\n continueFromExecutionId?: string\n /**\n * `\"from-failed\"`: continue a FAILED run (`continueFromExecutionId`) from\n * where it stopped. It runs every node that run did not complete — of\n * `nodeIds`, which default to the nodes the run was started on (a run\n * started on named nodes is continued on those, a run of every node on every\n * node; a continuation of a continuation keeps those of the first run of its\n * chain) plus every node the run left failed or held back — and hands on\n * what it completed,\n * never run or charged again. That is per node: a node that failed runs\n * again in full, every list item included. When a later continuation of it\n * completed only part of what it left (a narrower `nodeIds`), the run builds\n * on the newest such one: it is seeded from that run and runs only what is\n * still left ({@link RunWorkflowResult.continuedFrom} names it). A node\n * `nodeIds` names that no run of the chain ever ran runs too, and is priced\n * (see `nodeIds`). A Render\n * final, or a run of named nodes, continuing the newest of those counts as\n * one of them too. Not combinable with {@link renderFinal}. Refused with\n * `continuation_not_failed` (409) for a run that did not fail,\n * `continuation_superseded` (409) when a later continuation supersedes it —\n * the message names that run: one that failed (continue that one instead),\n * or one that completed all this run left (the work is done, and its results\n * are on that run) — `continuation_preview_pending` (409, a\n * `ContinuationPreviewPendingError`) when the newest later continuation\n * stopped at a Preview review of a render or of a Tighten Episode (the error\n * names that run, what holds it, and in `next` the run that finishes it:\n * `client.workflows.run(workflowId, error.next)` first — for a single render,\n * its {@link renderFinal}), and\n * `continuation_subset_required` (409) when nothing is left to run. Send an\n * {@link RunWorkflowOptions.idempotencyKey} with each continuation.\n */\n continueMode?: \"from-failed\"\n}\n\n/** Per-call options for {@link WorkflowsResource.run}. */\nexport interface RunWorkflowOptions {\n /**\n * Sent as the `Idempotency-Key` header (at least 8 characters; the server\n * ignores a shorter one). Reuse the same value when retrying the same\n * request: the server answers the run it already started (`deduped: true`)\n * instead of starting a second one — or, once that run is under way or has\n * superseded the one it continued, refuses with `already_running` (an\n * `AlreadyRunningError` carrying its `executionId`) or\n * `continuation_superseded` naming it. Either way nothing runs twice.\n */\n idempotencyKey?: string\n}\n\nexport interface RunWorkflowResult {\n executionId: string\n status: \"pending\" | \"running\"\n /** `true` when an `idempotencyKey` retry found the run already started: `executionId` is that run. */\n deduped?: boolean\n /**\n * With `continueMode: \"from-failed\"`: the execution the run continued from —\n * its states seed the run. The run asked for (`continueFromExecutionId`), or\n * the newest later continuation of it that completed part of what it left.\n * Absent on any other run, and on a `deduped` answer.\n */\n continuedFrom?: string\n}\n\n/**\n * A Render final: the Apply EDL render at Final for this run only, and every\n * node after it (Camera Switch first, in multicam). The server works out which\n * nodes run — the same rule as the editor's Render final button.\n */\nexport interface RenderFinalParams {\n /** The Apply EDL render node to finalize. */\n renderNodeId: string\n /**\n * The execution that stopped at the preview: your own `completed` run of\n * this workflow. Every node the Render final does not run hands on what it\n * produced (an Edit Plan hands on its plan with the review applied).\n */\n continueFromExecutionId: string\n}\n\n/** What a Render final will run and charge. Nothing is created by the quote. */\nexport interface RenderFinalQuote {\n renderNodeId: string\n /** The nodes the run executes, in canvas order. */\n nodeIds: string[]\n /** The one-shot override it runs with: `{ [renderNodeId]: { quality: \"final\" } }`. */\n inputOverrides: Record<string, Record<string, unknown>>\n /** Estimated credits; `null` in an edition without credits. */\n estimatedCredits: number | null\n /**\n * Whether the payer can cover `estimatedCredits`; `null` in an edition\n * without credits. When `false`, {@link WorkflowsResource.renderFinal} is\n * refused with `InsufficientCreditsError` before any execution exists.\n */\n sufficient: boolean | null\n /**\n * The payer's spendable credits; `null` when it is not yours to see (a\n * deployment's operator pays) or a workspace budget pays.\n */\n available: number | null\n}\n\n/** A person granted access to a workflow. Email is never returned (privacy). */\nexport interface Collaborator {\n userId: string\n name?: string | null\n avatar?: string | null\n role: CollaboratorRole\n}\n\nexport interface AddCollaboratorInput {\n /** Provide exactly one of `userId` or `email`. */\n userId?: string\n email?: string\n role: CollaboratorRole\n}\n\n/** A workflow someone else shared with you, plus the role you hold on it. */\nexport interface SharedWorkflow extends Workflow {\n grantedRole: CollaboratorRole\n}\n\n/** A grant dropped because a move took the workflow out of the workspace the\n * access came from. */\nexport interface DroppedCollaborator {\n userId: string\n name: string | null\n}\n\n/**\n * The people a workflow is shared with — reached as `client.workflows.collaborators`.\n * All four endpoints are served by the organizations feature and exist only when\n * it is enabled server-side; against an install without it they 404\n * (→ `NotFoundError`). The active workspace travels on the request like every\n * other call, so a workspace admin's grants apply automatically.\n */\nexport class WorkflowCollaboratorsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** List a workflow's collaborators (id, name, avatar, role — never email). */\n list(workflowId: string): Promise<{ data: Collaborator[] }> {\n return this.client.request(\n \"GET\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators`,\n )\n }\n\n /** Add a collaborator by `userId` OR `email` (exactly one), at the given role. */\n add(\n workflowId: string,\n input: AddCollaboratorInput,\n ): Promise<{ data: { userId: string; role: CollaboratorRole } }> {\n return this.client.request(\n \"POST\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators`,\n { body: input },\n )\n }\n\n /** Change a collaborator's role. */\n update(\n workflowId: string,\n userId: string,\n input: { role: CollaboratorRole },\n ): Promise<{ data: { userId: string; role: CollaboratorRole } }> {\n return this.client.request(\n \"PATCH\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators/${encodeURIComponent(userId)}`,\n { body: input },\n )\n }\n\n /** Remove a collaborator — or yourself. Returns `{ success: true }`. */\n remove(workflowId: string, userId: string): Promise<{ success: true }> {\n return this.client.request(\n \"DELETE\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators/${encodeURIComponent(userId)}`,\n )\n }\n}\n\nexport class WorkflowsResource {\n /** The people this workflow is shared with. See {@link WorkflowCollaboratorsResource}. */\n readonly collaborators: WorkflowCollaboratorsResource\n\n constructor(private client: NodaroClientCore) {\n this.collaborators = new WorkflowCollaboratorsResource(client)\n }\n\n /** List workflows for a project. Returns metadata only — `nodes`/`edges` are not included. */\n list(params: ListWorkflowsParams): Promise<{ data: Workflow[] }> {\n return this.client.request(\n \"GET\",\n `/v1/projects/${encodeURIComponent(params.projectId)}/workflows`,\n )\n }\n\n /** Get a workflow including its full nodes/edges/settings. */\n get(id: string): Promise<{ data: Workflow }> {\n return this.client.request(\"GET\", `/v1/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Get a PUBLICLY-SHARED workflow by id (`GET /v1/public/workflows/:id`) — the\n * unauthenticated share-by-link read. Returns the workflow's nodes/edges/\n * settings ONLY when it's opted into sharing server-side (`settings.studio.shared\n * === true`); otherwise the route 404s (→ `NotFoundError`). No auth required —\n * a share viewer has no session; the SDK omits the bearer when no token exists.\n */\n getPublic(id: string): Promise<{ data: Workflow }> {\n return this.client.request(\"GET\", `/v1/public/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Create a workflow under a project. Returns the full record.\n * NOTE: server route is `POST /v1/projects/:projectId/workflows`.\n */\n create(input: CreateWorkflowInput): Promise<{ data: Workflow }> {\n const { projectId, ...body } = input\n return this.client.request(\n \"POST\",\n `/v1/projects/${encodeURIComponent(projectId)}/workflows`,\n { body },\n )\n }\n\n /** Patch a workflow. Returns the full updated record. */\n update(id: string, input: UpdateWorkflowInput): Promise<{ data: Workflow }> {\n return this.client.request(\n \"PATCH\",\n `/v1/workflows/${encodeURIComponent(id)}`,\n { body: input },\n )\n }\n\n /** Delete a workflow. Returns `{ success: true }`. Throws `NotFoundError`\n * when the id doesn't exist or isn't yours (the delete is not silent). */\n delete(id: string): Promise<{ success: true }> {\n return this.client.request(\"DELETE\", `/v1/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Run a workflow. Returns the executionId for polling via\n * `client.executions.get(executionId)`.\n */\n run(id: string, params: RunWorkflowParams = {}, options?: RunWorkflowOptions): Promise<RunWorkflowResult> {\n return this.client.request(\n \"POST\",\n `/v1/workflows/${encodeURIComponent(id)}/run`,\n {\n body: params,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n },\n )\n }\n\n /**\n * Render final (`renderFinal` on `POST /v1/workflows/:id/run`): run the\n * render at Final for this run only, and every node after it, continuing the\n * execution that stopped at its preview. The server derives the nodes and\n * the override — send nothing else. Quote it first with\n * {@link estimateRenderFinal}. Refused with `render_final_node_not_found`,\n * `render_final_not_a_render`, or a continuation code (see `run`); a run\n * its payer cannot cover throws `InsufficientCreditsError` (with `required`\n * and, when it is yours to see, `available`) before any execution exists.\n */\n renderFinal(id: string, params: RenderFinalParams): Promise<RunWorkflowResult> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/run`, {\n body: {\n renderFinal: { renderNodeId: params.renderNodeId },\n continueFromExecutionId: params.continueFromExecutionId,\n },\n })\n }\n\n /**\n * Quote a Render final (`POST /v1/workflows/:id/render-final/estimate`): the\n * nodes it will run, the override it runs with and its estimated credits.\n * Nothing is created or charged.\n */\n estimateRenderFinal(id: string, params: RenderFinalParams): Promise<{ data: RenderFinalQuote }> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/render-final/estimate`, {\n body: { renderNodeId: params.renderNodeId, continueFromExecutionId: params.continueFromExecutionId },\n })\n }\n\n /**\n * Export a workflow as a portable JSON bundle.\n * Pass `opts.assets = true` to include character/object/location entity data.\n */\n export(\n workflowId: string,\n opts?: { assets?: boolean },\n ): Promise<{ data: WorkflowExport }> {\n return this.client.request(\n \"GET\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/export`,\n { query: { assets: opts?.assets ?? false } },\n )\n }\n\n /**\n * Import a `WorkflowExport` bundle into the specified project.\n * Re-creates any bundled assets (characters, objects, creatures, locations)\n * under your account, and re-points BOTH the entity nodes and every `@`-chip\n * (`ConnectedReference`) bound in the graph at the rows it created.\n * Media the bundle references on other hosts is copied onto this instance's\n * storage where reachable; a bundled entity's images are copied whoever\n * hosts them, because they are the exporter's bytes and their lifecycle is\n * not yours. `importReport` says what was copied, what could not be reached\n * and what was skipped (and why); `assetIdMap` maps each bundled entity id\n * to the row created for it (for chips you hold outside the graph), and\n * `assetsSkipped` names the entities your storage quota left uncreated —\n * the workflow itself still lands.\n */\n import(input: WorkflowExport & { projectId: string }): Promise<{ data: Workflow; importReport?: WorkflowImportReport }> {\n const { projectId, ...workflowJson } = input\n return this.client.request(\"POST\", \"/v1/workflows/import\", {\n body: { projectId, workflow_json: workflowJson },\n })\n }\n\n /**\n * Set a workflow's visibility — `\"private\"` (creator + explicit collaborators)\n * or `\"workspace\"` (everyone in its workspace). Only the creator or a workspace\n * admin may change it; anyone else gets HTTP 403. Thin wrapper over `update()`:\n * the visibility lever lives on `PATCH /v1/workflows/:id`.\n */\n setVisibility(id: string, visibility: WorkflowVisibility): Promise<{ data: Workflow }> {\n return this.client.request(\"PATCH\", `/v1/workflows/${encodeURIComponent(id)}`, {\n body: { visibility },\n })\n }\n\n /**\n * Move a workflow to another project (`POST /v1/workflows/:id/move`); its folder\n * is cleared. When the move takes the workflow out of a workspace, collaborator\n * grants that came from that workspace are dropped and returned as\n * `droppedCollaborators`.\n */\n move(\n id: string,\n params: { projectId: string },\n ): Promise<{ data: Workflow; droppedCollaborators: DroppedCollaborator[] }> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/move`, {\n body: params,\n })\n }\n\n /**\n * Workflows other people shared with you (`GET /v1/workflows/shared-with-me`) —\n * grants on work that is NOT in a workspace you belong to (workspace work already\n * shows in that workspace's own lists). Each carries the `grantedRole` you hold.\n * Empty when the organizations feature is off server-side.\n */\n sharedWithMe(): Promise<{ data: SharedWorkflow[] }> {\n return this.client.request(\"GET\", \"/v1/workflows/shared-with-me\")\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/resources/workflows.ts"],"names":[],"mappings":";AAyQO,IAAM,gCAAN,MAAoC;AAAA,EACzC,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,KAAK,UAAA,EAAuD;AAC1D,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,KAAA;AAAA,MACA,CAAA,cAAA,EAAiB,kBAAA,CAAmB,UAAU,CAAC,CAAA,cAAA;AAAA,KACjD;AAAA,EACF;AAAA;AAAA,EAGA,GAAA,CACE,YACA,KAAA,EAC+D;AAC/D,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,MAAA;AAAA,MACA,CAAA,cAAA,EAAiB,kBAAA,CAAmB,UAAU,CAAC,CAAA,cAAA,CAAA;AAAA,MAC/C,EAAE,MAAM,KAAA;AAAM,KAChB;AAAA,EACF;AAAA;AAAA,EAGA,MAAA,CACE,UAAA,EACA,MAAA,EACA,KAAA,EAC+D;AAC/D,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACj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AAAA;AAAA;AAAA;AAAA,EAQA,aAAA,CAAc,IAAY,UAAA,EAA6D;AACrF,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,OAAA,EAAS,iBAAiB,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC7E,IAAA,EAAM,EAAE,UAAA;AAAW,KACpB,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAA,CACE,IACA,MAAA,EAC0E;AAC1E,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,iBAAiB,kBAAA,CAAmB,EAAE,CAAC,CAAA,KAAA,CAAA,EAAS;AAAA,MACjF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAA,GAAoD;AAClD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,8BAA8B,CAAA;AAAA,EAClE;AACF","file":"chunk-JUON5NXA.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type {\n GenericNode,\n GenericEdge,\n} from \"@nodaro/shared/types\"\nimport type {\n WorkflowExport,\n WorkflowImportReport,\n} from \"@nodaro/shared/workflow\"\nimport type {\n WorkflowVisibility,\n CollaboratorRole,\n} from \"@nodaro/shared/organizations\"\n\n/**\n * Workflow metadata + (when fetched as a single record) full nodes/edges/settings.\n *\n * The list endpoint returns metadata only; `get`, `create`, and `update` return the\n * full record. `nodes`, `edges`, `settings`, and `sourcePrompt` are present only on\n * full records and omitted in list responses.\n */\nexport interface Workflow {\n id: string\n projectId: string | null\n userId: string\n name: string\n description?: string | null\n folderId?: string | null\n isTemplate?: boolean\n version?: number\n thumbnailUrl?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string | null\n createdAt: string\n updatedAt: string\n}\n\nexport interface ListWorkflowsParams {\n /** Required — list endpoint is `/v1/projects/:projectId/workflows`. */\n projectId: string\n}\n\nexport interface CreateWorkflowInput {\n /** Required — workflow is created under this project. */\n projectId: string\n name: string\n description?: string\n folderId?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string\n}\n\nexport interface UpdateWorkflowInput {\n name?: string\n description?: string\n folderId?: string | null\n nodes?: GenericNode[]\n edges?: GenericEdge[]\n settings?: Record<string, unknown>\n sourcePrompt?: string\n thumbnailUrl?: string | null\n /**\n * Optimistic concurrency: the `updatedAt` your copy of the workflow was\n * loaded with. When the row has since been written by another tab/device,\n * the update is rejected with HTTP 409 `workflow_conflict`\n * (`WorkflowConflictError`) carrying the current record — re-read/merge and\n * retry instead of last-writer-wins clobbering the other writer's changes.\n * Omit for the legacy unconditional replace.\n */\n expectedUpdatedAt?: string\n /**\n * Optimistic concurrency by monotonic version — preferred over\n * `expectedUpdatedAt` (integer bumped by the DB on every content change).\n */\n expectedVersion?: number\n}\n\nexport interface RunWorkflowParams {\n /**\n * Optional subset of node IDs to execute. Omit to run the full workflow.\n * With `continueMode: \"from-failed\"`, the nodes to consider (default: the\n * nodes the run's chain was first started on, plus every node left failed or\n * held back; see `continueMode`); the run executes only those the failed run\n * did not complete. Every id sent counts as named: a node of work no run of\n * the chain ever ran (each only handed on its saved results) runs and is\n * priced, while a source, trigger, parameter picker or container keeps what\n * the run handed on and a node set to skip never runs.\n */\n nodeIds?: string[]\n /**\n * Per-node field overrides for this run only, `{ [nodeId]: { field: value } }`,\n * shallow-merged over each node's saved data (the node's saved results are\n * not used). A run through the API has nobody to review a Preview render, so\n * a workflow whose Apply EDL render is set to Preview is refused\n * (`preview_review_required`) unless the run sets it to Final:\n * `{ [renderNodeId]: { quality: \"final\" } }`. A node with Review before\n * render on (Tighten Episode, Trailer) is refused the same way (turn its\n * review off). A failed execution records what held it —\n * `preview_review_required` / `preview_render_nested` (a render),\n * `…_review_on` (a review-on node) or `…_mixed` (both); match all six with\n * `isPreviewRefusalCode` from `@nodaro/shared`. A review-on Tighten Episode\n * fed by a List is refused with `use_case_review_list_driven`; a Trailer fed\n * by a List, with `use_case_list_driven`.\n */\n inputOverrides?: Record<string, Record<string, unknown>>\n /**\n * Continue from an earlier execution of this workflow — Render final after a\n * run that stopped at its preview, or (with `continueMode: \"from-failed\"`) a\n * failed run from where it stopped. The run executes `nodeIds` only\n * (required with this field, except with `continueMode`); every other node\n * hands on what that execution produced, not the workflow's saved results,\n * and an Edit Plan hands on its plan with the person's review applied. The\n * execution must be your own `completed` run of this workflow (`failed`,\n * with `continueMode`), not of a published app version. Refused with\n * `continuation_subset_required`, `continuation_not_found` (404),\n * `continuation_workflow_mismatch`, `continuation_version_mismatch` or\n * `continuation_not_completed` (409). A continuation its payer cannot cover\n * (with or without `continueMode`, priced on the nodes it runs) throws\n * `InsufficientCreditsError` before any execution exists, checked as a\n * {@link WorkflowsResource.renderFinal} is.\n */\n continueFromExecutionId?: string\n /**\n * `\"from-failed\"`: continue a FAILED run (`continueFromExecutionId`) from\n * where it stopped. It runs every node that run did not complete — of\n * `nodeIds`, which default to the nodes the run was started on (a run\n * started on named nodes is continued on those, a run of every node on every\n * node; a continuation of a continuation keeps those of the first run of its\n * chain) plus every node the run left failed or held back — and hands on\n * what it completed,\n * never run or charged again. That is per node: a node that failed runs\n * again in full, every list item included. When a later continuation of it\n * completed only part of what it left (a narrower `nodeIds`), the run builds\n * on the newest such one: it is seeded from that run and runs only what is\n * still left ({@link RunWorkflowResult.continuedFrom} names it). A node\n * `nodeIds` names that no run of the chain ever ran runs too, and is priced\n * (see `nodeIds`). A Render\n * final, or a run of named nodes, continuing the newest of those counts as\n * one of them too. Not combinable with {@link renderFinal}. Refused with\n * `continuation_not_failed` (409) for a run that did not fail,\n * `continuation_superseded` (409) when a later continuation supersedes it —\n * the message names that run: one that failed (continue that one instead),\n * or one that completed all this run left (the work is done, and its results\n * are on that run) — `continuation_preview_pending` (409, a\n * `ContinuationPreviewPendingError`) when the newest later continuation\n * stopped at a Preview review of a render or of a Tighten Episode (the error\n * names that run, what holds it, and in `next` the run that finishes it:\n * `client.workflows.run(workflowId, error.next)` first — for a single render,\n * its {@link renderFinal}), and\n * `continuation_subset_required` (409) when nothing is left to run. Send an\n * {@link RunWorkflowOptions.idempotencyKey} with each continuation.\n */\n continueMode?: \"from-failed\"\n}\n\n/** Per-call options for {@link WorkflowsResource.run}. */\nexport interface RunWorkflowOptions {\n /**\n * Sent as the `Idempotency-Key` header (at least 8 characters; the server\n * ignores a shorter one). Reuse the same value when retrying the same\n * request: the server answers the run it already started (`deduped: true`)\n * instead of starting a second one — or, once that run is under way or has\n * superseded the one it continued, refuses with `already_running` (an\n * `AlreadyRunningError` carrying its `executionId`) or\n * `continuation_superseded` naming it. Either way nothing runs twice.\n */\n idempotencyKey?: string\n}\n\nexport interface RunWorkflowResult {\n executionId: string\n status: \"pending\" | \"running\"\n /** `true` when an `idempotencyKey` retry found the run already started: `executionId` is that run. */\n deduped?: boolean\n /**\n * With `continueMode: \"from-failed\"`: the execution the run continued from —\n * its states seed the run. The run asked for (`continueFromExecutionId`), or\n * the newest later continuation of it that completed part of what it left.\n * Absent on any other run, and on a `deduped` answer.\n */\n continuedFrom?: string\n}\n\n/**\n * A Render final: the Apply EDL render at Final for this run only, and every\n * node after it (Camera Switch first, in multicam). The server works out which\n * nodes run — the same rule as the editor's Render final button.\n */\nexport interface RenderFinalParams {\n /** The Apply EDL render node to finalize. */\n renderNodeId: string\n /**\n * The execution that stopped at the preview: your own `completed` run of\n * this workflow. Every node the Render final does not run hands on what it\n * produced (an Edit Plan hands on its plan with the review applied).\n */\n continueFromExecutionId: string\n}\n\n/** What a Render final will run and charge. Nothing is created by the quote. */\nexport interface RenderFinalQuote {\n renderNodeId: string\n /** The nodes the run executes, in canvas order. */\n nodeIds: string[]\n /** The one-shot override it runs with: `{ [renderNodeId]: { quality: \"final\" } }`. */\n inputOverrides: Record<string, Record<string, unknown>>\n /** Estimated credits; `null` in an edition without credits. */\n estimatedCredits: number | null\n /**\n * Present (`true`) when `estimatedCredits` includes an LLM node's estimate:\n * an LLM call is charged its actual usage after it runs, so show `~N`.\n * Absent for a fixed price.\n */\n estimatedCreditsIsEstimate?: true\n /**\n * Whether the payer can cover `estimatedCredits`; `null` in an edition\n * without credits. When `false`, {@link WorkflowsResource.renderFinal} is\n * refused with `InsufficientCreditsError` before any execution exists.\n */\n sufficient: boolean | null\n /**\n * The payer's spendable credits; `null` when it is not yours to see (a\n * deployment's operator pays) or a workspace budget pays.\n */\n available: number | null\n}\n\n/** A person granted access to a workflow. Email is never returned (privacy). */\nexport interface Collaborator {\n userId: string\n name?: string | null\n avatar?: string | null\n role: CollaboratorRole\n}\n\nexport interface AddCollaboratorInput {\n /** Provide exactly one of `userId` or `email`. */\n userId?: string\n email?: string\n role: CollaboratorRole\n}\n\n/** A workflow someone else shared with you, plus the role you hold on it. */\nexport interface SharedWorkflow extends Workflow {\n grantedRole: CollaboratorRole\n}\n\n/** A grant dropped because a move took the workflow out of the workspace the\n * access came from. */\nexport interface DroppedCollaborator {\n userId: string\n name: string | null\n}\n\n/**\n * The people a workflow is shared with — reached as `client.workflows.collaborators`.\n * All four endpoints are served by the organizations feature and exist only when\n * it is enabled server-side; against an install without it they 404\n * (→ `NotFoundError`). The active workspace travels on the request like every\n * other call, so a workspace admin's grants apply automatically.\n */\nexport class WorkflowCollaboratorsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** List a workflow's collaborators (id, name, avatar, role — never email). */\n list(workflowId: string): Promise<{ data: Collaborator[] }> {\n return this.client.request(\n \"GET\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators`,\n )\n }\n\n /** Add a collaborator by `userId` OR `email` (exactly one), at the given role. */\n add(\n workflowId: string,\n input: AddCollaboratorInput,\n ): Promise<{ data: { userId: string; role: CollaboratorRole } }> {\n return this.client.request(\n \"POST\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators`,\n { body: input },\n )\n }\n\n /** Change a collaborator's role. */\n update(\n workflowId: string,\n userId: string,\n input: { role: CollaboratorRole },\n ): Promise<{ data: { userId: string; role: CollaboratorRole } }> {\n return this.client.request(\n \"PATCH\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators/${encodeURIComponent(userId)}`,\n { body: input },\n )\n }\n\n /** Remove a collaborator — or yourself. Returns `{ success: true }`. */\n remove(workflowId: string, userId: string): Promise<{ success: true }> {\n return this.client.request(\n \"DELETE\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/collaborators/${encodeURIComponent(userId)}`,\n )\n }\n}\n\nexport class WorkflowsResource {\n /** The people this workflow is shared with. See {@link WorkflowCollaboratorsResource}. */\n readonly collaborators: WorkflowCollaboratorsResource\n\n constructor(private client: NodaroClientCore) {\n this.collaborators = new WorkflowCollaboratorsResource(client)\n }\n\n /** List workflows for a project. Returns metadata only — `nodes`/`edges` are not included. */\n list(params: ListWorkflowsParams): Promise<{ data: Workflow[] }> {\n return this.client.request(\n \"GET\",\n `/v1/projects/${encodeURIComponent(params.projectId)}/workflows`,\n )\n }\n\n /** Get a workflow including its full nodes/edges/settings. */\n get(id: string): Promise<{ data: Workflow }> {\n return this.client.request(\"GET\", `/v1/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Get a PUBLICLY-SHARED workflow by id (`GET /v1/public/workflows/:id`) — the\n * unauthenticated share-by-link read. Returns the workflow's nodes/edges/\n * settings ONLY when it's opted into sharing server-side (`settings.studio.shared\n * === true`); otherwise the route 404s (→ `NotFoundError`). No auth required —\n * a share viewer has no session; the SDK omits the bearer when no token exists.\n */\n getPublic(id: string): Promise<{ data: Workflow }> {\n return this.client.request(\"GET\", `/v1/public/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Create a workflow under a project. Returns the full record.\n * NOTE: server route is `POST /v1/projects/:projectId/workflows`.\n */\n create(input: CreateWorkflowInput): Promise<{ data: Workflow }> {\n const { projectId, ...body } = input\n return this.client.request(\n \"POST\",\n `/v1/projects/${encodeURIComponent(projectId)}/workflows`,\n { body },\n )\n }\n\n /** Patch a workflow. Returns the full updated record. */\n update(id: string, input: UpdateWorkflowInput): Promise<{ data: Workflow }> {\n return this.client.request(\n \"PATCH\",\n `/v1/workflows/${encodeURIComponent(id)}`,\n { body: input },\n )\n }\n\n /** Delete a workflow. Returns `{ success: true }`. Throws `NotFoundError`\n * when the id doesn't exist or isn't yours (the delete is not silent). */\n delete(id: string): Promise<{ success: true }> {\n return this.client.request(\"DELETE\", `/v1/workflows/${encodeURIComponent(id)}`)\n }\n\n /**\n * Run a workflow. Returns the executionId for polling via\n * `client.executions.get(executionId)`.\n */\n run(id: string, params: RunWorkflowParams = {}, options?: RunWorkflowOptions): Promise<RunWorkflowResult> {\n return this.client.request(\n \"POST\",\n `/v1/workflows/${encodeURIComponent(id)}/run`,\n {\n body: params,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n },\n )\n }\n\n /**\n * Render final (`renderFinal` on `POST /v1/workflows/:id/run`): run the\n * render at Final for this run only, and every node after it, continuing the\n * execution that stopped at its preview. The server derives the nodes and\n * the override — send nothing else. Quote it first with\n * {@link estimateRenderFinal}. Refused with `render_final_node_not_found`,\n * `render_final_not_a_render`, or a continuation code (see `run`); a run\n * its payer cannot cover throws `InsufficientCreditsError` (with `required`\n * and, when it is yours to see, `available`) before any execution exists.\n */\n renderFinal(id: string, params: RenderFinalParams): Promise<RunWorkflowResult> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/run`, {\n body: {\n renderFinal: { renderNodeId: params.renderNodeId },\n continueFromExecutionId: params.continueFromExecutionId,\n },\n })\n }\n\n /**\n * Quote a Render final (`POST /v1/workflows/:id/render-final/estimate`): the\n * nodes it will run, the override it runs with and its estimated credits.\n * Nothing is created or charged.\n */\n estimateRenderFinal(id: string, params: RenderFinalParams): Promise<{ data: RenderFinalQuote }> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/render-final/estimate`, {\n body: { renderNodeId: params.renderNodeId, continueFromExecutionId: params.continueFromExecutionId },\n })\n }\n\n /**\n * Export a workflow as a portable JSON bundle.\n * Pass `opts.assets = true` to include character/object/location entity data.\n */\n export(\n workflowId: string,\n opts?: { assets?: boolean },\n ): Promise<{ data: WorkflowExport }> {\n return this.client.request(\n \"GET\",\n `/v1/workflows/${encodeURIComponent(workflowId)}/export`,\n { query: { assets: opts?.assets ?? false } },\n )\n }\n\n /**\n * Import a `WorkflowExport` bundle into the specified project.\n * Re-creates any bundled assets (characters, objects, creatures, locations)\n * under your account, and re-points BOTH the entity nodes and every `@`-chip\n * (`ConnectedReference`) bound in the graph at the rows it created.\n * Media the bundle references on other hosts is copied onto this instance's\n * storage where reachable; a bundled entity's images are copied whoever\n * hosts them, because they are the exporter's bytes and their lifecycle is\n * not yours. `importReport` says what was copied, what could not be reached\n * and what was skipped (and why); `assetIdMap` maps each bundled entity id\n * to the row created for it (for chips you hold outside the graph), and\n * `assetsSkipped` names the entities your storage quota left uncreated —\n * the workflow itself still lands.\n */\n import(input: WorkflowExport & { projectId: string }): Promise<{ data: Workflow; importReport?: WorkflowImportReport }> {\n const { projectId, ...workflowJson } = input\n return this.client.request(\"POST\", \"/v1/workflows/import\", {\n body: { projectId, workflow_json: workflowJson },\n })\n }\n\n /**\n * Set a workflow's visibility — `\"private\"` (creator + explicit collaborators)\n * or `\"workspace\"` (everyone in its workspace). Only the creator or a workspace\n * admin may change it; anyone else gets HTTP 403. Thin wrapper over `update()`:\n * the visibility lever lives on `PATCH /v1/workflows/:id`.\n */\n setVisibility(id: string, visibility: WorkflowVisibility): Promise<{ data: Workflow }> {\n return this.client.request(\"PATCH\", `/v1/workflows/${encodeURIComponent(id)}`, {\n body: { visibility },\n })\n }\n\n /**\n * Move a workflow to another project (`POST /v1/workflows/:id/move`); its folder\n * is cleared. When the move takes the workflow out of a workspace, collaborator\n * grants that came from that workspace are dropped and returned as\n * `droppedCollaborators`.\n */\n move(\n id: string,\n params: { projectId: string },\n ): Promise<{ data: Workflow; droppedCollaborators: DroppedCollaborator[] }> {\n return this.client.request(\"POST\", `/v1/workflows/${encodeURIComponent(id)}/move`, {\n body: params,\n })\n }\n\n /**\n * Workflows other people shared with you (`GET /v1/workflows/shared-with-me`) —\n * grants on work that is NOT in a workspace you belong to (workspace work already\n * shows in that workspace's own lists). Each carries the `grantedRole` you hold.\n * Empty when the organizations feature is off server-side.\n */\n sharedWithMe(): Promise<{ data: SharedWorkflow[] }> {\n return this.client.request(\"GET\", \"/v1/workflows/shared-with-me\")\n }\n}\n"]}
@@ -1,13 +1,22 @@
1
1
  // src/errors.ts
2
2
  var NodaroError = class extends Error {
3
- constructor(message, code, status) {
3
+ constructor(message, code, status, details) {
4
4
  super(message);
5
5
  this.code = code;
6
6
  this.status = status;
7
7
  this.name = "NodaroError";
8
+ if (details) this.details = { ...details };
8
9
  }
9
10
  code;
10
11
  status;
12
+ /**
13
+ * Every other field of the server's error envelope (`{ error: { code,
14
+ * message, … } }`), as it was sent: for example a trend refusal's `slot`, a
15
+ * publish refusal's `reasons`, a validation error's `issues`. Empty when the
16
+ * envelope had nothing else, or for an error the SDK made itself. A copy —
17
+ * changing it changes nothing else.
18
+ */
19
+ details = {};
11
20
  };
12
21
  var UnauthorizedError = class extends NodaroError {
13
22
  constructor(message = "Authentication required") {
@@ -36,8 +45,8 @@ var RateLimitedError = class extends NodaroError {
36
45
  }
37
46
  };
38
47
  var InsufficientCreditsError = class extends NodaroError {
39
- constructor(message = "Insufficient credits", required, available) {
40
- super(message, "insufficient_credits", 402);
48
+ constructor(message = "Insufficient credits", required, available, code = "insufficient_credits") {
49
+ super(message, code, 402);
41
50
  this.required = required;
42
51
  this.available = available;
43
52
  this.name = "InsufficientCreditsError";
@@ -45,6 +54,17 @@ var InsufficientCreditsError = class extends NodaroError {
45
54
  required;
46
55
  available;
47
56
  };
57
+ var CREDIT_CAP_CODES = /* @__PURE__ */ new Set([
58
+ "budget_exceeded",
59
+ "member_cap_exceeded",
60
+ "user_allowance_exceeded"
61
+ ]);
62
+ var CreditCapExceededError = class extends InsufficientCreditsError {
63
+ constructor(code, message = "A credit cap cannot cover this run", required, available) {
64
+ super(message, required, available, code);
65
+ this.name = "CreditCapExceededError";
66
+ }
67
+ };
48
68
  var StorageExceededError = class extends NodaroError {
49
69
  constructor(message = "Storage exceeded", limitBytes) {
50
70
  super(message, "storage_exceeded", 413);
@@ -200,7 +220,25 @@ function readErrorBody(status, body) {
200
220
  const message = nonEmpty(envelope.message) ?? outside;
201
221
  return { code, message, envelope };
202
222
  }
223
+ function envelopeDetails(envelope) {
224
+ const out = {};
225
+ for (const [key, value] of Object.entries(envelope)) {
226
+ if (key !== "code" && key !== "message") out[key] = value;
227
+ }
228
+ return out;
229
+ }
203
230
  function throwFromResponse(status, body) {
231
+ try {
232
+ selectError(status, body);
233
+ } catch (err) {
234
+ if (err instanceof NodaroError) {
235
+ const raw = body && typeof body === "object" ? body.error : void 0;
236
+ if (raw && typeof raw === "object") Object.defineProperty(err, "details", { value: envelopeDetails(raw), enumerable: true });
237
+ }
238
+ throw err;
239
+ }
240
+ }
241
+ function selectError(status, body) {
204
242
  const parsed = body && typeof body === "object" ? body : {};
205
243
  const read = readErrorBody(status, parsed);
206
244
  const envelope = read.envelope;
@@ -245,16 +283,18 @@ function throwFromResponse(status, body) {
245
283
  if (status === 404) throw new NotFoundError(read.message);
246
284
  if (status === 429) throw new RateLimitedError(read.message);
247
285
  if (status === 402) {
248
- throw new InsufficientCreditsError(
249
- read.message,
250
- finite(envelope.required) ?? finite(parsed.required),
251
- finite(envelope.available) ?? finite(parsed.balance)
252
- );
286
+ const required = finite(envelope.required) ?? finite(parsed.required);
287
+ const available = finite(envelope.available) ?? finite(parsed.balance) ?? finite(parsed.remaining);
288
+ const capCode = read.code;
289
+ if (capCode !== void 0 && CREDIT_CAP_CODES.has(capCode)) {
290
+ throw new CreditCapExceededError(capCode, read.message, required, available);
291
+ }
292
+ throw new InsufficientCreditsError(read.message, required, available, read.code ?? "insufficient_credits");
253
293
  }
254
294
  if (status === 413) throw new StorageExceededError(read.message, envelope.limitBytes);
255
295
  throw new NodaroError(message, code, status);
256
296
  }
257
297
 
258
- export { AlreadyRunningError, AppRunVersionChangedError, ContinuationPreviewPendingError, ContinuationRefusedError, ForbiddenError, InsufficientCreditsError, JobAbortedError, JobBlockedError, JobFailedError, JobHeldError, JobTimeoutError, NodaroError, NotFoundError, RateLimitedError, StorageExceededError, StudioOpError, StudioPreviewAppliedError, StudioPreviewUnavailable, UnauthorizedError, WorkflowConflictError, throwFromResponse };
259
- //# sourceMappingURL=chunk-JGS6YBDW.js.map
260
- //# sourceMappingURL=chunk-JGS6YBDW.js.map
298
+ export { AlreadyRunningError, AppRunVersionChangedError, CREDIT_CAP_CODES, ContinuationPreviewPendingError, ContinuationRefusedError, CreditCapExceededError, ForbiddenError, InsufficientCreditsError, JobAbortedError, JobBlockedError, JobFailedError, JobHeldError, JobTimeoutError, NodaroError, NotFoundError, RateLimitedError, StorageExceededError, StudioOpError, StudioPreviewAppliedError, StudioPreviewUnavailable, UnauthorizedError, WorkflowConflictError, throwFromResponse };
299
+ //# sourceMappingURL=chunk-L6T44A3G.js.map
300
+ //# sourceMappingURL=chunk-L6T44A3G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AAEO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAUrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,MAAA,EAChB,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAJG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAI,OAAA,EAAS,IAAA,CAAK,OAAA,GAAU,EAAE,GAAG,OAAA,EAAQ;AAAA,EA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AA,CAAK,OAAA,EAAS,SAAS,YAAY,CAAA;AAAA,EAC9D;AACA,EAAA,IAAI,WAAW,GAAA,EAAK,MAAM,IAAI,cAAA,CAAe,KAAK,OAAO,CAAA;AAIzD,EAAA,IAAI,WAAW,GAAA,EAAK,MAAM,IAAI,aAAA,CAAc,KAAK,OAAO,CAAA;AACxD,EAAA,IAAI,WAAW,GAAA,EAAK,MAAM,IAAI,gBAAA,CAAiB,KAAK,OAAO,CAAA;AAC3D,EAAA,IAAI,WAAW,GAAA,EAAK;AAIlB,IAAA,MAAM,WAAW,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,IAAK,MAAA,CAAO,OAAO,QAAQ,CAAA;AACpE,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,QAAA,CAAS,SAAS,CAAA,IAAK,MAAA,CAAO,MAAA,CAAO,OAAO,CAAA,IAAK,MAAA,CAAO,MAAA,CAAO,SAAS,CAAA;AACjG,IAAA,MAAM,UAAU,IAAA,CAAK,IAAA;AACrB,IAAA,IAAI,OAAA,KAAY,MAAA,IAAa,gBAAA,CAAiB,GAAA,CAAI,OAAO,CAAA,EAAG;AAC1D,MAAA,MAAM,IAAI,sBAAA,CAAuB,OAAA,EAAS,IAAA,CAAK,OAAA,EAAS,UAAU,SAAS,CAAA;AAAA,IAC7E;AACA,IAAA,MAAM,IAAI,yBAAyB,IAAA,CAAK,OAAA,EAAS,UAAU,SAAA,EAAW,IAAA,CAAK,QAAQ,sBAAsB,CAAA;AAAA,EAC3G;AACA,EAAA,IAAI,MAAA,KAAW,KAAK,MAAM,IAAI,qBAAqB,IAAA,CAAK,OAAA,EAAS,SAAS,UAAU,CAAA;AACpF,EAAA,MAAM,IAAI,WAAA,CAAY,OAAA,EAAS,IAAA,EAAM,MAAM,CAAA;AAC7C","file":"chunk-L6T44A3G.js","sourcesContent":["import type { StudioOpsResponse } from \"./resources/studio-productions.js\"\n\nexport class NodaroError extends Error {\n /**\n * Every other field of the server's error envelope (`{ error: { code,\n * message, … } }`), as it was sent: for example a trend refusal's `slot`, a\n * publish refusal's `reasons`, a validation error's `issues`. Empty when the\n * envelope had nothing else, or for an error the SDK made itself. A copy —\n * changing it changes nothing else.\n */\n public readonly details: Readonly<Record<string, unknown>> = {}\n\n constructor(\n message: string,\n public readonly code: string,\n public readonly status: number,\n details?: Readonly<Record<string, unknown>>,\n ) {\n super(message)\n this.name = \"NodaroError\"\n if (details) this.details = { ...details }\n }\n}\n\nexport class UnauthorizedError extends NodaroError {\n constructor(message = \"Authentication required\") {\n super(message, \"unauthorized\", 401)\n this.name = \"UnauthorizedError\"\n }\n}\n\nexport class ForbiddenError extends NodaroError {\n constructor(message = \"Forbidden\", public readonly missingScope?: string) {\n super(message, \"forbidden\", 403)\n this.name = \"ForbiddenError\"\n }\n}\n\nexport class NotFoundError extends NodaroError {\n constructor(message = \"Not found\") {\n super(message, \"not_found\", 404)\n this.name = \"NotFoundError\"\n }\n}\n\nexport class RateLimitedError extends NodaroError {\n constructor(message = \"Rate limited\") {\n super(message, \"rate_limited\", 429)\n this.name = \"RateLimitedError\"\n }\n}\n\n/**\n * HTTP 402: the run costs more than the caller may spend. `code` is the\n * refusal's own code — `insufficient_credits` for the caller's own balance, or\n * another 402 code such as `free_video_limit`. A spending cap someone else set\n * (a workspace budget, a member cap, a per-user allowance) is the subclass\n * {@link CreditCapExceededError}, so `instanceof InsufficientCreditsError`\n * still catches every 402.\n */\nexport class InsufficientCreditsError extends NodaroError {\n constructor(\n message = \"Insufficient credits\",\n public readonly required?: number,\n public readonly available?: number,\n code = \"insufficient_credits\",\n ) {\n super(message, code, 402)\n this.name = \"InsufficientCreditsError\"\n }\n}\n\n/** The 402 codes of a spending cap set by someone other than the caller. */\nexport type CreditCapCode = \"budget_exceeded\" | \"member_cap_exceeded\" | \"user_allowance_exceeded\"\n\n/**\n * The 402 codes {@link CreditCapExceededError} carries: the workspace's budget\n * (`budget_exceeded`), the caller's cap in that workspace\n * (`member_cap_exceeded`), the deployment's per-user allowance\n * (`user_allowance_exceeded`).\n */\nexport const CREDIT_CAP_CODES: ReadonlySet<CreditCapCode> = new Set<CreditCapCode>([\n \"budget_exceeded\",\n \"member_cap_exceeded\",\n \"user_allowance_exceeded\",\n])\n\n/**\n * HTTP 402 from a spending cap, not from the caller's own balance: topping up\n * does not help — whoever set the cap (the workspace's owner, the deployment's\n * operator) has to raise it. An {@link InsufficientCreditsError}, so existing\n * catches keep working; `code` says which cap. `available`, when sent, is what\n * the cap has left.\n */\nexport class CreditCapExceededError extends InsufficientCreditsError {\n declare readonly code: CreditCapCode\n\n constructor(code: CreditCapCode, message = \"A credit cap cannot cover this run\", required?: number, available?: number) {\n super(message, required, available, code)\n this.name = \"CreditCapExceededError\"\n }\n}\n\nexport class StorageExceededError extends NodaroError {\n constructor(message = \"Storage exceeded\", public readonly limitBytes?: number) {\n super(message, \"storage_exceeded\", 413)\n this.name = \"StorageExceededError\"\n }\n}\n\n/**\n * Optimistic-concurrency rejection (HTTP 409 `workflow_conflict`): the workflow\n * was written by another tab/device after the state carried in\n * `expectedUpdatedAt`/`expectedVersion` was read. `currentRecord` — when the\n * server includes it — is the full current workflow: merge your changes onto it\n * and retry with its fresh `updatedAt`, no follow-up GET needed.\n */\nexport class WorkflowConflictError extends NodaroError {\n constructor(\n message = \"Workflow was updated by another writer\",\n public readonly currentUpdatedAt?: string,\n public readonly currentVersion?: number,\n public readonly currentRecord?: Record<string, unknown>,\n /**\n * The wire code this conflict actually arrived with.\n *\n * `production_busy` is the studio production routes' own 409: the row\n * changed under a read-modify-write and the server exhausted its retries.\n * It is the same situation and the same remedy — re-read and apply again —\n * so it is the same ERROR, and a caller catching `WorkflowConflictError`\n * handles both. The code stays truthful because a caller that logs or\n * branches on it should see what the server said, not what the class is\n * usually called.\n */\n code: WorkflowConflictCode = \"workflow_conflict\",\n ) {\n super(message, code, 409)\n this.name = \"WorkflowConflictError\"\n }\n}\n\n/** The 409 codes that mean \"somebody else wrote first; re-read and retry\". */\nexport type WorkflowConflictCode = \"workflow_conflict\" | \"production_busy\"\n\n/**\n * A studio operation batch was refused, and the error names WHICH operation\n * (`opIndex`, zero-based) was wrong. Nothing in the batch was written: a batch\n * applies atomically or not at all, so fix that one operation and send the\n * whole batch again.\n *\n * Selected by SHAPE — any 4xx carrying a numeric `opIndex` — not by a list of\n * codes, so a new refusal reason (`op_invalid`, `op_target_missing`, whatever\n * the server adds next) reaches the caller as this error without an SDK\n * release. `code` is whatever the server sent.\n */\nexport class StudioOpError extends NodaroError {\n constructor(\n message: string,\n code: string,\n status: number,\n /** Zero-based index into the `ops` array that was sent. */\n public readonly opIndex: number,\n ) {\n super(message, code, status)\n this.name = \"StudioOpError\"\n }\n}\n\n/** The 409 codes whose answer names the job to turn to instead (a top-level `jobId`). */\nconst CONTINUATION_REFUSAL_CODES: ReadonlySet<string> = new Set([\n \"already_running\",\n \"continuation_superseded\",\n \"render_final_already_rendered\",\n])\n\n/**\n * A 409 that names the job to turn to instead: continuing a use-case run\n * (`client.edit.continueUseCase`) answers `already_running` (a continuation is\n * under way, or one that already completed — follow `jobId`),\n * `continuation_superseded` (a later continuation failed too — continue\n * `jobId` instead) or `render_final_already_rendered` (a Render final with this\n * very edit already completed — `jobId` holds the result). `code` and `status`\n * are what the server sent. Selected for exactly those three codes when the\n * answer carries a top-level `jobId`; every other 409 stays a plain\n * `NodaroError`.\n */\nexport class ContinuationRefusedError extends NodaroError {\n constructor(\n message: string,\n code: string,\n /** The job the refusal names. */\n public readonly jobId: string,\n ) {\n super(message, code, 409)\n this.name = \"ContinuationRefusedError\"\n }\n}\n\n/**\n * The one run that finishes a continuation held at a Preview review (the\n * `next` of {@link ContinuationPreviewPendingError}): pass these three fields\n * to `client.workflows.run`. It continues that execution, runs each held render\n * at Final and each held Tighten Episode continuing the run that made its\n * Preview, then every node after them.\n */\nexport interface HeldFinalRun {\n continueFromExecutionId: string\n /** The nodes it runs, in canvas order. */\n nodeIds: string[]\n /** For this run only: each held render at Final, each held use-case node's `useCaseContinue`. */\n inputOverrides: Record<string, Record<string, unknown>>\n}\n\n/**\n * HTTP 409 `continuation_preview_pending`: a continue-from-failed\n * (`client.workflows.run` with `continueMode: \"from-failed\"`) whose run's\n * newest later continuation completed by stopping at a Preview review, so\n * continuing again would stop there too. `executionId` is that continuation;\n * `renderNodeIds` the Apply EDL renders and `reviewNodeIds` the Tighten Episode\n * nodes holding it; `next` the run that finishes them — send it first\n * (`client.workflows.run(workflowId, error.next)`), then continue. Absent only\n * when the server could not name it. For a single held render, `next` is that\n * render's `client.workflows.renderFinal`.\n */\nexport class ContinuationPreviewPendingError extends NodaroError {\n constructor(\n message: string,\n public readonly executionId: string,\n public readonly renderNodeIds: readonly string[],\n public readonly reviewNodeIds: readonly string[],\n public readonly next?: HeldFinalRun,\n ) {\n super(message, \"continuation_preview_pending\", 409)\n this.name = \"ContinuationPreviewPendingError\"\n }\n}\n\nconst stringList = (v: unknown): string[] => (Array.isArray(v) ? v.filter((id): id is string => typeof id === \"string\") : [])\n\n/** A `next` as the server sends it, or undefined for anything else. */\nfunction heldFinalRunOf(v: unknown): HeldFinalRun | undefined {\n if (!v || typeof v !== \"object\") return undefined\n const r = v as Record<string, unknown>\n if (typeof r.continueFromExecutionId !== \"string\" || !Array.isArray(r.nodeIds)) return undefined\n if (!r.inputOverrides || typeof r.inputOverrides !== \"object\" || Array.isArray(r.inputOverrides)) return undefined\n return {\n continueFromExecutionId: r.continueFromExecutionId,\n nodeIds: stringList(r.nodeIds),\n inputOverrides: r.inputOverrides as Record<string, Record<string, unknown>>,\n }\n}\n\n/**\n * HTTP 409 `already_running` that names the execution under way (a top-level\n * `executionId`): the run you asked to start or continue is still running —\n * follow `executionId` (`client.executions.get`) instead of starting it again.\n * Sent by the workflow run route and by an app run's Retry\n * (`client.apps.resume`). An `already_running` that names a job instead stays\n * {@link ContinuationRefusedError}; one that names nothing, a plain\n * `NodaroError`.\n */\nexport class AlreadyRunningError extends NodaroError {\n constructor(\n message: string,\n /** The execution under way. */\n public readonly executionId: string,\n ) {\n super(message, \"already_running\", 409)\n this.name = \"AlreadyRunningError\"\n }\n}\n\n/**\n * HTTP 409 `app_run_version_changed`: a Retry of a failed app run\n * (`client.apps.resume`) refused because the app is on another version than\n * the one the run ran — continuing would mix them. `runVersion` is the run's\n * version, `appVersion` the one you are on (the `version` you sent, else the\n * app's latest). Start the run over (`client.apps.run`) to run `appVersion`,\n * or send `{ version: runVersion }` to continue on the run's own version.\n * Nothing was written or billed. Selected by code; the two numbers are\n * `undefined` when the answer does not carry them.\n */\nexport class AppRunVersionChangedError extends NodaroError {\n constructor(\n message: string,\n public readonly runVersion?: number,\n public readonly appVersion?: number,\n ) {\n super(message, \"app_run_version_changed\", 409)\n this.name = \"AppRunVersionChangedError\"\n }\n}\n\n/**\n * HTTP 422 `job_blocked`. A job policy registered by this deployment refused\n * the generation **before it ran** — no job was created, nothing was reserved\n * and nothing was charged. `message` is the policy's user-safe text: show it\n * as-is. Do not retry the identical request; whether the same input would be\n * judged differently is the deployment's policy's business.\n *\n * Only occurs on deployments that register a job policy. Selected by `code`,\n * not by status, the same way `workflow_conflict` narrows a 409 above — any\n * other 422 stays a plain `NodaroError`.\n */\nexport class JobBlockedError extends NodaroError {\n constructor(message = \"Blocked by this deployment's content policy\") {\n super(message, \"job_blocked\", 422)\n this.name = \"JobBlockedError\"\n }\n}\n\n/**\n * A job reached a terminal `failed`/`cancelled` status while being awaited by\n * `nodes.runAndWait` / `nodes.runMany`. Not an HTTP-level error (the polls\n * themselves succeeded), so `status` is 0 — distinguish it by type/`code`.\n * Carries the job's own `error_message` (as the message) and `jobId`.\n */\nexport class JobFailedError extends NodaroError {\n constructor(\n message: string,\n public readonly jobId: string,\n /** The terminal status that triggered the failure (`failed` | `cancelled`). */\n public readonly jobStatus: \"failed\" | \"cancelled\" = \"failed\",\n ) {\n super(message, \"job_failed\", 0)\n this.name = \"JobFailedError\"\n }\n}\n\n/**\n * `nodes.runAndWait` polled past its `maxMs` deadline without the job reaching\n * a terminal status. Not an HTTP error — `status` is 0; catch by type/`code`.\n */\nexport class JobTimeoutError extends NodaroError {\n constructor(\n message: string,\n public readonly jobId: string,\n /** The wall-clock deadline (ms) that was exceeded. */\n public readonly timeoutMs: number,\n ) {\n super(message, \"job_timeout\", 0)\n this.name = \"JobTimeoutError\"\n }\n}\n\n/**\n * The caller's `AbortSignal` fired while `nodes.runAndWait` was polling (or it\n * was already aborted on entry). Polling stops and this rejects. Not an HTTP\n * error — `status` is 0; catch by type/`code`.\n */\nexport class JobAbortedError extends NodaroError {\n constructor(message = \"Aborted\", public readonly jobId?: string) {\n super(message, \"job_aborted\", 0)\n this.name = \"JobAbortedError\"\n }\n}\n\n/**\n * A batch preview was asked for and this deployment cannot give one, so\n * NOTHING was sent: the batch is still unapplied and the production untouched.\n *\n * A preview is two requests because the route's body is parsed in strip mode —\n * a deployment that predates the preview silently DROPS the flag and APPLIES\n * the batch. So the SDK asks with an EMPTY batch first and sends the real one\n * only when that answer carries the `dryRun` marker. This is what it throws\n * when the answer does not: whatever the older deployment made of an empty\n * batch, the caller's batch never left.\n *\n * The remedy is a deployment that serves the preview — there is nothing to\n * retry here. To apply the batch instead, send it without the flag.\n *\n * A deployment that REFUSES the empty batch outright throws its own error\n * instead of this one, which is the right way round: the route's message says\n * more than \"unavailable\" does.\n *\n * Not an HTTP error: the request itself succeeded and answered the older shape.\n * `status` is 0; catch by type/`code`.\n */\nexport class StudioPreviewUnavailable extends NodaroError {\n constructor(\n message = \"This deployment does not preview operation batches; nothing was sent\",\n ) {\n super(message, \"studio_preview_unavailable\", 0)\n this.name = \"StudioPreviewUnavailable\"\n }\n}\n\n/**\n * A batch preview was asked for and the batch was APPLIED instead. The\n * production is written; this is the opposite of {@link\n * StudioPreviewUnavailable}, where nothing was sent.\n *\n * How it happens: the preview's proving ping and the batch are two requests,\n * and a fleet mid-rollout can serve them from different deployments. The ping\n * answers the marker, the batch reaches a deployment that predates the preview,\n * parses in strip mode, drops the flag and writes. The SDK cannot recall that\n * request — by the time the answer comes back the change has landed — so it\n * refuses to call the result a preview, which is the only thing still in its\n * gift. `receipts` and `warnings` are on both shapes, so an unchecked reply\n * would have shown a person what ALREADY happened under the heading of what\n * would.\n *\n * `applied` is what the route answered: the ordinary apply reply, whose\n * `production` and `version` are now the truth. Adopt them the way a plain\n * apply's caller does — do NOT re-send the batch, and do not present it for\n * approval.\n *\n * Not an HTTP error: the request succeeded, at the wrong thing. `status` is 0.\n */\nexport class StudioPreviewAppliedError extends NodaroError {\n constructor(\n /**\n * The apply reply the route sent back, as it sent it. An answer this\n * package does not recognise arrives here unchanged rather than being\n * dressed up: it is what the deployment said about a batch it took.\n *\n * `undefined` when the answer carried no body at all — a 204, an empty\n * envelope. The refusal still fires, because a non-preview answer is never\n * handed back as a preview, but there is nothing to report and the SDK will\n * not invent it: whether the batch was applied is unknown from here, and\n * the caller settles it by re-reading the production.\n */\n public readonly applied: StudioOpsResponse | undefined,\n message = applied\n ? \"Asked for a preview and this deployment APPLIED the batch; the change is written — see `applied`\"\n : \"Asked for a preview and this deployment answered with neither one nor a body to read; the batch may have been applied — re-read the production before deciding anything\",\n ) {\n super(message, \"studio_preview_applied\", 0)\n this.name = \"StudioPreviewAppliedError\"\n }\n}\n\n/**\n * The awaited job entered `pending_review`: a job policy registered by this\n * deployment held its output for a human reviewer. `pending_review` is\n * IN-FLIGHT, not terminal, so `nodes.runAndWait` / `nodes.runMany` end the\n * poll on the first tick they observe it rather than burning `maxMs` on a\n * status that no longer moves on its own.\n *\n * This does NOT cancel the job — the output exists, a human is reviewing it,\n * and the credit reservation stays `reserved` for the whole hold. Do not\n * re-run the request (a duplicate would be held too): re-fetch with\n * `jobs.get(jobId)` later, or surface \"awaiting review\" to your user and poll\n * `jobs.getStatus()` yourself. It resolves to `completed` (approved), `failed`\n * (rejected, with `error_hint.kind === \"policy-block\"`) or `cancelled`.\n *\n * Not an HTTP error — `status` is 0; catch by type/`code`.\n */\nexport class JobHeldError extends NodaroError {\n constructor(\n message: string,\n public readonly jobId: string,\n ) {\n super(message, \"job_held\", 0)\n this.name = \"JobHeldError\"\n }\n}\n\n/** The `{ error: { code, message, … } }` envelope every current route sends. */\ninterface ApiErrorEnvelope {\n code?: string\n message?: string\n missingScope?: string\n required?: number\n available?: number\n limitBytes?: number\n opIndex?: number\n [key: string]: unknown\n}\n\ninterface ApiErrorBody {\n /** The envelope — or, on an older route, a bare string (see {@link readErrorBody}). */\n error?: ApiErrorEnvelope | string\n /** A top-level message: an older route's, a bare validation answer's, or the server framework's own. */\n message?: unknown\n /** OAuth's human text (RFC 6749 §5.2), beside a bare-string `error`. */\n error_description?: unknown\n /** A bare validation answer's per-field issues (`{ message, issues }`). */\n issues?: unknown\n /** A refusal that names another job (see {@link ContinuationRefusedError}). */\n jobId?: unknown\n /** `continuation_preview_pending`: the held continuation, what holds it, and the run that finishes it. */\n executionId?: unknown\n renderNodeIds?: unknown\n reviewNodeIds?: unknown\n next?: unknown\n /** The credit guard's 402 sends its figures beside the envelope: what the run needs… */\n required?: unknown\n /** …and what the caller has (withheld on a deployment-paid instance). */\n balance?: unknown\n /** A per-user allowance's 402: what the allowance has left. */\n remaining?: unknown\n /** `app_run_version_changed`: the version the run ran, and the one the caller is on. */\n runVersion?: unknown\n appVersion?: unknown\n}\n\nconst finite = (v: unknown): number | undefined => (typeof v === \"number\" && Number.isFinite(v) ? v : undefined)\n\n/** A machine code as an older route writes it: lower snake_case, never a sentence or a reason phrase. */\nconst BARE_CODE = /^[a-z][a-z0-9_]*$/\n\nconst nonEmpty = (v: unknown): string | undefined => (typeof v === \"string\" && v.length > 0 ? v : undefined)\n\n/**\n * Where a body keeps its code and its human message. Most routes send the\n * envelope `{ error: { code, message } }`; three other shapes reach the SDK\n * too, and each is read for what it says rather than collapsed into\n * `internal_error` / \"Request failed\":\n *\n * - an older route's bare string, `{ error: \"<code>\", message?, … }` (character\n * training, a few profile and billing routes), and OAuth's\n * `{ error: \"<code>\", error_description }`. A snake_case string is the code;\n * a sentence (`\"Profile not found\"`) is the message.\n * - a bare validation answer, `{ message, issues: [...] }`: `validation_error`.\n * - the server framework's own answer, `{ statusCode, error: \"<reason phrase>\",\n * message }` (a route it does not have): the reason phrase is neither, the\n * message is kept — so \"no such route\" stays distinguishable from \"no such\n * resource\".\n *\n * At HTTP 500 and above only the CODE is read from outside the envelope. Text\n * there can be whatever the server failed with: the framework's own answer to\n * an uncaught throw is `{ statusCode: 500, error: \"Internal Server Error\",\n * message: <the raw error> }`, and the server's sanitizer rewrites only the\n * `internal_error` envelope. The envelope's own message is a route's chosen\n * sentence and is read at every status, as before.\n *\n * `message` is undefined when the body carries no human text it may show, so a\n * typed class keeps its own default (\"Not found\").\n */\nfunction readErrorBody(status: number, body: ApiErrorBody): { code: string | undefined; message: string | undefined; envelope: ApiErrorEnvelope } {\n const raw = body.error\n const envelope: ApiErrorEnvelope = raw && typeof raw === \"object\" ? raw : {}\n const bare = typeof raw === \"string\" ? raw : undefined\n const bareCode = bare !== undefined && BARE_CODE.test(bare) ? bare : undefined\n // Words with a space between them are human text: an older route's sentence,\n // or the framework's reason phrase — which always arrives with a real\n // `message`, read first. A single capitalised word (\"Unauthorized\") is a\n // reason phrase alone and says nothing the status does not.\n const bareSentence = bare !== undefined && bareCode === undefined && /\\s/.test(bare.trim()) ? bare : undefined\n const code =\n nonEmpty(envelope.code) ??\n bareCode ??\n (status === 400 && raw === undefined && Array.isArray(body.issues) ? \"validation_error\" : undefined)\n const outside = status >= 500 ? undefined : (nonEmpty(body.message) ?? nonEmpty(body.error_description) ?? bareSentence)\n const message = nonEmpty(envelope.message) ?? outside\n return { code, message, envelope }\n}\n\n/** The envelope's fields other than `code` and `message` (see {@link NodaroError.details}). */\nfunction envelopeDetails(envelope: ApiErrorEnvelope): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(envelope)) {\n if (key !== \"code\" && key !== \"message\") out[key] = value\n }\n return out\n}\n\nexport function throwFromResponse(status: number, body: ApiErrorBody): never {\n try {\n selectError(status, body)\n } catch (err) {\n // Every class carries the envelope's other fields, whichever was chosen.\n if (err instanceof NodaroError) {\n const raw = body && typeof body === \"object\" ? body.error : undefined\n if (raw && typeof raw === \"object\") Object.defineProperty(err, \"details\", { value: envelopeDetails(raw), enumerable: true })\n }\n throw err\n }\n}\n\nfunction selectError(status: number, body: ApiErrorBody): never {\n // A body that is not an object (an empty answer, `null`, a bare string) still\n // throws by its status.\n const parsed: ApiErrorBody = body && typeof body === \"object\" ? body : {}\n const read = readErrorBody(status, parsed)\n const envelope = read.envelope\n const code = read.code ?? \"internal_error\"\n // A typed class falls back to its own default; a generic error to the code\n // it carries, which says more than \"Request failed\" does.\n const message = read.message ?? (read.code ? read.code : \"Request failed\")\n if (status === 401) throw new UnauthorizedError(read.message)\n if (status === 409 && (code === \"workflow_conflict\" || code === \"production_busy\")) {\n throw new WorkflowConflictError(\n read.message,\n envelope.currentUpdatedAt as string | undefined,\n envelope.currentVersion as number | undefined,\n envelope.currentRecord as Record<string, unknown> | undefined,\n code,\n )\n }\n // By shape, not by code — see StudioOpError. Only the studio operations route\n // sends an op index, so this cannot capture anyone else's 400.\n if (status >= 400 && status < 500 && typeof envelope.opIndex === \"number\") {\n throw new StudioOpError(message, code, status, envelope.opIndex)\n }\n if (status === 409 && CONTINUATION_REFUSAL_CODES.has(code) && typeof parsed.jobId === \"string\") {\n throw new ContinuationRefusedError(message, code, parsed.jobId)\n }\n if (status === 409 && code === \"continuation_preview_pending\" && typeof parsed.executionId === \"string\") {\n throw new ContinuationPreviewPendingError(\n message,\n parsed.executionId,\n stringList(parsed.renderNodeIds),\n stringList(parsed.reviewNodeIds),\n heldFinalRunOf(parsed.next),\n )\n }\n if (status === 409 && code === \"already_running\" && typeof parsed.executionId === \"string\") {\n throw new AlreadyRunningError(message, parsed.executionId)\n }\n if (status === 409 && code === \"app_run_version_changed\") {\n throw new AppRunVersionChangedError(message, finite(parsed.runVersion), finite(parsed.appVersion))\n }\n if (status === 422 && code === \"job_blocked\") throw new JobBlockedError(read.message)\n if (status === 403 && code === \"insufficient_scope\") {\n throw new ForbiddenError(read.message, envelope.missingScope)\n }\n if (status === 403) throw new ForbiddenError(read.message)\n // A 404 the framework answered itself (no route at that path) carries its\n // message at the top level, not under `error`; `readErrorBody` keeps it so\n // callers can tell \"no such route\" from \"no such resource\".\n if (status === 404) throw new NotFoundError(read.message)\n if (status === 429) throw new RateLimitedError(read.message)\n if (status === 402) {\n // The credit guard puts `required` / `balance` (an allowance: `remaining`)\n // beside the envelope; an envelope that carries them (`required` /\n // `available`) is read first.\n const required = finite(envelope.required) ?? finite(parsed.required)\n const available = finite(envelope.available) ?? finite(parsed.balance) ?? finite(parsed.remaining)\n const capCode = read.code as CreditCapCode | undefined\n if (capCode !== undefined && CREDIT_CAP_CODES.has(capCode)) {\n throw new CreditCapExceededError(capCode, read.message, required, available)\n }\n throw new InsufficientCreditsError(read.message, required, available, read.code ?? \"insufficient_credits\")\n }\n if (status === 413) throw new StorageExceededError(read.message, envelope.limitBytes)\n throw new NodaroError(message, code, status)\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkN6GLZOE4_cjs = require('./chunk-N6GLZOE4.cjs');
3
+ var chunkFM2KM5TY_cjs = require('./chunk-FM2KM5TY.cjs');
4
4
 
5
5
  // src/resources/studio-productions.ts
6
6
  function isStudioGenerateEstimate(result) {
@@ -104,11 +104,11 @@ var StudioProductionsResource = class {
104
104
  this.path(productionId, "/ops"),
105
105
  { body: { ops: [], dryRun: true } }
106
106
  );
107
- if (ping?.data?.dryRun !== true) throw new chunkN6GLZOE4_cjs.StudioPreviewUnavailable();
107
+ if (ping?.data?.dryRun !== true) throw new chunkFM2KM5TY_cjs.StudioPreviewUnavailable();
108
108
  const res = await this.client.request("POST", this.path(productionId, "/ops"), { body: input });
109
109
  const data = res?.data;
110
110
  if (data?.dryRun !== true) {
111
- throw new chunkN6GLZOE4_cjs.StudioPreviewAppliedError(data);
111
+ throw new chunkFM2KM5TY_cjs.StudioPreviewAppliedError(data);
112
112
  }
113
113
  return data;
114
114
  }
@@ -321,5 +321,5 @@ var StudioResource = class {
321
321
  exports.StudioProductionsResource = StudioProductionsResource;
322
322
  exports.StudioResource = StudioResource;
323
323
  exports.isStudioGenerateEstimate = isStudioGenerateEstimate;
324
- //# sourceMappingURL=chunk-U4T3Z3K7.cjs.map
325
- //# sourceMappingURL=chunk-U4T3Z3K7.cjs.map
324
+ //# sourceMappingURL=chunk-NKH2UFSD.cjs.map
325
+ //# sourceMappingURL=chunk-NKH2UFSD.cjs.map