@nodaro/sdk 2.47.0 → 2.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-KBHDUHKM.js → chunk-2SQ7V6EX.js} +2 -2
- package/dist/chunk-2SQ7V6EX.js.map +1 -0
- package/dist/{chunk-FIMBPKIH.cjs → chunk-4BAHF762.cjs} +43 -2
- package/dist/chunk-4BAHF762.cjs.map +1 -0
- package/dist/chunk-6FZN3QQO.cjs +146 -0
- package/dist/chunk-6FZN3QQO.cjs.map +1 -0
- package/dist/{chunk-5MOJSYHI.js → chunk-7QK2NXJA.js} +43 -2
- package/dist/chunk-7QK2NXJA.js.map +1 -0
- package/dist/{chunk-JTAW54UM.js → chunk-AEUPH7EE.js} +2 -2
- package/dist/{chunk-34PU2DAT.cjs.map → chunk-AEUPH7EE.js.map} +1 -1
- package/dist/{chunk-DIF7A5OH.cjs → chunk-E5MJK3W5.cjs} +2 -2
- package/dist/chunk-E5MJK3W5.cjs.map +1 -0
- package/dist/{chunk-I7AHLDXV.js → chunk-EC6MC46Y.js} +10 -10
- package/dist/{chunk-I7AHLDXV.js.map → chunk-EC6MC46Y.js.map} +1 -1
- package/dist/{chunk-NP6KDFIJ.cjs → chunk-HPSENMVN.cjs} +18 -18
- package/dist/{chunk-NP6KDFIJ.cjs.map → chunk-HPSENMVN.cjs.map} +1 -1
- package/dist/{chunk-XKDVEQVD.cjs → chunk-LTZKNAXM.cjs} +2 -2
- package/dist/chunk-LTZKNAXM.cjs.map +1 -0
- package/dist/{chunk-OWG3XAHQ.js → chunk-OCRUDBPG.js} +10 -6
- package/dist/chunk-OCRUDBPG.js.map +1 -0
- package/dist/{chunk-MYTMNPCP.cjs → chunk-OMX7JBGY.cjs} +3 -3
- package/dist/{chunk-MYTMNPCP.cjs.map → chunk-OMX7JBGY.cjs.map} +1 -1
- package/dist/{chunk-7LTVS75S.cjs → chunk-P6AM42UB.cjs} +2 -2
- package/dist/chunk-P6AM42UB.cjs.map +1 -0
- package/dist/{chunk-34PU2DAT.cjs → chunk-Q45PC4YD.cjs} +2 -2
- package/dist/chunk-Q45PC4YD.cjs.map +1 -0
- package/dist/{chunk-PQHZUWSL.js → chunk-THLTFB6I.js} +2 -2
- package/dist/chunk-THLTFB6I.js.map +1 -0
- package/dist/{chunk-GDDV5U32.cjs → chunk-TY2S25W5.cjs} +10 -6
- package/dist/chunk-TY2S25W5.cjs.map +1 -0
- package/dist/chunk-WYYDWJFF.js +144 -0
- package/dist/chunk-WYYDWJFF.js.map +1 -0
- package/dist/{chunk-FCYN4N3M.js → chunk-XISHBW5I.js} +3 -3
- package/dist/{chunk-FCYN4N3M.js.map → chunk-XISHBW5I.js.map} +1 -1
- package/dist/{chunk-XILR6TFO.js → chunk-YXVMQEJX.js} +2 -2
- package/dist/chunk-YXVMQEJX.js.map +1 -0
- package/dist/entries/billing.cjs +2 -2
- package/dist/entries/billing.d.cts +202 -3
- package/dist/entries/billing.d.ts +202 -3
- package/dist/entries/billing.js +1 -1
- package/dist/entries/cast-swap.cjs +2 -2
- package/dist/entries/cast-swap.d.cts +34 -31
- package/dist/entries/cast-swap.d.ts +34 -31
- package/dist/entries/cast-swap.js +1 -1
- package/dist/entries/client.cjs +14 -14
- package/dist/entries/client.js +9 -9
- package/dist/entries/core.cjs +5 -5
- package/dist/entries/core.js +1 -1
- package/dist/entries/credits.cjs +2 -2
- package/dist/entries/credits.d.cts +179 -1
- package/dist/entries/credits.d.ts +179 -1
- package/dist/entries/credits.js +1 -1
- package/dist/entries/jobs.cjs +2 -2
- package/dist/entries/jobs.d.cts +18 -7
- package/dist/entries/jobs.d.ts +18 -7
- package/dist/entries/jobs.js +1 -1
- package/dist/entries/node-presets.cjs +2 -2
- package/dist/entries/node-presets.d.cts +6 -0
- package/dist/entries/node-presets.d.ts +6 -0
- package/dist/entries/node-presets.js +1 -1
- package/dist/entries/trash.cjs +2 -2
- package/dist/entries/trash.d.cts +4 -1
- package/dist/entries/trash.d.ts +4 -1
- package/dist/entries/trash.js +1 -1
- package/dist/entries/trends.cjs +2 -2
- package/dist/entries/trends.d.cts +22 -13
- package/dist/entries/trends.d.ts +22 -13
- package/dist/entries/trends.js +1 -1
- package/dist/index.cjs +22 -22
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +9 -9
- package/package.json +3 -3
- package/dist/chunk-5MOJSYHI.js.map +0 -1
- package/dist/chunk-7LTVS75S.cjs.map +0 -1
- package/dist/chunk-DIF7A5OH.cjs.map +0 -1
- package/dist/chunk-FIMBPKIH.cjs.map +0 -1
- package/dist/chunk-GDDV5U32.cjs.map +0 -1
- package/dist/chunk-J4WFSKY6.js +0 -50
- package/dist/chunk-J4WFSKY6.js.map +0 -1
- package/dist/chunk-JTAW54UM.js.map +0 -1
- package/dist/chunk-KBHDUHKM.js.map +0 -1
- package/dist/chunk-NGKODS3J.cjs +0 -52
- package/dist/chunk-NGKODS3J.cjs.map +0 -1
- package/dist/chunk-OWG3XAHQ.js.map +0 -1
- package/dist/chunk-PQHZUWSL.js.map +0 -1
- package/dist/chunk-XILR6TFO.js.map +0 -1
- package/dist/chunk-XKDVEQVD.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
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,KAAS,CAAC,OAAA,CAAQ,IAAA,CAAK,UAAU,CAAA,IAAK,MAAA,CAAO,UAAU,CAAA,GAAI,QAAA,CAAA,EAAW;AACvF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAC5B,IAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;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A,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC1C,QAAA,IAAI,CAAA,KAAM,QAAW,CAAA,CAAE,YAAA,CAAa,IAAI,CAAA,EAAG,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,MACtD;AACA,MAAA,OAAO,KAAK,OAAA,GAAU,CAAA,CAAE,UAAS,GAAI,CAAA,CAAE,WAAW,CAAA,CAAE,MAAA;AAAA,IACtD;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;ACjUO,IAAM,kBAAN,MAAsC;AAAA,EAC3C,YAAoB,KAAA,EAAe;AAAf,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAAgB;AAAA,EAAhB,KAAA;AAAA,EACpB,MAAM,QAAA,GAAW;AACf,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AACF;AAEO,IAAM,eAAN,MAAmC;AAAA,EACxC,YAAoB,EAAA,EAAkD;AAAlD,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AAAA,EAAmD;AAAA,EAAnD,EAAA;AAAA,EACpB,MAAM,QAAA,GAAW;AACf,IAAA,OAAO,KAAK,EAAA,EAAG;AAAA,EACjB;AACF;AASO,SAAS,aAAa,QAAA,EAAoC;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-MYTMNPCP.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,KAAS,CAAC,OAAA,CAAQ,IAAA,CAAK,UAAU,CAAA,IAAK,MAAA,CAAO,UAAU,CAAA,GAAI,QAAA,CAAA,EAAW;AACvF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAC5B,IAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,EACnE;AACA,EAAA,IAAI,CAAC,QAAA,CAAS,IAAA,EAAM,OAAO,IAAI,YAAY,CAAC,CAAA;AAC5C,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,CAAK,SAAA,EAAU;AACvC,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,I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,GAAI,CAAA,CAAE,WAAW,CAAA,CAAE,MAAA;AAAA,IACtD;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;ACjUO,IAAM,kBAAN,MAAsC;AAAA,EAC3C,YAAoB,KAAA,EAAe;AAAf,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAAgB;AAAA,EAAhB,KAAA;AAAA,EACpB,MAAM,QAAA,GAAW;AACf,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AACF;AAEO,IAAM,eAAN,MAAmC;AAAA,EACxC,YAAoB,EAAA,EAAkD;AAAlD,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AAAA,EAAmD;AAAA,EAAnD,EAAA;AAAA,EACpB,MAAM,QAAA,GAAW;AACf,IAAA,OAAO,KAAK,EAAA,EAAG;AAAA,EACjB;AACF;AASO,SAAS,aAAa,QAAA,EAAoC;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-OMX7JBGY.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"]}
|
|
@@ -118,5 +118,5 @@ var JobsResource = class {
|
|
|
118
118
|
};
|
|
119
119
|
|
|
120
120
|
exports.JobsResource = JobsResource;
|
|
121
|
-
//# sourceMappingURL=chunk-
|
|
122
|
-
//# sourceMappingURL=chunk-
|
|
121
|
+
//# sourceMappingURL=chunk-P6AM42UB.cjs.map
|
|
122
|
+
//# sourceMappingURL=chunk-P6AM42UB.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/jobs.ts"],"names":[],"mappings":";;;AA8SA,SAAS,UAAU,KAAA,EAAmE;AACpF,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,KAAA,CAAM,KAAK,GAAG,CAAA;AAC3D;AAgCO,IAAM,eAAN,MAAmB;AAAA,EACxB,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,IAAI,EAAA,EAAoC;AACtC,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,KAAA,EAAO,YAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,IAAA,CAAK,MAAA,GAAyB,EAAC,EAA0B;AACvD,I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AAAA;AAAA,EAWA,OAAO,EAAA,EAAsC;AAC3C,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,MAAA;AAAA,MACA,CAAA,SAAA,EAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,OAAA;AAAA,KACpC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAA,CAAO,EAAA,EAAY,OAAA,GAAiC,EAAC,EAA6B;AAChF,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,QAAA;AAAA,MACA,CAAA,SAAA,EAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA;AAAA,MAClC,OAAA,CAAQ,UAAU,EAAE,KAAA,EAAO,EAAE,OAAA,EAAS,MAAA,EAAO,EAAE,GAAI;AAAC,KACtD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAQ,EAAA,EAAwC;AAC9C,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,YAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,QAAA,CAAU,CAAA;AAAA,EACjF;AACF","file":"chunk-P6AM42UB.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * A job's lifecycle status. Hand-copied mirror of `JOB_STATUSES` in the\n * platform's `backend/src/lib/job-status.ts` — nothing links the two at build\n * time, so a new member has to be added here in the same change.\n *\n * `pending_review` is IN-FLIGHT, NOT TERMINAL: a job policy registered by the\n * deployment held the output for a human reviewer. Treat it like `processing`\n * in a `switch` — keep waiting, do not re-run — and it resolves to `completed`\n * (approved), `failed` (rejected, carrying an `error_hint` with\n * `kind: \"policy-block\"`) or `cancelled` (a held job is cancellable like any\n * in-flight job). `credit_status` reads `\"reserved\"` for the whole hold. Only\n * appears on deployments that register a job policy; `runAndWait` throws\n * {@link JobHeldError} on the first held tick rather than waiting it out.\n */\nexport type JobStatus =\n | \"pending\"\n | \"queued\"\n | \"processing\"\n | \"pending_review\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n\n/**\n * A PROVIDER's verdict: the model's own safety filter refused the output.\n * `class` distinguishes a deterministic block (copyright/likeness — retrying\n * the same request never helps) from `safety`, whose filter is known to be\n * non-deterministic for some models: `retried` says whether the worker\n * already spent its one extra attempt, and `suggestedProvider` — present\n * only when the catalog declares a fallback for the model that failed — is a\n * real model id the SAME prompt/references can be retried on.\n */\nexport type SafetyBlockHint = {\n kind: \"safety-block\"\n class: \"copyright\" | \"likeness\" | \"safety\"\n retried: boolean\n suggestedProvider?: string\n /**\n * Present when the provider refused the INPUT VIDEO itself — not the prompt,\n * a reference image or the output. Sending a different clip is the fix.\n */\n subject?: \"input_video\"\n}\n\n/**\n * A NODARO-side verdict, not a provider's: a job policy registered by the\n * deployment rejected the request (`hookPoint: \"request\"` — nothing ran, and\n * the call itself failed with {@link JobBlockedError}) or the finished output\n * (`hookPoint: \"result\"` — the result was blocked and never published).\n *\n * `reason` is USER-SAFE BY CONTRACT — the platform guarantees the policy's\n * machine text (scores, labels) never reaches it — so show it to the person\n * who made the request as-is. `policyId` identifies the deployment's policy,\n * not a Nodaro product feature. Only occurs on deployments that register a\n * job policy.\n */\nexport type PolicyBlockHint = {\n kind: \"policy-block\"\n policyId: string\n reason: string\n hookPoint: \"request\" | \"result\"\n}\n\n/**\n * The job ran out of credits partway: a step that reserves its own credits\n * (for example, the video a Cast Swap or trend run dispatches) was refused —\n * the balance could not cover it, or a plan or workspace cap was reached. The\n * job failed and its credits were refunded; ask the person to top up (or raise\n * the cap), then run it again.\n *\n * `code` is the refusal's own code, a lowercase snake_case token — for\n * example `insufficient_credits`, `free_video_limit`, `instance_cap_reached`,\n * `budget_exceeded`, `member_cap_exceeded` or `user_allowance_exceeded`. Treat\n * an unknown code like `insufficient_credits`.\n */\nexport type CreditsHint = {\n kind: \"credits\"\n code: string\n}\n\n/**\n * The provider refused the job's input video without naming a content-policy\n * class (its message is about the file, not a policy). Treat it like any\n * other failure — no fallback model is offered — except that the input to\n * change is known: send a different clip.\n */\nexport type InputRefusedHint = {\n kind: \"input-refused\"\n subject: \"input_video\"\n}\n\n/**\n * A job's `jobs.error_hint` (migration 376) — a user-safe, machine-readable\n * failure verdict, so a caller can act on it without parsing `error_message`\n * prose. One column, several verdict sources; `kind` is the discriminant.\n *\n * HAND-COPIED MIRROR of `ErrorHint` in the platform's\n * `backend/src/lib/safety-block.ts` (which names this file in its own\n * comment). Nothing links the two at build time: a new arm there has to be\n * pasted here verbatim in the same change, with a changeset.\n * `packages/client/dist/index.d.ts` is REBUILT, never hand-edited.\n */\nexport type JobErrorHint = SafetyBlockHint | PolicyBlockHint | CreditsHint | InputRefusedHint\n\n/**\n * The billing lifecycle of a job's credit reservation — `usage_logs.status`\n * for the job's `usage_log_id`. `null` when the job has no usage log (e.g. a\n * free run) or hasn't reserved credits yet.\n */\nexport type CreditStatus = \"reserved\" | \"committed\" | \"refunded\"\n\n/** A job owner's rating of their job — set with {@link JobsResource.rate}. */\nexport type JobRating = \"good\" | \"bad\"\n\n/**\n * The `rating` filter of {@link JobsResource.list}: one rating, any rating\n * (`\"rated\"`) or none (`\"unrated\"`).\n */\nexport type JobRatingFilter = JobRating | \"rated\" | \"unrated\"\n\n/**\n * Job record returned to non-admin SDK consumers. Field names are snake_case\n * to match the wire format (per the OpenAPI fix in Phase 1).\n *\n * Sensitive fields stripped server-side for non-admin callers:\n * `provider`, `provider_cost`, `display_cost`, `credits_actual`. USD\n * pricing is admin-only across api/sdk/mcp — non-admin consumers see\n * only the `credits` abstraction. Server-only nested job data (including\n * Recast's private remux base) is stripped for every caller, including admins.\n */\nexport interface Job {\n id: string\n status: JobStatus\n progress: number\n user_id: string\n input_data: unknown\n output_data: unknown\n error_message: string | null\n /** Present on a failed job the worker classified as a provider\n * content-policy block (`kind: \"safety-block\"`) or that a deployment's job\n * policy rejected (`kind: \"policy-block\"`); absent/null otherwise.\n * User-safe by construction — narrow on `kind` before reading the rest. */\n error_hint?: JobErrorHint | null\n /** PR9: the job's credit reservation lifecycle, derived server-side from\n * `usage_logs.status`. `null` when there is no usage log to report. Never\n * changes the meaning of `credits` (the reserved amount) below. */\n credit_status?: CreditStatus | null\n /** The credits the job itself HELD when it was accepted. Never changes — a\n * job can settle below it; read {@link Job.credits_charged} for what it cost. */\n credits: number | null\n /**\n * What the job actually cost once its hold settled, INCLUDING the steps it\n * ran: a job that runs other jobs for you (a Nodaro Motion run's reference\n * preparation, mask and video) is charged for each, and they are not listed\n * on their own. A step adds its charge once it settles. Can be lower than\n * {@link Job.credits_held} (the unused part goes back to the balance). `0`\n * when the run's own hold was refunded, plus any settled steps (a refunded\n * Nodaro Motion run whose reference and mask steps committed reads\n * `credit_status: \"refunded\"` with `credits_charged: 165`). `null` while the\n * job's own hold is still open (even when some steps have settled), when\n * nothing in the run was reserved, or when its steps could not be read for a\n * moment (unknown — never a lower figure). Sum this — not `credits` — to\n * total spend. Returned by `get()` and `list()`.\n */\n credits_charged?: number | null\n /** The run's hold: the job's own `credits` plus its steps' holds (equals `credits` for a job with no steps). */\n credits_held?: number | null\n /** What went back from `credits_held` once every hold in the run settled; `null` until then. */\n credits_released?: number | null\n job_type: string | null\n created_at: string\n started_at: string | null\n completed_at: string | null\n /**\n * Provenance: which kind of caller created the job — one of\n * `\"internal\" | \"mcp\" | \"app\" | \"cli\" | \"sdk\" | \"extension\" | \"web\" | \"api\"`.\n * `source_detail` narrows it (origin host, `extension/<name>` label,\n * `sdk/<version>`, MCP client name, developer-app id). Descriptive only;\n * lets a library view label or filter media by origin.\n */\n source?: string | null\n source_detail?: string | null\n /** The generation session this job was born in (the `sessionId` sent with\n * the generation request), or null. See `client.sessions`. */\n session_id?: string | null\n /**\n * With `list({ withSessions: true })`: every session that holds the job now,\n * each linkable — empty when it is in no session (General). Absent otherwise.\n */\n sessions?: JobSessionRef[]\n /**\n * When the job was deleted, on a job read from the Trash\n * (`client.trash.list()`). A deleted job is left out of every other read, so\n * this is otherwise absent or `null`.\n */\n deleted_at?: string | null\n /**\n * Whether the job's owner favorited it (`client.gallery.toggleFavorite`).\n * Returned by `get()` and `list()`. Absent from an older server, and when\n * the server could not read it for a moment — treat absent as unknown,\n * never as `false`.\n */\n favorited?: boolean\n /**\n * The owner's rating of the job ({@link JobsResource.rate}), or `null` when\n * unrated. Returned by `get()` and `list()`; absent like `favorited`.\n */\n rating?: JobRating | null\n}\n\nexport interface CancelJobResult {\n success: true\n cancelled: number\n /**\n * `true` when the job could not be stopped because its provider call is\n * already running — a metered LLM job's call, an external provider task. It\n * finishes and is charged only what it used.\n */\n inFlight?: boolean\n}\n\n/**\n * The kind of caller that created a job (`Job.source`). Hand-copied mirror of\n * `JOB_SOURCES` in the platform's `backend/src/lib/job-source.ts`.\n */\nexport type JobSource = \"internal\" | \"mcp\" | \"app\" | \"cli\" | \"sdk\" | \"extension\" | \"web\" | \"api\"\n\nexport interface DeleteJobResult {\n success: true\n}\n\n/** A session that holds a job now (`Job.sessions`). */\nexport interface JobSessionRef {\n id: string\n title: string | null\n /** The session's project, or `null` when it has none. */\n projectId: string | null\n}\n\nexport interface ListJobsParams {\n /** One status or several (a job matching any of them). An unknown status is a 400. */\n status?: JobStatus | readonly JobStatus[]\n /** Exact match on `input_data.type` — the route that created the job\n * (`\"llm-structured\"`, `\"video-analysis\"`, …). One value or several (up to 20). */\n type?: string | readonly string[]\n /** Exact match on `input_data.origin` — the client app that sent it. */\n origin?: string\n /** The surface that created the job (`Job.source`): `\"mcp\"` lists what your\n * MCP clients (Claude, ChatGPT, …) made. One value or several. */\n source?: JobSource | readonly JobSource[]\n /** `true`: only jobs you favorited; `false`: only jobs you did not. */\n favorited?: boolean\n /** Your rating: `\"good\"`, `\"bad\"`, any (`\"rated\"`) or none (`\"unrated\"`). */\n rating?: JobRatingFilter\n /** The jobs of one generate-image batch (`count` / `models`) — its `batchId`. */\n batchId?: string\n /**\n * The jobs a session of this project holds now — or, `\"none\"`, a session\n * with no project. Each job once, however many sessions hold it. Not with\n * `inSession: false`.\n */\n projectId?: string | \"none\"\n /**\n * `false`: the jobs no session holds now (General), whatever session they\n * were born in. `true`: the jobs at least one session holds.\n */\n inSession?: boolean\n /** `true`: each job carries `sessions`, the sessions that hold it now. */\n withSessions?: boolean\n /** Page size, 1–100 (server default 50). */\n limit?: number\n /** The previous page's `next`. */\n cursor?: string\n}\n\n/** What {@link JobsResource.rate} answers: the job's rating now. */\nexport interface RateJobResult {\n data: { jobId: string; rating: JobRating | null }\n}\n\n/**\n * {@link JobsResource.fromUpload}'s body: an image edited in the browser,\n * already stored with `client.uploads.upload`, and what it was made from.\n */\nexport interface JobFromUploadParams {\n /** The edited image's `assetId`, as `client.uploads.upload` returned it. */\n assetId: string\n /** The job whose image was edited. */\n sourceJobId?: string\n /** Which of `sourceJobId`'s images was edited, when it made several. Default: its `imageUrl`. */\n sourceImageUrl?: string\n /** The upload that was edited, when the source is not a job. Not with `sourceJobId`. */\n sourceAssetId?: string\n /** The editor's design state, stored with `client.uploads.uploadJson`, so the edit can be reopened. */\n editStateUrl?: string\n /** The generation session to file the job in. */\n sessionId?: string\n}\n\n/** A list filter value as the query string carries it: several are comma-separated. */\nfunction listParam(value: string | readonly string[] | undefined): string | undefined {\n if (value === undefined) return undefined\n return typeof value === \"string\" ? value : value.join(\",\")\n}\n\nexport interface ListJobsPage {\n /**\n * A page may hold fewer than `limit` rows — even none — and still carry a\n * `next`. Page on `next`, never on `data.length`.\n */\n data: Job[]\n /** Pass back as `cursor` for the next page; `null` on the last one. */\n next: string | null\n}\n\n/**\n * Lean job status returned by `GET /v1/jobs/:id/status`. Skips the\n * `input_data` JSONB and cost columns. Its `output_data` still goes\n * through the server-only nested-field redaction. Intended for poll loops that\n * only need progress/output/error, and when the job finished.\n */\nexport interface JobStatusResult {\n id: string\n status: JobStatus\n progress?: number\n output_data?: unknown\n error_message?: string | null\n /** PR9: see {@link Job.error_hint}. */\n error_hint?: JobErrorHint | null\n /** PR9: see {@link Job.credit_status}. */\n credit_status?: CreditStatus | null\n /** When the job finished, on the server's clock; null until it has. */\n completed_at?: string | null\n}\n\nexport class JobsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** Get a single job by ID. */\n get(id: string): Promise<{ data: Job }> {\n return this.client.request(\"GET\", `/v1/jobs/${encodeURIComponent(id)}`)\n }\n\n /**\n * Your jobs, newest first (`GET /v1/jobs`), cursor-paginated. `type` and\n * `origin` filter on the job's own `input_data`, which every job carries —\n * a client app lists its runs with `{ type: \"llm-structured\", origin: \"studio\" }`.\n * `status` and `type` take one value or a list; `favorited` and `rating`\n * filter on your own marks, `source` on the surface that created the job.\n * `projectId` / `inSession` filter on where the job is now (a project's\n * sessions, or General), and `withSessions` says which sessions each job is\n * in — for \"everything in this project\". Every filter combines with AND,\n * and each job carries `favorited` and `rating`. A deleted job is never\n * listed: read the Trash with `client.trash.list()`.\n */\n list(params: ListJobsParams = {}): Promise<ListJobsPage> {\n const { status, type, source, inSession, withSessions, ...rest } = params\n return this.client.request<ListJobsPage>(\"GET\", \"/v1/jobs\", {\n query: {\n ...rest,\n status: listParam(status),\n type: listParam(type),\n source: listParam(source),\n inSession: inSession === undefined ? undefined : String(inSession),\n withSessions: withSessions ? \"true\" : undefined,\n },\n })\n }\n\n /**\n * Record an image edited in the browser as a job (`POST /v1/jobs/from-upload`):\n * a completed, private, free `image-edit` job whose `output_data.imageUrl` is\n * the upload, linked to its source in `input_data` (`sourceJobId` /\n * `sourceAssetId`, `sourceImageUrl`). It then lists, rates, favorites and\n * files into a session like any image job. One upload is one job: the same\n * `assetId` again returns the same job. OAuth apps need the `assets:write`\n * scope. A deployment's job policy can refuse the image ({@link JobBlockedError}).\n */\n fromUpload(params: JobFromUploadParams): Promise<{ data: Job }> {\n return this.client.request<{ data: Job }>(\"POST\", \"/v1/jobs/from-upload\", { body: params })\n }\n\n /**\n * Rate one of your jobs `\"good\"` or `\"bad\"`, or clear the rating with\n * `null` (`PUT /v1/jobs/:id/rating`). Only the job's owner rates it — anyone\n * else's job is a `NotFoundError`. The rating reads back as `Job.rating`\n * and filters {@link list}. OAuth apps need the `assets:write` scope.\n */\n rate(id: string, rating: JobRating | null): Promise<RateJobResult> {\n return this.client.request<RateJobResult>(\"PUT\", `/v1/jobs/${encodeURIComponent(id)}/rating`, {\n body: { rating },\n })\n }\n\n /**\n * Get the lean status of a single job (poll-loop friendly).\n * Hits `GET /v1/jobs/:id/status` — returns only id/status/progress/\n * output_data/error_message, with far less wire/CPU cost than `get()`.\n * Same auth + ownership semantics as {@link get}.\n */\n getStatus(id: string): Promise<{ data: JobStatusResult }> {\n return this.client.request(\n \"GET\",\n `/v1/jobs/${encodeURIComponent(id)}/status`,\n )\n }\n\n /**\n * Cancel a job. Server route is `POST /v1/jobs/:jobId/cancel`.\n * Refunds any reserved credit holds. A running LLM job priced per model\n * (metered) whose call has already started answers\n * `{ success: true, cancelled: 0, inFlight: true }`: it finishes and is\n * charged only what it used. A job stopped before its call starts is\n * refunded, except for what an earlier attempt of the same job already used\n * (a retry after a billed attempt): that is charged.\n */\n cancel(id: string): Promise<CancelJobResult> {\n return this.client.request(\n \"POST\",\n `/v1/jobs/${encodeURIComponent(id)}/cancel`,\n )\n }\n\n /**\n * Delete a job: it goes to the Trash (`client.trash.list()`). It is left out\n * of every read from then on, stays restorable for 30 days ({@link restore},\n * back into the sessions it was in), and is then deleted for good, as a\n * delete always was (a copy saved to the Library stays). `{ forever: true }` deletes a job already in the Trash for good now;\n * on a live job it fails with a 409 `NodaroError` whose `code` is\n * `\"not_in_trash\"`. Only the job's owner (or an admin) may delete it; a job\n * that is still running keeps running — cancel it first when its worker\n * should stop ({@link cancel}). Nothing is refunded. OAuth apps need the\n * `assets:write` scope.\n */\n delete(id: string, options: { forever?: boolean } = {}): Promise<DeleteJobResult> {\n return this.client.request(\n \"DELETE\",\n `/v1/jobs/${encodeURIComponent(id)}`,\n options.forever ? { query: { forever: \"true\" } } : {},\n )\n }\n\n /**\n * Bring a deleted job back from the Trash: it reappears in every read and in\n * every session it was in. A job that is not in the Trash succeeds too.\n * OAuth apps need the `assets:write` scope.\n */\n restore(id: string): Promise<{ success: true }> {\n return this.client.request(\"POST\", `/v1/jobs/${encodeURIComponent(id)}/restore`)\n }\n}\n"]}
|
|
@@ -114,5 +114,5 @@ var PresetsResource = class {
|
|
|
114
114
|
};
|
|
115
115
|
|
|
116
116
|
exports.PresetsResource = PresetsResource;
|
|
117
|
-
//# sourceMappingURL=chunk-
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
117
|
+
//# sourceMappingURL=chunk-Q45PC4YD.cjs.map
|
|
118
|
+
//# sourceMappingURL=chunk-Q45PC4YD.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/node-presets.ts"],"names":[],"mappings":";;;AAuJO,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,EAMpB,MAAM,KAAK,QAAA,EAA0C;AACnD,IAAA,MAAM,KAAK,QAAA,GAAW,CAAA,UAAA,EAAa,kBAAA,CAAmB,QAAQ,CAAC,CAAA,CAAA,GAAK,EAAA;AACpE,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAgC,KAAA,EAAO,CAAA,gBAAA,EAAmB,EAAE,CAAA,CAAE,CAAA;AAC5F,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,WAAW,QAAA,EAA+C;AAC9D,IAAA,MAAM,KAAK,QAAA,GAAW,CAAA,UAAA,EAAa,kBAAA,CAAmB,QAAQ,CAAC,CAAA,CAAA,GAAK,EAAA;AACpE,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAqC,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A,MACzG,OAAO,EAAE,QAAA,EAAU,MAAM,QAAA,EAAU,QAAA,EAAU,MAAM,QAAA;AAAS,KAC7D,CAAA;AACD,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,YAAY,KAAA,EAA6D;AAC7E,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAmC,QAAQ,wBAAA,EAA0B,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAClH,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,WAAA,CAAY,EAAA,EAAY,KAAA,EAA6D;AACzF,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAmC,SAAS,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC5H,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,YAAY,EAAA,EAAwC;AACxD,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAqC,UAAU,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAC/H,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-Q45PC4YD.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { FactoryPreset } from \"@nodaro/prompts/presets\"\n\n/**\n * A user's saved custom preset (`GET /v1/node-presets`). Mirrors the backend's\n * camelCase row shape. `data` is captured node config — merge it into a node's\n * data when building/running a workflow to \"apply\" the preset.\n */\nexport interface NodePreset {\n id: string\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n groupId?: string\n tags: string[]\n sortOrder: number\n /**\n * How many connected reference images the preset works from (0 = none),\n * counted from the `{image:N}` tokens in its prompt. Absent from servers that\n * predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /** The example picture stored with the preset, or null. */\n previewUrl?: string | null\n createdAt: string\n updatedAt: string\n}\n\n/** A user's preset folder/section (`GET /v1/node-preset-groups`). */\nexport interface NodePresetGroup {\n id: string\n nodeType: string\n name: string\n kind: \"folder\" | \"section\"\n sortOrder: number\n createdAt: string\n updatedAt: string\n}\n\n/**\n * One built-in preset as `GET /v1/node-presets/factory` serves it: the\n * catalog entry plus what a client needs to present it.\n */\nexport interface FactoryPresetEntry extends FactoryPreset {\n /**\n * How many connected reference images the preset works from (0 = none):\n * Reference Sheet, Portrait Transformations, Edits and every template using\n * `{image:N}` need at least one. Absent from servers that predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /**\n * An example picture of what the preset makes — an absolute URL on the\n * server you asked — or null while the preset has none.\n */\n previewUrl?: string | null\n /**\n * The same picture at its two sizes for an `<img srcset>` — the tile picture\n * at 512w and the full-screen one at up to 1024w. Present only when the\n * preset has both; absent from servers that predate it.\n */\n previewSrcSet?: string\n}\n\n/**\n * Result of `GET /v1/node-presets/factory` — the built-in (factory) catalog for\n * a node type.\n */\nexport interface FactoryPresetsResult {\n data: FactoryPresetEntry[]\n}\n\n/** `POST /v1/node-presets` body. */\nexport interface CreateNodePresetInput {\n /** The node type the preset configures, e.g. `\"generate-image\"`. */\n nodeType: string\n /** Unique per node type (case-insensitive); a duplicate answers 409 `name_taken`. */\n name: string\n description?: string\n /** Node config (≤ 64 KB). Runtime keys (results, job ids, labels) are stripped. */\n data: Record<string, unknown>\n /** One of your preset groups, or null for none. */\n groupId?: string | null\n tags?: string[]\n sortOrder?: number\n /**\n * An example picture: an image stored on this platform (an upload or a\n * generated result) that already exists. Anything else answers 400.\n */\n previewUrl?: string | null\n}\n\n/** `PATCH /v1/node-presets/:id` body — every field optional; `previewUrl: null` removes the picture. */\nexport type UpdateNodePresetInput = Partial<Omit<CreateNodePresetInput, \"nodeType\">>\n\n/** One entry of `POST /v1/node-presets/import` (the `presets export` envelope's entries fit). */\nexport interface ImportNodePresetInput {\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n previewUrl?: string | null\n}\n\n/** `POST /v1/node-presets/reorder` body. */\nexport interface ReorderNodePresetsInput {\n groups?: Array<{ id: string; sortOrder: number }>\n /** `groupId` moves the preset into one of your groups (null = out of any group). */\n presets?: Array<{ id: string; groupId?: string | null; sortOrder: number }>\n}\n\n/** A favorite: a factory preset id (`\"generate-image/character-board\"`) or one of your preset ids. */\nexport interface NodePresetFavoriteInput {\n nodeType: string\n presetId: string\n}\n\n/** `POST /v1/node-preset-groups` body. */\nexport interface CreateNodePresetGroupInput {\n nodeType: string\n name: string\n /** A collapsible `\"folder\"` (default) or a flat `\"section\"` header. */\n kind?: \"folder\" | \"section\"\n sortOrder?: number\n}\n\n/** `PATCH /v1/node-preset-groups/:id` body. */\nexport interface UpdateNodePresetGroupInput {\n name?: string\n sortOrder?: number\n}\n\n/**\n * Node presets — reusable, named node configurations: your own presets and\n * folders, your favorites, and the built-in factory catalog.\n *\n * To *use* a preset, take its `data` and merge it into a node's config when you\n * create/update a workflow. `needsImage` / `minReferences` say how many photos\n * it works from; `previewUrl` is an example picture (null when there is none).\n *\n * The factory catalog (`listFactory`) is public: no token needed. Reads of\n * your own library need the `presets:read` scope for an OAuth app token;\n * writes (create, update, delete, import, reorder, favorites, groups) need\n * `assets:write`. Your own API key needs neither — but a key limited to some\n * workflows cannot reach your own presets (it reads the factory catalog as\n * anyone can).\n */\nexport class PresetsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/node-presets` → your custom presets, newest first. Pass `nodeType`\n * (e.g. `\"generate-image\"`) to filter to one node type.\n */\n async list(nodeType?: string): Promise<NodePreset[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePreset[] }>(\"GET\", `/v1/node-presets${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-preset-groups` → your preset folders/sections, in display\n * order. Pass `nodeType` to filter to one node type.\n */\n async listGroups(nodeType?: string): Promise<NodePresetGroup[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePresetGroup[] }>(\"GET\", `/v1/node-preset-groups${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-presets/factory` → the built-in catalog for `nodeType`. These\n * ship with the app (no account needed to exist), so they're a good starting\n * point for \"what configs are available\".\n *\n * Login is optional: the catalog is public, so this works on a client with\n * no credential at all (`auth: { getToken: async () => null }`) — show the\n * names, example pictures (`previewUrl`) and photo counts (`minReferences`,\n * `needsImage`) to a visitor who is not signed in, and ask for a login only\n * when they generate. Your OWN presets (`list()`) still need a token.\n */\n listFactory(nodeType: string): Promise<FactoryPresetsResult> {\n return this.client.request<FactoryPresetsResult>(\n \"GET\",\n `/v1/node-presets/factory?nodeType=${encodeURIComponent(nodeType)}`,\n )\n }\n\n /** `POST /v1/node-presets` → the new preset. */\n async create(input: CreateNodePresetInput): Promise<NodePreset> {\n const res = await this.client.request<{ data: NodePreset }>(\"POST\", \"/v1/node-presets\", { body: input })\n return res.data\n }\n\n /**\n * `PATCH /v1/node-presets/:id` → the updated preset. Pass the `updatedAt` you\n * read as `expectedUpdatedAt` to refuse (409 `conflict`) a change made\n * elsewhere since.\n */\n async update(id: string, patch: UpdateNodePresetInput, opts: { expectedUpdatedAt?: string } = {}): Promise<NodePreset> {\n const body = opts.expectedUpdatedAt ? { ...patch, expectedUpdatedAt: opts.expectedUpdatedAt } : patch\n const res = await this.client.request<{ data: NodePreset }>(\"PATCH\", `/v1/node-presets/${encodeURIComponent(id)}`, { body })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/:id` (404 when it is not yours). `expectedUpdatedAt` as on `update`. */\n async delete(id: string, opts: { expectedUpdatedAt?: string } = {}): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-presets/${encodeURIComponent(id)}`, {\n query: { expectedUpdatedAt: opts.expectedUpdatedAt },\n })\n return res.data\n }\n\n /**\n * `POST /v1/node-presets/import` — up to 500 presets in one call. A name you\n * already use gets an \"(imported N)\" suffix; a preset whose data is empty\n * after stripping runtime keys is skipped.\n */\n async import(presets: ImportNodePresetInput[]): Promise<{ imported: number }> {\n const res = await this.client.request<{ data: { imported: number } }>(\"POST\", \"/v1/node-presets/import\", { body: { presets } })\n return res.data\n }\n\n /** `POST /v1/node-presets/reorder` — positions (and group membership) for many presets and groups at once. */\n async reorder(input: ReorderNodePresetsInput): Promise<{ ok: true }> {\n const res = await this.client.request<{ data: { ok: true } }>(\"POST\", \"/v1/node-presets/reorder\", { body: input })\n return res.data\n }\n\n /** `GET /v1/node-presets/favorites` → your favorite preset ids for `nodeType`, newest first. */\n async favorites(nodeType: string): Promise<string[]> {\n const res = await this.client.request<{ data: string[] }>(\"GET\", \"/v1/node-presets/favorites\", { query: { nodeType } })\n return res.data\n }\n\n /** `POST /v1/node-presets/favorites` — idempotent. */\n async addFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"POST\", \"/v1/node-presets/favorites\", { body: input })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/favorites` — idempotent. */\n async removeFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", \"/v1/node-presets/favorites\", {\n query: { nodeType: input.nodeType, presetId: input.presetId },\n })\n return res.data\n }\n\n /** `POST /v1/node-preset-groups` → the new folder or section. */\n async createGroup(input: CreateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"POST\", \"/v1/node-preset-groups\", { body: input })\n return res.data\n }\n\n /** `PATCH /v1/node-preset-groups/:id` → the renamed or moved group. */\n async updateGroup(id: string, patch: UpdateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"PATCH\", `/v1/node-preset-groups/${encodeURIComponent(id)}`, {\n body: patch,\n })\n return res.data\n }\n\n /** `DELETE /v1/node-preset-groups/:id` — its presets move out of the group; none are deleted. */\n async deleteGroup(id: string): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-preset-groups/${encodeURIComponent(id)}`)\n return res.data\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/jobs.ts"],"names":[],"mappings":";AA8SA,SAAS,UAAU,KAAA,EAAmE;AACpF,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,KAAA,CAAM,KAAK,GAAG,CAAA;AAC3D;AAgCO,IAAM,eAAN,MAAmB;AAAA,EACxB,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,IAAI,EAAA,EAAoC;AACtC,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,KAAA,EAAO,YAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,IAAA,CAAK,MAAA,GAAyB,EAAC,EAA0B;AACvD,IAAA,MAAM,EAAE,QAAQ,IAAA,EAAM,MAAA,EAAQ,WAAW,YAAA,EAAc,GAAG,MAAK,GAAI,MAAA;AACnE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAsB,KAAA,EAAO,UAAA,EAAY;AAAA,MAC1D,KAAA,EAAO;AAAA,QACL,GAAG,IAAA;AAAA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAA,CAAO,EAAA,EAAY,OAAA,GAAiC,EAAC,EAA6B;AAChF,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,QAAA;AAAA,MACA,CAAA,SAAA,EAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA;AAAA,MAClC,OAAA,CAAQ,UAAU,EAAE,KAAA,EAAO,EAAE,OAAA,EAAS,MAAA,EAAO,EAAE,GAAI;AAAC,KACtD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAQ,EAAA,EAAwC;AAC9C,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAQ,MAAA,EAAQ,YAAY,kBAAA,CAAmB,EAAE,CAAC,CAAA,QAAA,CAAU,CAAA;AAAA,EACjF;AACF","file":"chunk-THLTFB6I.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * A job's lifecycle status. Hand-copied mirror of `JOB_STATUSES` in the\n * platform's `backend/src/lib/job-status.ts` — nothing links the two at build\n * time, so a new member has to be added here in the same change.\n *\n * `pending_review` is IN-FLIGHT, NOT TERMINAL: a job policy registered by the\n * deployment held the output for a human reviewer. Treat it like `processing`\n * in a `switch` — keep waiting, do not re-run — and it resolves to `completed`\n * (approved), `failed` (rejected, carrying an `error_hint` with\n * `kind: \"policy-block\"`) or `cancelled` (a held job is cancellable like any\n * in-flight job). `credit_status` reads `\"reserved\"` for the whole hold. Only\n * appears on deployments that register a job policy; `runAndWait` throws\n * {@link JobHeldError} on the first held tick rather than waiting it out.\n */\nexport type JobStatus =\n | \"pending\"\n | \"queued\"\n | \"processing\"\n | \"pending_review\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n\n/**\n * A PROVIDER's verdict: the model's own safety filter refused the output.\n * `class` distinguishes a deterministic block (copyright/likeness — retrying\n * the same request never helps) from `safety`, whose filter is known to be\n * non-deterministic for some models: `retried` says whether the worker\n * already spent its one extra attempt, and `suggestedProvider` — present\n * only when the catalog declares a fallback for the model that failed — is a\n * real model id the SAME prompt/references can be retried on.\n */\nexport type SafetyBlockHint = {\n kind: \"safety-block\"\n class: \"copyright\" | \"likeness\" | \"safety\"\n retried: boolean\n suggestedProvider?: string\n /**\n * Present when the provider refused the INPUT VIDEO itself — not the prompt,\n * a reference image or the output. Sending a different clip is the fix.\n */\n subject?: \"input_video\"\n}\n\n/**\n * A NODARO-side verdict, not a provider's: a job policy registered by the\n * deployment rejected the request (`hookPoint: \"request\"` — nothing ran, and\n * the call itself failed with {@link JobBlockedError}) or the finished output\n * (`hookPoint: \"result\"` — the result was blocked and never published).\n *\n * `reason` is USER-SAFE BY CONTRACT — the platform guarantees the policy's\n * machine text (scores, labels) never reaches it — so show it to the person\n * who made the request as-is. `policyId` identifies the deployment's policy,\n * not a Nodaro product feature. Only occurs on deployments that register a\n * job policy.\n */\nexport type PolicyBlockHint = {\n kind: \"policy-block\"\n policyId: string\n reason: string\n hookPoint: \"request\" | \"result\"\n}\n\n/**\n * The job ran out of credits partway: a step that reserves its own credits\n * (for example, the video a Cast Swap or trend run dispatches) was refused —\n * the balance could not cover it, or a plan or workspace cap was reached. The\n * job failed and its credits were refunded; ask the person to top up (or raise\n * the cap), then run it again.\n *\n * `code` is the refusal's own code, a lowercase snake_case token — for\n * example `insufficient_credits`, `free_video_limit`, `instance_cap_reached`,\n * `budget_exceeded`, `member_cap_exceeded` or `user_allowance_exceeded`. Treat\n * an unknown code like `insufficient_credits`.\n */\nexport type CreditsHint = {\n kind: \"credits\"\n code: string\n}\n\n/**\n * The provider refused the job's input video without naming a content-policy\n * class (its message is about the file, not a policy). Treat it like any\n * other failure — no fallback model is offered — except that the input to\n * change is known: send a different clip.\n */\nexport type InputRefusedHint = {\n kind: \"input-refused\"\n subject: \"input_video\"\n}\n\n/**\n * A job's `jobs.error_hint` (migration 376) — a user-safe, machine-readable\n * failure verdict, so a caller can act on it without parsing `error_message`\n * prose. One column, several verdict sources; `kind` is the discriminant.\n *\n * HAND-COPIED MIRROR of `ErrorHint` in the platform's\n * `backend/src/lib/safety-block.ts` (which names this file in its own\n * comment). Nothing links the two at build time: a new arm there has to be\n * pasted here verbatim in the same change, with a changeset.\n * `packages/client/dist/index.d.ts` is REBUILT, never hand-edited.\n */\nexport type JobErrorHint = SafetyBlockHint | PolicyBlockHint | CreditsHint | InputRefusedHint\n\n/**\n * The billing lifecycle of a job's credit reservation — `usage_logs.status`\n * for the job's `usage_log_id`. `null` when the job has no usage log (e.g. a\n * free run) or hasn't reserved credits yet.\n */\nexport type CreditStatus = \"reserved\" | \"committed\" | \"refunded\"\n\n/** A job owner's rating of their job — set with {@link JobsResource.rate}. */\nexport type JobRating = \"good\" | \"bad\"\n\n/**\n * The `rating` filter of {@link JobsResource.list}: one rating, any rating\n * (`\"rated\"`) or none (`\"unrated\"`).\n */\nexport type JobRatingFilter = JobRating | \"rated\" | \"unrated\"\n\n/**\n * Job record returned to non-admin SDK consumers. Field names are snake_case\n * to match the wire format (per the OpenAPI fix in Phase 1).\n *\n * Sensitive fields stripped server-side for non-admin callers:\n * `provider`, `provider_cost`, `display_cost`, `credits_actual`. USD\n * pricing is admin-only across api/sdk/mcp — non-admin consumers see\n * only the `credits` abstraction. Server-only nested job data (including\n * Recast's private remux base) is stripped for every caller, including admins.\n */\nexport interface Job {\n id: string\n status: JobStatus\n progress: number\n user_id: string\n input_data: unknown\n output_data: unknown\n error_message: string | null\n /** Present on a failed job the worker classified as a provider\n * content-policy block (`kind: \"safety-block\"`) or that a deployment's job\n * policy rejected (`kind: \"policy-block\"`); absent/null otherwise.\n * User-safe by construction — narrow on `kind` before reading the rest. */\n error_hint?: JobErrorHint | null\n /** PR9: the job's credit reservation lifecycle, derived server-side from\n * `usage_logs.status`. `null` when there is no usage log to report. Never\n * changes the meaning of `credits` (the reserved amount) below. */\n credit_status?: CreditStatus | null\n /** The credits the job itself HELD when it was accepted. Never changes — a\n * job can settle below it; read {@link Job.credits_charged} for what it cost. */\n credits: number | null\n /**\n * What the job actually cost once its hold settled, INCLUDING the steps it\n * ran: a job that runs other jobs for you (a Nodaro Motion run's reference\n * preparation, mask and video) is charged for each, and they are not listed\n * on their own. A step adds its charge once it settles. Can be lower than\n * {@link Job.credits_held} (the unused part goes back to the balance). `0`\n * when the run's own hold was refunded, plus any settled steps (a refunded\n * Nodaro Motion run whose reference and mask steps committed reads\n * `credit_status: \"refunded\"` with `credits_charged: 165`). `null` while the\n * job's own hold is still open (even when some steps have settled), when\n * nothing in the run was reserved, or when its steps could not be read for a\n * moment (unknown — never a lower figure). Sum this — not `credits` — to\n * total spend. Returned by `get()` and `list()`.\n */\n credits_charged?: number | null\n /** The run's hold: the job's own `credits` plus its steps' holds (equals `credits` for a job with no steps). */\n credits_held?: number | null\n /** What went back from `credits_held` once every hold in the run settled; `null` until then. */\n credits_released?: number | null\n job_type: string | null\n created_at: string\n started_at: string | null\n completed_at: string | null\n /**\n * Provenance: which kind of caller created the job — one of\n * `\"internal\" | \"mcp\" | \"app\" | \"cli\" | \"sdk\" | \"extension\" | \"web\" | \"api\"`.\n * `source_detail` narrows it (origin host, `extension/<name>` label,\n * `sdk/<version>`, MCP client name, developer-app id). Descriptive only;\n * lets a library view label or filter media by origin.\n */\n source?: string | null\n source_detail?: string | null\n /** The generation session this job was born in (the `sessionId` sent with\n * the generation request), or null. See `client.sessions`. */\n session_id?: string | null\n /**\n * With `list({ withSessions: true })`: every session that holds the job now,\n * each linkable — empty when it is in no session (General). Absent otherwise.\n */\n sessions?: JobSessionRef[]\n /**\n * When the job was deleted, on a job read from the Trash\n * (`client.trash.list()`). A deleted job is left out of every other read, so\n * this is otherwise absent or `null`.\n */\n deleted_at?: string | null\n /**\n * Whether the job's owner favorited it (`client.gallery.toggleFavorite`).\n * Returned by `get()` and `list()`. Absent from an older server, and when\n * the server could not read it for a moment — treat absent as unknown,\n * never as `false`.\n */\n favorited?: boolean\n /**\n * The owner's rating of the job ({@link JobsResource.rate}), or `null` when\n * unrated. Returned by `get()` and `list()`; absent like `favorited`.\n */\n rating?: JobRating | null\n}\n\nexport interface CancelJobResult {\n success: true\n cancelled: number\n /**\n * `true` when the job could not be stopped because its provider call is\n * already running — a metered LLM job's call, an external provider task. It\n * finishes and is charged only what it used.\n */\n inFlight?: boolean\n}\n\n/**\n * The kind of caller that created a job (`Job.source`). Hand-copied mirror of\n * `JOB_SOURCES` in the platform's `backend/src/lib/job-source.ts`.\n */\nexport type JobSource = \"internal\" | \"mcp\" | \"app\" | \"cli\" | \"sdk\" | \"extension\" | \"web\" | \"api\"\n\nexport interface DeleteJobResult {\n success: true\n}\n\n/** A session that holds a job now (`Job.sessions`). */\nexport interface JobSessionRef {\n id: string\n title: string | null\n /** The session's project, or `null` when it has none. */\n projectId: string | null\n}\n\nexport interface ListJobsParams {\n /** One status or several (a job matching any of them). An unknown status is a 400. */\n status?: JobStatus | readonly JobStatus[]\n /** Exact match on `input_data.type` — the route that created the job\n * (`\"llm-structured\"`, `\"video-analysis\"`, …). One value or several (up to 20). */\n type?: string | readonly string[]\n /** Exact match on `input_data.origin` — the client app that sent it. */\n origin?: string\n /** The surface that created the job (`Job.source`): `\"mcp\"` lists what your\n * MCP clients (Claude, ChatGPT, …) made. One value or several. */\n source?: JobSource | readonly JobSource[]\n /** `true`: only jobs you favorited; `false`: only jobs you did not. */\n favorited?: boolean\n /** Your rating: `\"good\"`, `\"bad\"`, any (`\"rated\"`) or none (`\"unrated\"`). */\n rating?: JobRatingFilter\n /** The jobs of one generate-image batch (`count` / `models`) — its `batchId`. */\n batchId?: string\n /**\n * The jobs a session of this project holds now — or, `\"none\"`, a session\n * with no project. Each job once, however many sessions hold it. Not with\n * `inSession: false`.\n */\n projectId?: string | \"none\"\n /**\n * `false`: the jobs no session holds now (General), whatever session they\n * were born in. `true`: the jobs at least one session holds.\n */\n inSession?: boolean\n /** `true`: each job carries `sessions`, the sessions that hold it now. */\n withSessions?: boolean\n /** Page size, 1–100 (server default 50). */\n limit?: number\n /** The previous page's `next`. */\n cursor?: string\n}\n\n/** What {@link JobsResource.rate} answers: the job's rating now. */\nexport interface RateJobResult {\n data: { jobId: string; rating: JobRating | null }\n}\n\n/**\n * {@link JobsResource.fromUpload}'s body: an image edited in the browser,\n * already stored with `client.uploads.upload`, and what it was made from.\n */\nexport interface JobFromUploadParams {\n /** The edited image's `assetId`, as `client.uploads.upload` returned it. */\n assetId: string\n /** The job whose image was edited. */\n sourceJobId?: string\n /** Which of `sourceJobId`'s images was edited, when it made several. Default: its `imageUrl`. */\n sourceImageUrl?: string\n /** The upload that was edited, when the source is not a job. Not with `sourceJobId`. */\n sourceAssetId?: string\n /** The editor's design state, stored with `client.uploads.uploadJson`, so the edit can be reopened. */\n editStateUrl?: string\n /** The generation session to file the job in. */\n sessionId?: string\n}\n\n/** A list filter value as the query string carries it: several are comma-separated. */\nfunction listParam(value: string | readonly string[] | undefined): string | undefined {\n if (value === undefined) return undefined\n return typeof value === \"string\" ? value : value.join(\",\")\n}\n\nexport interface ListJobsPage {\n /**\n * A page may hold fewer than `limit` rows — even none — and still carry a\n * `next`. Page on `next`, never on `data.length`.\n */\n data: Job[]\n /** Pass back as `cursor` for the next page; `null` on the last one. */\n next: string | null\n}\n\n/**\n * Lean job status returned by `GET /v1/jobs/:id/status`. Skips the\n * `input_data` JSONB and cost columns. Its `output_data` still goes\n * through the server-only nested-field redaction. Intended for poll loops that\n * only need progress/output/error, and when the job finished.\n */\nexport interface JobStatusResult {\n id: string\n status: JobStatus\n progress?: number\n output_data?: unknown\n error_message?: string | null\n /** PR9: see {@link Job.error_hint}. */\n error_hint?: JobErrorHint | null\n /** PR9: see {@link Job.credit_status}. */\n credit_status?: CreditStatus | null\n /** When the job finished, on the server's clock; null until it has. */\n completed_at?: string | null\n}\n\nexport class JobsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** Get a single job by ID. */\n get(id: string): Promise<{ data: Job }> {\n return this.client.request(\"GET\", `/v1/jobs/${encodeURIComponent(id)}`)\n }\n\n /**\n * Your jobs, newest first (`GET /v1/jobs`), cursor-paginated. `type` and\n * `origin` filter on the job's own `input_data`, which every job carries —\n * a client app lists its runs with `{ type: \"llm-structured\", origin: \"studio\" }`.\n * `status` and `type` take one value or a list; `favorited` and `rating`\n * filter on your own marks, `source` on the surface that created the job.\n * `projectId` / `inSession` filter on where the job is now (a project's\n * sessions, or General), and `withSessions` says which sessions each job is\n * in — for \"everything in this project\". Every filter combines with AND,\n * and each job carries `favorited` and `rating`. A deleted job is never\n * listed: read the Trash with `client.trash.list()`.\n */\n list(params: ListJobsParams = {}): Promise<ListJobsPage> {\n const { status, type, source, inSession, withSessions, ...rest } = params\n return this.client.request<ListJobsPage>(\"GET\", \"/v1/jobs\", {\n query: {\n ...rest,\n status: listParam(status),\n type: listParam(type),\n source: listParam(source),\n inSession: inSession === undefined ? undefined : String(inSession),\n withSessions: withSessions ? \"true\" : undefined,\n },\n })\n }\n\n /**\n * Record an image edited in the browser as a job (`POST /v1/jobs/from-upload`):\n * a completed, private, free `image-edit` job whose `output_data.imageUrl` is\n * the upload, linked to its source in `input_data` (`sourceJobId` /\n * `sourceAssetId`, `sourceImageUrl`). It then lists, rates, favorites and\n * files into a session like any image job. One upload is one job: the same\n * `assetId` again returns the same job. OAuth apps need the `assets:write`\n * scope. A deployment's job policy can refuse the image ({@link JobBlockedError}).\n */\n fromUpload(params: JobFromUploadParams): Promise<{ data: Job }> {\n return this.client.request<{ data: Job }>(\"POST\", \"/v1/jobs/from-upload\", { body: params })\n }\n\n /**\n * Rate one of your jobs `\"good\"` or `\"bad\"`, or clear the rating with\n * `null` (`PUT /v1/jobs/:id/rating`). Only the job's owner rates it — anyone\n * else's job is a `NotFoundError`. The rating reads back as `Job.rating`\n * and filters {@link list}. OAuth apps need the `assets:write` scope.\n */\n rate(id: string, rating: JobRating | null): Promise<RateJobResult> {\n return this.client.request<RateJobResult>(\"PUT\", `/v1/jobs/${encodeURIComponent(id)}/rating`, {\n body: { rating },\n })\n }\n\n /**\n * Get the lean status of a single job (poll-loop friendly).\n * Hits `GET /v1/jobs/:id/status` — returns only id/status/progress/\n * output_data/error_message, with far less wire/CPU cost than `get()`.\n * Same auth + ownership semantics as {@link get}.\n */\n getStatus(id: string): Promise<{ data: JobStatusResult }> {\n return this.client.request(\n \"GET\",\n `/v1/jobs/${encodeURIComponent(id)}/status`,\n )\n }\n\n /**\n * Cancel a job. Server route is `POST /v1/jobs/:jobId/cancel`.\n * Refunds any reserved credit holds. A running LLM job priced per model\n * (metered) whose call has already started answers\n * `{ success: true, cancelled: 0, inFlight: true }`: it finishes and is\n * charged only what it used. A job stopped before its call starts is\n * refunded, except for what an earlier attempt of the same job already used\n * (a retry after a billed attempt): that is charged.\n */\n cancel(id: string): Promise<CancelJobResult> {\n return this.client.request(\n \"POST\",\n `/v1/jobs/${encodeURIComponent(id)}/cancel`,\n )\n }\n\n /**\n * Delete a job: it goes to the Trash (`client.trash.list()`). It is left out\n * of every read from then on, stays restorable for 30 days ({@link restore},\n * back into the sessions it was in), and is then deleted for good, as a\n * delete always was (a copy saved to the Library stays). `{ forever: true }` deletes a job already in the Trash for good now;\n * on a live job it fails with a 409 `NodaroError` whose `code` is\n * `\"not_in_trash\"`. Only the job's owner (or an admin) may delete it; a job\n * that is still running keeps running — cancel it first when its worker\n * should stop ({@link cancel}). Nothing is refunded. OAuth apps need the\n * `assets:write` scope.\n */\n delete(id: string, options: { forever?: boolean } = {}): Promise<DeleteJobResult> {\n return this.client.request(\n \"DELETE\",\n `/v1/jobs/${encodeURIComponent(id)}`,\n options.forever ? { query: { forever: \"true\" } } : {},\n )\n }\n\n /**\n * Bring a deleted job back from the Trash: it reappears in every read and in\n * every session it was in. A job that is not in the Trash succeeds too.\n * OAuth apps need the `assets:write` scope.\n */\n restore(id: string): Promise<{ success: true }> {\n return this.client.request(\"POST\", `/v1/jobs/${encodeURIComponent(id)}/restore`)\n }\n}\n"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var models = require('@nodaro/shared/models');
|
|
4
|
+
|
|
3
5
|
// src/resources/cast-swap.ts
|
|
4
6
|
var CastSwapResource = class {
|
|
5
7
|
constructor(client) {
|
|
@@ -20,13 +22,15 @@ var CastSwapResource = class {
|
|
|
20
22
|
});
|
|
21
23
|
}
|
|
22
24
|
/** Quote a run before starting it (`POST /v1/cast-swap/estimate`); spends nothing. */
|
|
23
|
-
estimate(params) {
|
|
24
|
-
|
|
25
|
+
async estimate(params) {
|
|
26
|
+
const quote = await this.client.request("POST", "/v1/cast-swap/estimate", { body: params });
|
|
27
|
+
const engine = models.nodaroMotionEngineFrom(quote?.engine);
|
|
28
|
+
return engine && engine !== quote.engine ? { ...quote, engine } : quote;
|
|
25
29
|
}
|
|
26
30
|
/**
|
|
27
31
|
* Quote finishing a run at Full Quality (`POST
|
|
28
32
|
* /v1/cast-swap/:jobId/full-quality/estimate`); spends nothing. `jobId` is a
|
|
29
|
-
* finished Nodaro Motion
|
|
33
|
+
* finished Nodaro Motion Prism DRAFT run, or a finished Nodaro Motion Pulse
|
|
30
34
|
* run at 720p (a Nodaro Motion or trend run); the quote's `kind` says whether it is the same take
|
|
31
35
|
* re-rendered or a new take. The quote
|
|
32
36
|
* does not look for a Full Quality already running: when one is,
|
|
@@ -39,7 +43,7 @@ var CastSwapResource = class {
|
|
|
39
43
|
/**
|
|
40
44
|
* Finish a run at Full Quality (`POST /v1/cast-swap/:jobId/full-quality`):
|
|
41
45
|
* at 1080p, with the clip's audio, as a new job linked to the run — a
|
|
42
|
-
* Nodaro Motion
|
|
46
|
+
* Nodaro Motion Prism draft's own take re-rendered, or a new Nodaro Motion Pulse take from a
|
|
43
47
|
* 720p run's inputs (the quote's `kind`). SPENDS CREDITS: quote it first with
|
|
44
48
|
* {@link fullQualityEstimate}. Answers 202 `{ jobId }`, or 200
|
|
45
49
|
* `{ jobId, existing: true }` when this run's Full Quality is already
|
|
@@ -55,5 +59,5 @@ var CastSwapResource = class {
|
|
|
55
59
|
};
|
|
56
60
|
|
|
57
61
|
exports.CastSwapResource = CastSwapResource;
|
|
58
|
-
//# sourceMappingURL=chunk-
|
|
59
|
-
//# sourceMappingURL=chunk-
|
|
62
|
+
//# sourceMappingURL=chunk-TY2S25W5.cjs.map
|
|
63
|
+
//# sourceMappingURL=chunk-TY2S25W5.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/cast-swap.ts"],"names":["nodaroMotionEngineFrom"],"mappings":";;;;;AAqdO,IAAM,mBAAN,MAAuB;AAAA,EAC5B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASpB,GAAA,CAAI,QAAwB,OAAA,EAA6E;AACvG,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,eAAA,EAAiB;AAAA,MAClD,IAAA,EAAM,MAAA;AAAA,MACN,GAAI,OAAA,EAAS,cAAA,GAAiB,EAAE,OAAA,EAAS,EAAE,iBAAA,EAAmB,OAAA,CAAQ,cAAA,EAAe,EAAE,GAAI;AAAC,KAC7F,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,SAAS,MAAA,EAAmD;AAChE,IAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAA0B,QAAQ,wBAAA,EAA0B,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA;AAE5G,IAAA,MAAM,MAAA,GAASA,6BAAA,CAAuB,KAAA,EAAO,MAAM,CAAA;AACnD,IAAA,OAAO,MAAA,IAAU,WAAW,KAAA,CAAM,MAAA,GAAS,EAAE,GAAG,KAAA,EAAO,QAAO,GAAI,KAAA;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,oBAAoB,KAAA,EAAqD;AACvE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,CAAA,cAAA,EAAiB,kBAAA,CAAmB,KAAK,CAAC,CAAA,sBAAA,CAAA,EAA0B,EAAE,IAAA,EAAM,IAAI,CAAA;AAAA,EACrH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,WAAA,CAAY,KAAA,EAAe,MAAA,GAAoC,EAAC,EAAuC;AACrG,IAAA,MAAM,IAAA,GAAO,OAAO,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,GAAI,EAAC;AACjF,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,EAAQ,CAAA,cAAA,EAAiB,kBAAA,CAAmB,KAAK,CAAC,CAAA,aAAA,CAAA,EAAiB,EAAE,IAAA,EAAM,CAAA;AAAA,EACxG;AACF","file":"chunk-TY2S25W5.cjs","sourcesContent":["import { nodaroMotionEngineFrom } from \"@nodaro/shared/models\"\nimport type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Nodaro Motion (the `castSwap` resource; routes `/v1/cast-swap`) — replace\n * the people, pets, products and/or the location in a short video with your\n * own references, keeping its motion, framing, timing and sound (the clip's\n * audio is kept, and the result is the clip's length).\n *\n * Before the video, each person, pet and product role's photos are turned\n * into one clean reference picture by an image model. This costs extra\n * credits (`breakdown.references` in the estimate), charged when it runs, even\n * if the video then fails; it adds about a minute, falls back to your own\n * photos if it fails, and is turned off with `prepareReferences: false`.\n * Locations are not prepared.\n *\n * Engines: a run is made on Nodaro Motion Prism (`engine` left out, or\n * `\"motion-prism\"`) or Nodaro Motion Pulse (`\"motion-pulse\"`). Pulse renders 720p\n * (its default) or 1080p and has no draft; it makes a new take guided by the\n * clip and pictures, so its Full Quality is a new take at 1080p rather than\n * the same take re-rendered (`CastSwapFullQualityEstimate.kind`).\n *\n * How the clip is prepared for the video model (for one, whether faces are\n * hidden first, and whether a refused clip is retried) is set by Nodaro for\n * each engine; a run cannot change it. `faceMasking` is no longer read\n * (deprecated: accepted and ignored).\n *\n * Cloud edition only: `/v1/cast-swap` is served by the cloud plugin and 404s\n * on self-hosted installs. `run()` answers 202 with a job id; follow it with\n * `client.jobs.get(jobId)` / `client.jobs.getStatus(jobId)` like any other job.\n *\n * Repeats: pass `{ idempotencyKey }` to `run()` and it is sent as the\n * `Idempotency-Key` header. A repeat with the same key within the credit\n * guard's dedup window (about 10 s) answers 200 `{ jobId, deduped: true }` with\n * an `X-Dedup-Hit` header; a later one answers 202 with the first run's\n * `jobId`. Nothing new is started or charged.\n *\n * Refusals (thrown as a `NodaroError` subclass; body `{ error: { code, message } }`), before\n * anything is charged: 400 `validation_error` (the body: no role with images,\n * no reference and no `prePrompt` or `postPrompt`, more roles of a kind\n * than allowed, more than 30 images in all, `draft: true` above 480p, a\n * `prePrompt` or `postPrompt` over 4,000 characters); on Nodaro Motion Pulse,\n * `draft_unsupported` (`draft: true`), `resolution_unsupported` (480p),\n * `output_format_unsupported` (a MOV edit output) and `too_many_images` (more\n * than 10 images in the run, across every role and fixed reference);\n * `raw_reference_token` (also in a reference's `line`),\n * `invalid_role_mention` (also any `{role:N}` in a reference's `line`),\n * `unsafe_url`, `video_unreadable`, `clip_out_of_range` (4–30 s),\n * `preview_out_of_range`, `no_roles_in_preview` (a preview with every role\n * `inPreview: false`, always refused even with a prompt, or with no role kept\n * in it that has images and no `prePrompt` or `postPrompt`), `prompt_too_long`\n * (the prompt would build too long: a `{role:N}` reads as the role's name when\n * it sends no images; Nodaro Motion Pulse's cap is 8,000 characters); 401; 402 `insufficient_credits` (`run()` only); 404\n * (a `sessionId` you may not use, `run()` only); 422 `job_blocked` (`run()`\n * only); 503 `host_too_old` (both); 503 `estimate_unavailable` (`estimate()`\n * only).\n */\n\n/**\n * The engine a Nodaro Motion run is made on, by its public id. Left out =\n * `\"motion-prism\"`.\n *\n * - `\"motion-prism\"` (Nodaro Motion Prism): 480p (the default, a draft unless\n * `draft: false`), 720p or 1080p; Full Quality re-renders a draft's own take\n * at 1080p.\n * - `\"motion-pulse\"` (Nodaro Motion Pulse): 720p (the default) or 1080p, never a\n * draft (`draft: true` answers 400 `draft_unsupported`); Full Quality makes a\n * new take at 1080p from a completed 720p run's inputs. A preview is still\n * 4 s from `previewStart`.\n */\nexport type CastSwapEngine = \"motion-prism\" | \"motion-pulse\"\n\n/**\n * The engine ids an older client sent: the earlier public ids (`\"motion-pro\"`\n * = `\"motion-prism\"`, `\"motion-lite\"` = `\"motion-pulse\"`) and the internal\n * ones (`\"seedance-2-5\"`, `\"kling-4\"`). Still accepted in a request; never\n * returned.\n * @deprecated use {@link CastSwapEngine}.\n */\nexport type CastSwapEngineLegacyId = \"motion-pro\" | \"motion-lite\" | \"seedance-2-5\" | \"kling-4\"\n\n/**\n * Where a Nodaro Motion Pulse run cuts the clip to whole seconds (Pulse renders\n * whole seconds; asked for more than the clip, it would stretch the motion):\n * - `\"cut-end\"` (the default): drop the fraction of a second at its end;\n * - `\"cut-start\"`: drop it at its start.\n */\nexport type CastSwapMotionLength = \"cut-end\" | \"cut-start\"\n\n/** @deprecated use {@link CastSwapMotionLength}. */\nexport type CastSwapKlingLength = CastSwapMotionLength\n\n/** Whether a swapped subject takes this trait from the references (`\"new\"`) or keeps the video's (`\"original\"`). */\nexport type CastSwapTraitSource = \"new\" | \"original\"\n\n/**\n * Preview-only settings, on every role kind; a full run (`preview` not `true`)\n * ignores both.\n */\nexport interface CastSwapRolePreviewSettings {\n /** The name used instead of `name` in a preview. Same rules as `name` (1–200 characters). */\n previewName?: string\n /**\n * `false` leaves this role out of the preview: its reference images are not\n * sent, not prepared and not charged, and a `{role:N}` naming it reads as its\n * `previewName`, else its `name`. Default `true`. A preview with every role\n * left out (always refused, even with a prompt), or with no role kept in it\n * that has images and no pre / post prompt, answers 400 `no_roles_in_preview`.\n */\n inPreview?: boolean\n}\n\n/** A person in the video to recast. */\nexport interface CastSwapPersonRole extends CastSwapRolePreviewSettings {\n kind: \"person\"\n /** How the person is told apart in the video, e.g. `\"the woman that attacks\"`. */\n name: string\n /** 0–3 images of ONE person. Empty or `null` keeps the original person. */\n images: string[] | null\n /** Body from the references or the video. Default `\"new\"`. */\n body?: CastSwapTraitSource\n /** Outfit from the references or the video. Default `\"new\"`. */\n outfit?: CastSwapTraitSource\n /** Hairstyle and haircut from the references or the video. Default `\"new\"`. */\n hair?: CastSwapTraitSource\n}\n\n/** The place the video happens in. */\nexport interface CastSwapLocationRole extends CastSwapRolePreviewSettings {\n kind: \"location\"\n /** How the place is named. Default `\"the setting\"`. */\n name?: string\n /** 0–3 images of ONE place. Empty or `null` keeps the original place. */\n images: string[] | null\n}\n\n/** An animal in the video to recast. */\nexport interface CastSwapPetRole extends CastSwapRolePreviewSettings {\n kind: \"pet\"\n /** How the animal is told apart in the video, e.g. `\"the dog\"`. */\n name: string\n /** 0–3 images of ONE animal. Empty or `null` keeps the original animal. */\n images: string[] | null\n /** Body (shape, size and build) from the references or the video. Default `\"new\"`. */\n body?: CastSwapTraitSource\n /** Coat (fur, colors and markings) from the references or the video. Default `\"new\"`. */\n coat?: CastSwapTraitSource\n}\n\n/** An object in the video to recast. */\nexport interface CastSwapProductRole extends CastSwapRolePreviewSettings {\n kind: \"product\"\n /** How the object is told apart in the video, e.g. `\"the can\"`. */\n name: string\n /** 0–3 images of ONE product. Empty or `null` keeps the original object. */\n images: string[] | null\n /** Shape and proportions from the references or the video. Default `\"new\"`. */\n shape?: CastSwapTraitSource\n /** Finish (colors, materials, label and markings) from the references or the video. Default `\"new\"`. */\n finish?: CastSwapTraitSource\n}\n\nexport type CastSwapRole = CastSwapPersonRole | CastSwapLocationRole | CastSwapPetRole | CastSwapProductRole\n\n/**\n * A fixed reference: 1–3 images of ONE thing that no role replaces, and the\n * line that says what it is (`\"the glass she drinks from\"`). Sent as given,\n * never prepared; its images count toward the 30.\n */\nexport interface CastSwapReference {\n /** 1–3 http(s) image URLs of one thing. */\n images: string[]\n /**\n * What it is, 1–500 characters. `{image}` in the line stands for this\n * reference's first image (`\"Use {image} for the sky\"`); a line without it\n * gets it appended. A `{role:N}` or a raw `{image:` / `{video:` / `{audio:`\n * token answers 400.\n */\n line: string\n}\n\n/**\n * @deprecated Nodaro sets this per engine; a run's `faceMasking` is ignored.\n */\nexport interface CastSwapFaceMaskingZone {\n leftPct?: number\n rightPct?: number\n topPct?: number\n bottomPct?: number\n}\n\n/**\n * @deprecated Nodaro sets how the clip is prepared for the video model, per\n * engine; a run cannot change it. A `faceMasking` sent is accepted and\n * ignored (no error), so older code keeps working unchanged.\n */\nexport interface CastSwapFaceMasking {\n mode: \"off\" | \"always\" | \"auto\"\n fill?: \"blur\" | \"depth\"\n minFaceHeightPct?: number\n maxFaceHeightPct?: number\n zone?: CastSwapFaceMaskingZone | null\n blurStrengthPct?: number\n threshold?: number\n}\n\n/** The body of `POST /v1/cast-swap` and `POST /v1/cast-swap/estimate`. */\nexport interface CastSwapParams {\n /** The source clip, 4–30 seconds. */\n videoUrl: string\n /**\n * Who and what to swap: at most 6 person roles, 1 location role, 3 pet roles\n * and 3 product roles, with at most 30 images in all. A role with no images\n * is skipped (that subject or place stays as in the video). At least one role\n * with images, or a `prePrompt` or `postPrompt`, is required.\n */\n roles: CastSwapRole[]\n /**\n * Fixed references (at most 5): things the video should show that no role\n * replaces, each with the line that names it. Their images count toward the\n * 30. A reference alone is enough for a run (no role needs images).\n */\n references?: CastSwapReference[]\n /**\n * Your own words placed at the start of the prompt, before the role\n * instructions; at most 4,000 characters. Mention a role as `{role:N}`, as in\n * `postPrompt`; the same 400 refusals apply (an N outside 1..`roles.length`,\n * a raw `{image:` / `{video:` / `{audio:` token).\n */\n prePrompt?: string\n /**\n * Extra instructions in your own words, at most 4,000 characters. Mention a\n * role as `{role:N}`, where N is its 1-based position in `roles`\n * (`{role:1}` is `roles[0]`; empty roles count).\n *\n * The route answers 400, before charging, for an N outside 1..`roles.length`,\n * for a raw `{image:` / `{video:` / `{audio:` token in the pre or post prompt\n * or a role's `name`, for a clip outside 4–30 s, and for a preview past the clip's\n * end (`previewStart + 4` > its length).\n */\n postPrompt?: string\n /** `true` runs on 4 seconds of the clip, starting at `previewStart`: a cheap check of the roles and choices. */\n preview?: boolean\n /** Where the preview starts, in seconds. Default 0. */\n previewStart?: number\n /**\n * The engine (see {@link CastSwapEngine}). Default `\"motion-prism\"`. The job\n * records it in `input_data.engine`, and a completed job's output in its\n * `engine`. The ids an older client sent ({@link CastSwapEngineLegacyId})\n * are still accepted.\n */\n engine?: CastSwapEngine | CastSwapEngineLegacyId\n /**\n * Nodaro Motion Pulse only (Prism ignores it): which end of the clip is cut to\n * whole seconds (see {@link CastSwapMotionLength}). Default `\"cut-end\"`.\n */\n motionLength?: CastSwapMotionLength\n /** @deprecated use {@link motionLength} (still accepted). */\n klingLength?: CastSwapKlingLength\n /**\n * The output resolution. Nodaro Motion Prism: `\"480p\"` (default), `\"720p\"` or\n * `\"1080p\"`. Nodaro Motion Pulse: `\"720p\"` (default) or `\"1080p\"`; `\"480p\"`\n * answers 400.\n */\n resolution?: \"480p\" | \"720p\" | \"1080p\"\n /**\n * Render as a draft (Nodaro Motion Prism only). Defaults to `true` at 480p and\n * `false` above it; `true` with `\"720p\"` or `\"1080p\"` answers 400 (draft is\n * 480p only). Nodaro Motion Pulse has no draft: `true` answers 400\n * `draft_unsupported`.\n */\n draft?: boolean\n /**\n * Turn each person, pet and product role's photos into one clean reference\n * picture before the video (extra credits, shown in `breakdown.references`;\n * about a minute longer; falls back to your own photos if it fails).\n * Default `true`.\n */\n prepareReferences?: boolean\n /**\n * Ignored: Nodaro sets how the clip is prepared, per engine. Accepted (no\n * error) so older code keeps working.\n * @deprecated leave it out.\n */\n faceMasking?: CastSwapFaceMasking\n /**\n * `\"draft\"` means 480p draft.\n * @deprecated use `resolution` + `draft`.\n */\n quality?: \"draft\"\n /** A generation session to file the result in. */\n sessionId?: string\n /** The client app that sent the run (stored on the job as `input_data.origin`). */\n origin?: string\n}\n\n/** What a run would cost, in credits. */\nexport interface CastSwapEstimate {\n /**\n * The engine the run would use, by its public id (absent from an older\n * server = `\"motion-prism\"`). An id an older server answers is read as the\n * public id it names.\n */\n engine?: CastSwapEngine\n /**\n * What is held when the run starts. The run is charged what it actually\n * costs, which is expected to be `expectedCredits`.\n */\n totalCredits: number\n /**\n * The charge the run is expected to come to. Never above `totalCredits`\n * (on Nodaro Motion Pulse it equals it: Pulse renders exactly the length\n * asked for, so the hold is what it settles at). Absent from an older\n * server: read `totalCredits` then.\n */\n expectedCredits?: number\n /**\n * The parts of the quote, by name, for display only:\n * - `base`: the run itself (its base fee). A server before Cast Swap 0.396.0\n * names it `castSwap` instead: read `base`, else `castSwap`;\n * - `references`: preparing the reference pictures (0 when\n * `prepareReferences` is off or there is nothing to prepare);\n * - `motion`: what the video holds (on Nodaro Motion Pulse, what it costs);\n * - `motionExpected`: what the video is expected to be charged, never above\n * `motion` (Nodaro Motion Prism);\n * - `privacy`: preparing the clip, when the engine's setting does. In both\n * totals when it always runs; outside both when it is the retry\n * (`privacyCredits`).\n *\n * `motion` and `motionExpected` are alternatives, so the parts sum to more\n * than either total: read `totalCredits` and `expectedCredits`, never the\n * sum. Other parts may appear.\n */\n breakdown: {\n base?: number\n /** @deprecated read {@link base} (an older server answered this name for the same part). */\n castSwap?: number\n references: number\n motion?: number\n motionExpected?: number\n privacy?: number\n } & Record<string, number>\n /**\n * The extra credits charged only if the video model refuses the clip and\n * the run is retried (Nodaro's setting for the engine decides whether it\n * does). Not in `totalCredits` or `expectedCredits`; `run()` needs credits\n * for both the hold and this (else 402).\n */\n privacyCredits?: number\n /** @deprecated read {@link privacyCredits} (an older server answered this name). */\n maskingCredits?: number\n /**\n * `true` when the video is made at Auto length (every Nodaro Motion Prism\n * run): the final charge is expected to come out lower than `totalCredits`,\n * at about `expectedCredits`. `false` on Nodaro Motion Pulse.\n */\n settlesLower: boolean\n}\n\n/** Per-call options for {@link CastSwapResource.run}. */\nexport interface CastSwapRunOptions {\n /**\n * Sent as the `Idempotency-Key` header, unchanged (the SDK checks nothing;\n * an empty string sends no header, like no key).\n * The server takes 8–200 characters and answers 400 for any other length.\n * Reuse the same value when retrying the same run: within about 10 s the\n * repeat answers 200 `{ jobId, deduped: true }`, later 202 with the first\n * run's `jobId`. Nothing new is started or charged.\n */\n idempotencyKey?: string\n}\n\n/**\n * What a Full Quality version would be: `\"same-take\"` re-renders a Nodaro\n * Motion Prism draft's own take at 1080p; `\"new-take\"` makes a new Nodaro Motion Pulse take at\n * 1080p from a 720p run's inputs (it will not match the 720p run frame for\n * frame). The 720p run or draft stays either way.\n */\nexport type CastSwapFullQualityKind = \"same-take\" | \"new-take\"\n\n/**\n * What a Full Quality version of a run would cost\n * (`POST /v1/cast-swap/:jobId/full-quality/estimate`): a Nodaro Motion Prism\n * draft, or a completed Nodaro Motion Pulse run at 720p.\n */\nexport interface CastSwapFullQualityEstimate {\n /**\n * Which Full Quality this is ({@link CastSwapFullQualityKind}), so it can\n * be worded right. Absent from an older server: `\"same-take\"`.\n */\n kind?: CastSwapFullQualityKind\n /** The quote in credits: `breakdown.base` plus the 1080p render (same take) or the new take. */\n totalCredits: number\n /**\n * The parts of the quote, by name, for display only: `base` (the Full\n * Quality job's own steps; a server before Cast Swap 0.396.0 names it\n * `castSwap` instead: read `base`, else `castSwap`), and `motionHd` (a same\n * take: the 1080p render, 0 when an earlier try of this draft already\n * finished that render, which is then reused) or `motion` (a new take).\n */\n breakdown: {\n base?: number\n /** @deprecated read {@link base} (an older server answered this name for the same part). */\n castSwap?: number\n motionHd?: number\n motion?: number\n } & Record<string, number>\n /** ISO time until which the run can be finished at Full Quality (7 days after it completed). */\n availableUntil: string\n}\n\n/** Options for {@link CastSwapResource.fullQuality}. */\nexport interface CastSwapFullQualityParams {\n /** A generation session to file the Full Quality result in. */\n sessionId?: string\n}\n\n/** The Full Quality job (`POST /v1/cast-swap/:jobId/full-quality`). */\nexport interface CastSwapFullQualityResult {\n jobId: string\n /** `true` when this run's Full Quality was already running or done: that job is answered, nothing new is started or charged. */\n existing?: boolean\n}\n\n/**\n * The `code` of a Full Quality refusal (`NodaroError.code`), all before\n * anything is charged:\n * - `unauthorized` (401): no authenticated user;\n * - `not_found` (404): not your job, or not a Nodaro Motion run; also a\n * `sessionId` you may not use;\n * - `not_completed` (409): the run has not finished;\n * - `not_a_draft` (409): the run is neither a Nodaro Motion Prism draft nor a\n * Nodaro Motion Pulse run at 720p (a Pulse run at 1080p is already Full Quality);\n * - `draft_expired` (410): more than 7 days after the draft completed, or\n * the draft can no longer be finished at Full Quality;\n * - `full_quality_pending` (409, `details.retryable: true`): not final — an\n * earlier try's 1080p render of this draft is being reviewed, or has not\n * started yet; try again later (once the review ends). The only refusal\n * that ends on its own;\n * - `full_quality_unavailable` (409): final — nothing kept to re-render, no\n * readable completion time, or the 1080p finalize refuses this draft; on\n * the start only, also \"failed too many times\" (every try failed) or no\n * try can be started for this run;\n * - `insufficient_credits` (402), or in a workspace `budget_exceeded`,\n * `member_cap_exceeded` or `user_allowance_exceeded`;\n * - `job_blocked` (422): the request was blocked by the job policy;\n * - `job_read_failed` (503, retryable), `estimate_unavailable` (503, try\n * again shortly), `host_too_old` (503).\n *\n * Open-ended: a code not listed here may still arrive.\n */\nexport type CastSwapFullQualityRefusalCode =\n | \"unauthorized\"\n | \"not_found\"\n | \"not_completed\"\n | \"not_a_draft\"\n | \"draft_expired\"\n | \"full_quality_pending\"\n | \"full_quality_unavailable\"\n | \"insufficient_credits\"\n | \"budget_exceeded\"\n | \"member_cap_exceeded\"\n | \"user_allowance_exceeded\"\n | \"job_blocked\"\n | \"job_read_failed\"\n | \"estimate_unavailable\"\n | \"host_too_old\"\n | (string & {})\n\nexport class CastSwapResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * Start a Nodaro Motion run (`POST /v1/cast-swap`, 202 `{ jobId }`). Returns the\n * job to follow. With `options.idempotencyKey` (sent as the\n * `Idempotency-Key` header; 8–200 characters, else 400) a repeat with the\n * same key within about 10 s answers 200 `{ jobId, deduped: true }`, a later\n * one 202 with the first run's `jobId`; nothing new starts.\n */\n run(params: CastSwapParams, options?: CastSwapRunOptions): Promise<{ jobId: string; deduped?: boolean }> {\n return this.client.request(\"POST\", \"/v1/cast-swap\", {\n body: params,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n })\n }\n\n /** Quote a run before starting it (`POST /v1/cast-swap/estimate`); spends nothing. */\n async estimate(params: CastSwapParams): Promise<CastSwapEstimate> {\n const quote = await this.client.request<CastSwapEstimate>(\"POST\", \"/v1/cast-swap/estimate\", { body: params })\n // An older server names the engine by an earlier id: answered as the public id it names.\n const engine = nodaroMotionEngineFrom(quote?.engine)\n return engine && engine !== quote.engine ? { ...quote, engine } : quote\n }\n\n /**\n * Quote finishing a run at Full Quality (`POST\n * /v1/cast-swap/:jobId/full-quality/estimate`); spends nothing. `jobId` is a\n * finished Nodaro Motion Prism DRAFT run, or a finished Nodaro Motion Pulse\n * run at 720p (a Nodaro Motion or trend run); the quote's `kind` says whether it is the same take\n * re-rendered or a new take. The quote\n * does not look for a Full Quality already running: when one is,\n * {@link fullQuality} answers it (`existing: true`) and charges nothing.\n * Refusals: {@link CastSwapFullQualityRefusalCode}.\n */\n fullQualityEstimate(jobId: string): Promise<CastSwapFullQualityEstimate> {\n return this.client.request(\"POST\", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality/estimate`, { body: {} })\n }\n\n /**\n * Finish a run at Full Quality (`POST /v1/cast-swap/:jobId/full-quality`):\n * at 1080p, with the clip's audio, as a new job linked to the run — a\n * Nodaro Motion Prism draft's own take re-rendered, or a new Nodaro Motion Pulse take from a\n * 720p run's inputs (the quote's `kind`). SPENDS CREDITS: quote it first with\n * {@link fullQualityEstimate}. Answers 202 `{ jobId }`, or 200\n * `{ jobId, existing: true }` when this run's Full Quality is already\n * running or done (one per run; a failed one may be asked again). Follow\n * the job with `client.jobs.get(jobId)`. No `Idempotency-Key` is taken: the\n * server keys the job by the draft. The new job keeps the draft's origin.\n * Refusals: {@link CastSwapFullQualityRefusalCode}.\n */\n fullQuality(jobId: string, params: CastSwapFullQualityParams = {}): Promise<CastSwapFullQualityResult> {\n const body = params.sessionId !== undefined ? { sessionId: params.sessionId } : {}\n return this.client.request(\"POST\", `/v1/cast-swap/${encodeURIComponent(jobId)}/full-quality`, { body })\n }\n}\n"]}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// src/resources/billing.ts
|
|
2
|
+
var BillingResource = class {
|
|
3
|
+
constructor(client) {
|
|
4
|
+
this.client = client;
|
|
5
|
+
}
|
|
6
|
+
client;
|
|
7
|
+
/**
|
|
8
|
+
* `GET /v1/billing/plans` → the plans and credit packs on sale, with their
|
|
9
|
+
* prices. Public: works with no credential, the same for every caller.
|
|
10
|
+
* Nodaro Cloud only — a self-hosted instance answers 404. Throws on `403
|
|
11
|
+
* self_serve_disabled` (this deployment does not sell to its users) and on
|
|
12
|
+
* `503` (`stripe_not_configured`, or prices briefly unavailable).
|
|
13
|
+
*/
|
|
14
|
+
plans() {
|
|
15
|
+
return this.client.request("GET", "/v1/billing/plans");
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `GET /v1/billing/subscription` → the account's latest subscription
|
|
19
|
+
* (`null` when it never subscribed) and the tier its entitlements follow.
|
|
20
|
+
* Match `effectiveTier` to a {@link BillingPlan} `id` to mark the current
|
|
21
|
+
* plan (no match: pay-as-you-go, or a tier not on sale). Needs a signed-in
|
|
22
|
+
* session, a personal API token without a workflow limit, or an app's OAuth
|
|
23
|
+
* token. Nodaro Cloud only — a self-hosted instance answers 404.
|
|
24
|
+
*/
|
|
25
|
+
subscription() {
|
|
26
|
+
return this.client.request("GET", "/v1/billing/subscription");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* `GET /v1/billing/surface` → how this deployment bills: whether it meters
|
|
30
|
+
* at all (`providerId !== "none"`) and in which unit costs display. Public,
|
|
31
|
+
* every edition.
|
|
32
|
+
*/
|
|
33
|
+
async surface() {
|
|
34
|
+
const res = await this.client.request("GET", "/v1/billing/surface");
|
|
35
|
+
return res.data;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* `GET /v1/billing/account` → the caller's plan and balance as the
|
|
39
|
+
* deployment's billing provider reports them, in its display unit. `null`
|
|
40
|
+
* when the provider could not answer — not a zero balance. Every edition.
|
|
41
|
+
*/
|
|
42
|
+
async account() {
|
|
43
|
+
const res = await this.client.request("GET", "/v1/billing/account");
|
|
44
|
+
return res.data;
|
|
45
|
+
}
|
|
46
|
+
// ── Signed-in session only (ForbiddenError on an API key or an app token) ──
|
|
47
|
+
/**
|
|
48
|
+
* `GET /v1/billing/transactions` → the account's credit purchases, newest
|
|
49
|
+
* first: subscription payments and credit packs, each with its Stripe
|
|
50
|
+
* receipt link when one was captured. **Signed-in session only.**
|
|
51
|
+
*/
|
|
52
|
+
async purchases() {
|
|
53
|
+
const res = await this.client.request("GET", "/v1/billing/transactions");
|
|
54
|
+
return res.data;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* `GET /v1/billing/invoices` → every payment as a document, newest first:
|
|
58
|
+
* a Stripe invoice (with its PDF) for each subscription payment, a hosted
|
|
59
|
+
* receipt for each credit pack or load. **Signed-in session only.**
|
|
60
|
+
*/
|
|
61
|
+
async invoices() {
|
|
62
|
+
const res = await this.client.request("GET", "/v1/billing/invoices");
|
|
63
|
+
return res.data;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* `GET /v1/billing/payment-method` → the card and the billing details on
|
|
67
|
+
* file with Stripe; both `null` for an account that has not bought yet
|
|
68
|
+
* (never an error). **Signed-in session only.**
|
|
69
|
+
*/
|
|
70
|
+
async paymentMethod() {
|
|
71
|
+
const res = await this.client.request("GET", "/v1/billing/payment-method");
|
|
72
|
+
return res.data;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* `GET /v1/billing/auto-recharge` → the automatic top-up setting: when the
|
|
76
|
+
* balance falls under `thresholdCredits`, `amountUsd` is loaded from the
|
|
77
|
+
* saved card. **Signed-in session only.**
|
|
78
|
+
*/
|
|
79
|
+
async autoRecharge() {
|
|
80
|
+
const res = await this.client.request("GET", "/v1/billing/auto-recharge");
|
|
81
|
+
return res.data;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* `PUT /v1/billing/auto-recharge` → changes the automatic top-up. Enabling
|
|
85
|
+
* needs both `thresholdCredits` (100–100,000) and `amountUsd` (a whole
|
|
86
|
+
* amount in the load range); the server answers `400` otherwise. A change
|
|
87
|
+
* clears the failure count. **Signed-in session only.**
|
|
88
|
+
*/
|
|
89
|
+
async setAutoRecharge(input) {
|
|
90
|
+
const res = await this.client.request("PUT", "/v1/billing/auto-recharge", { body: input });
|
|
91
|
+
return res.data;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `POST /v1/billing/create-checkout-session` → a Stripe Checkout page for a
|
|
95
|
+
* plan or a credit pack (`priceId` from {@link BillingPlansResult}): send
|
|
96
|
+
* the person to `url`. Pass `returnPath` (a path on your own origin, such
|
|
97
|
+
* as `"/billing"`) to have Stripe bring them back to your app with
|
|
98
|
+
* `checkout=success` or `checkout=cancelled` in the query; without it the
|
|
99
|
+
* Nodaro app's own pages are used. `ForbiddenError` with the code
|
|
100
|
+
* `self_serve_disabled` on a deployment that does not sell to its users.
|
|
101
|
+
* **Signed-in session only.**
|
|
102
|
+
*/
|
|
103
|
+
async checkout(input) {
|
|
104
|
+
const res = await this.client.request("POST", "/v1/billing/create-checkout-session", { body: input });
|
|
105
|
+
return res.data;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* `POST /v1/billing/create-load-session` → a Stripe Checkout page that loads
|
|
109
|
+
* a whole amount (`amountUsd`, within {@link BillingPlansResult.topUpRange})
|
|
110
|
+
* as credits at the packs' rate; `credits` is what it will grant. The card
|
|
111
|
+
* is saved for auto top-up. `returnPath` as in {@link checkout}.
|
|
112
|
+
* **Signed-in session only.**
|
|
113
|
+
*/
|
|
114
|
+
async loadCredits(input) {
|
|
115
|
+
const res = await this.client.request("POST", "/v1/billing/create-load-session", { body: input });
|
|
116
|
+
return res.data;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* `POST /v1/billing/manage-subscription` → a Stripe Customer Portal page
|
|
120
|
+
* (the card, the billing address, the invoices, cancelling): send the person
|
|
121
|
+
* to `url`; `returnPath` is where the portal's Back goes (default the app's
|
|
122
|
+
* `/billing`). `NotFoundError` before a first purchase — Stripe does not
|
|
123
|
+
* know the account yet. **Signed-in session only.**
|
|
124
|
+
*/
|
|
125
|
+
async portal(input = {}) {
|
|
126
|
+
const res = await this.client.request("POST", "/v1/billing/manage-subscription", { body: input });
|
|
127
|
+
return res.data;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* `POST /v1/billing/change-plan` → moves the active subscription to another
|
|
131
|
+
* plan's price (`newPriceId`, a subscription price from the plans list),
|
|
132
|
+
* prorated by Stripe; the new tier applies at once. `NotFoundError` with no
|
|
133
|
+
* active subscription; `400` on a pack's price or the current one.
|
|
134
|
+
* **Signed-in session only.**
|
|
135
|
+
*/
|
|
136
|
+
async changePlan(input) {
|
|
137
|
+
const res = await this.client.request("POST", "/v1/billing/change-plan", { body: input });
|
|
138
|
+
return res.data;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export { BillingResource };
|
|
143
|
+
//# sourceMappingURL=chunk-WYYDWJFF.js.map
|
|
144
|
+
//# sourceMappingURL=chunk-WYYDWJFF.js.map
|