@nodaro/sdk 2.51.0 → 2.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/{chunk-YXVMQEJX.js → chunk-35CNQ3WW.js} +2 -2
  2. package/dist/chunk-35CNQ3WW.js.map +1 -0
  3. package/dist/{chunk-TY2S25W5.cjs → chunk-65VIIZEF.cjs} +2 -2
  4. package/dist/{chunk-TY2S25W5.cjs.map → chunk-65VIIZEF.cjs.map} +1 -1
  5. package/dist/{chunk-HPSENMVN.cjs → chunk-74N3EL5F.cjs} +14 -10
  6. package/dist/chunk-74N3EL5F.cjs.map +1 -0
  7. package/dist/{chunk-OCRUDBPG.js → chunk-DV6GTEX5.js} +2 -2
  8. package/dist/{chunk-OCRUDBPG.js.map → chunk-DV6GTEX5.js.map} +1 -1
  9. package/dist/{chunk-XISHBW5I.js → chunk-F4MFMHTQ.js} +3 -3
  10. package/dist/{chunk-XISHBW5I.js.map → chunk-F4MFMHTQ.js.map} +1 -1
  11. package/dist/chunk-ISKOLJJJ.cjs +4 -0
  12. package/dist/chunk-ISKOLJJJ.cjs.map +1 -0
  13. package/dist/chunk-K6BWJ7ZY.js +3 -0
  14. package/dist/chunk-K6BWJ7ZY.js.map +1 -0
  15. package/dist/{chunk-OMX7JBGY.cjs → chunk-KQTPJ6R4.cjs} +3 -3
  16. package/dist/{chunk-OMX7JBGY.cjs.map → chunk-KQTPJ6R4.cjs.map} +1 -1
  17. package/dist/chunk-LR5TGCJP.js +31 -0
  18. package/dist/chunk-LR5TGCJP.js.map +1 -0
  19. package/dist/{chunk-E5MJK3W5.cjs → chunk-NWMO4MHE.cjs} +2 -2
  20. package/dist/chunk-NWMO4MHE.cjs.map +1 -0
  21. package/dist/{chunk-6FZN3QQO.cjs → chunk-TVPYDC5T.cjs} +2 -2
  22. package/dist/chunk-TVPYDC5T.cjs.map +1 -0
  23. package/dist/chunk-UIDVH3GP.cjs +33 -0
  24. package/dist/chunk-UIDVH3GP.cjs.map +1 -0
  25. package/dist/{chunk-EC6MC46Y.js → chunk-WD556UAW.js} +10 -6
  26. package/dist/chunk-WD556UAW.js.map +1 -0
  27. package/dist/{chunk-WYYDWJFF.js → chunk-ZVKEPVDQ.js} +2 -2
  28. package/dist/chunk-ZVKEPVDQ.js.map +1 -0
  29. package/dist/entries/billing.cjs +2 -2
  30. package/dist/entries/billing.d.cts +7 -0
  31. package/dist/entries/billing.d.ts +7 -0
  32. package/dist/entries/billing.js +1 -1
  33. package/dist/entries/cast-swap.cjs +2 -2
  34. package/dist/entries/cast-swap.d.cts +15 -1
  35. package/dist/entries/cast-swap.d.ts +15 -1
  36. package/dist/entries/cast-swap.js +1 -1
  37. package/dist/entries/client.cjs +11 -10
  38. package/dist/entries/client.d.cts +3 -0
  39. package/dist/entries/client.d.ts +3 -0
  40. package/dist/entries/client.js +6 -5
  41. package/dist/entries/core.cjs +5 -5
  42. package/dist/entries/core.js +1 -1
  43. package/dist/entries/trends.cjs +2 -2
  44. package/dist/entries/trends.js +1 -1
  45. package/dist/entries/user-settings.cjs +13 -0
  46. package/dist/entries/user-settings.cjs.map +1 -0
  47. package/dist/entries/user-settings.d.cts +115 -0
  48. package/dist/entries/user-settings.d.ts +115 -0
  49. package/dist/entries/user-settings.js +4 -0
  50. package/dist/entries/user-settings.js.map +1 -0
  51. package/dist/index.cjs +20 -14
  52. package/dist/index.d.cts +2 -1
  53. package/dist/index.d.ts +2 -1
  54. package/dist/index.js +7 -5
  55. package/package.json +7 -2
  56. package/dist/chunk-6FZN3QQO.cjs.map +0 -1
  57. package/dist/chunk-E5MJK3W5.cjs.map +0 -1
  58. package/dist/chunk-EC6MC46Y.js.map +0 -1
  59. package/dist/chunk-HPSENMVN.cjs.map +0 -1
  60. package/dist/chunk-WYYDWJFF.js.map +0 -1
  61. package/dist/chunk-YXVMQEJX.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/binary-response.ts","../src/core.ts","../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ACf,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-XISHBW5I.js","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":[],"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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MAAM,IAAI,IAAI,GAAA,CAAI,KAAK,OAAA,GAAU,OAAA,GAAU,SAAS,IAAI,CAAA;AACxD,MAAA,KAAA,MAAW,CAAC,CAAA,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-F4MFMHTQ.js","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"]}
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=chunk-ISKOLJJJ.cjs.map
4
+ //# sourceMappingURL=chunk-ISKOLJJJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-ISKOLJJJ.cjs"}
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=chunk-K6BWJ7ZY.js.map
3
+ //# sourceMappingURL=chunk-K6BWJ7ZY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-K6BWJ7ZY.js"}
@@ -36,7 +36,7 @@ async function readBinaryResponse(response, maxBytes) {
36
36
  }
37
37
  return bytes.buffer;
38
38
  }
39
- var SDK_VERSION = "2.51.0" ;
39
+ var SDK_VERSION = "2.53.0" ;
40
40
  var CLIENT_HEADER = "X-Nodaro-Client";
41
41
  var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
42
42
  var NodaroClientCore = class {
@@ -229,5 +229,5 @@ exports.CallbackAuth = CallbackAuth;
229
229
  exports.NodaroClientCore = NodaroClientCore;
230
230
  exports.StaticTokenAuth = StaticTokenAuth;
231
231
  exports.supabaseAuth = supabaseAuth;
232
- //# sourceMappingURL=chunk-OMX7JBGY.cjs.map
233
- //# sourceMappingURL=chunk-OMX7JBGY.cjs.map
232
+ //# sourceMappingURL=chunk-KQTPJ6R4.cjs.map
233
+ //# sourceMappingURL=chunk-KQTPJ6R4.cjs.map
@@ -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;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,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,IAAA,EAAK;AAC/B,MAAA,IAAI,KAAK,IAAA,EAAM;AACf,MAAA,MAAA,IAAU,KAAK,KAAA,CAAM,UAAA;AACrB,MAA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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"]}
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,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,IAAA,EAAK;AAC/B,MAAA,IAAI,KAAK,IAAA,EAAM;AACf,MAAA,MAAA,IAAU,KAAK,KAAA,CAAM,UAAA;AACrB,MAAA,IAAI,SAAS,QAAA,EAAU;AACrB,QAAA,MAAM,OAAO,MAAA,EAAO;AACpB,QAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,MACnE;AACA,MAAA,MAAA,CAAO,IAAA,CAAK,KAAK,KAAK,CAAA;AAAA,IACxB;AAAA,EACF,CAAA,SAAE;AAAU,IAAA,MAAA,CAAO,WAAA,EAAY;A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,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-KQTPJ6R4.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"]}
@@ -0,0 +1,31 @@
1
+ // src/resources/user-settings.ts
2
+ var UserSettingsResource = class {
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ client;
7
+ /**
8
+ * `GET /v1/user/settings` → the person's own settings. Throws
9
+ * `UnauthorizedError` (401) when signed out, `NotFoundError` with no
10
+ * profile row.
11
+ */
12
+ async get() {
13
+ const res = await this.client.request("GET", "/v1/user/settings");
14
+ return res.data;
15
+ }
16
+ /**
17
+ * `PATCH /v1/user/settings` → changes the fields sent and answers the
18
+ * settings as saved. A `NodaroError` with status 400 names an invalid
19
+ * value (`validation_error`), or says so for a patch with nothing to
20
+ * change; `ForbiddenError` for `publicOutputs: false` below the Standard
21
+ * plan; `NotFoundError` with no profile row.
22
+ */
23
+ async update(patch) {
24
+ const res = await this.client.request("PATCH", "/v1/user/settings", { body: patch });
25
+ return res.data;
26
+ }
27
+ };
28
+
29
+ export { UserSettingsResource };
30
+ //# sourceMappingURL=chunk-LR5TGCJP.js.map
31
+ //# sourceMappingURL=chunk-LR5TGCJP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/user-settings.ts"],"names":[],"mappings":";AAqFO,IAAM,uBAAN,MAA2B;AAAA,EAChC,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpB,MAAM,GAAA,GAA6B;AACjC,IAAA,MAAM,MAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,OAAO,mBAAmB,CAAA;AACxF,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAO,KAAA,EAAsD;AACjE,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAqC,SAAS,mBAAA,EAAqB,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAChH,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-LR5TGCJP.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * The signed-in person's own settings — the shape of `GET` / `PATCH\n * /v1/user/settings` (`backend/src/routes/user-settings.ts`, the source of\n * truth: keep these in sync if they change). A first-party app renders the\n * ones it cares about (the monthly statement opt-in on a billing screen, the\n * interface language) and sends back only the fields it changes.\n */\n\n/** How `{nodeRef}` placeholders render in prompt fields. */\nexport type VariableDisplayMode = \"raw\" | \"annotated\" | \"resolved\"\n/** What double-clicking a canvas node does. */\nexport type NodeDoubleClickAction = \"zoom\" | \"settings\"\n/** The interface languages Nodaro ships; the server refuses any other value. */\nexport type UserSettingsLocale = \"en\" | \"es\" | \"fr\" | \"de\" | \"pt-BR\" | \"ru\" | \"hi\" | \"ja\" | \"ko\" | \"zh-CN\" | \"he\" | \"ar\"\n\n/** One of the person's own Generate Text templates. */\nexport interface UserTextTemplate {\n id: string\n /** Up to 80 characters. */\n label: string\n /** Up to 10,000 characters. */\n systemPrompt: string\n defaultInput?: string\n /** 1–16,384. */\n defaultMaxTokens?: number\n llmModel?: string\n reasoningEffort?: string\n fansOut?: boolean\n requiresImageRef?: boolean\n}\n\n/** Per-user MCP defaults, sparse: a key left out keeps its stored value. */\nexport interface UserMcpPreferences {\n image?: { model?: string; aspectRatio?: string; resolution?: string; quality?: string }\n video?: { model?: string; aspectRatio?: string; duration?: number; resolution?: string }\n audio?: { ttsModel?: string; musicModel?: string }\n flows?: { enabled?: boolean }\n}\n\nexport interface UserSettings {\n /** The stored billing tier (`\"free\"`, `\"basic\"`, …). */\n tier: string | null\n /** Whether generations are visible in the public gallery. */\n publicOutputs: boolean\n /** Per-template overrides of the system prompts, by template key. */\n promptTemplates: Record<string, string>\n /** The person's own Generate Text templates. */\n textTemplates: UserTextTemplate[]\n /** The interface language; `null` = the browser's. */\n preferredLocale: UserSettingsLocale | null\n mcpPreferences: UserMcpPreferences\n showRecentNodes: boolean\n showMostUsedNodes: boolean\n variableDisplayMode: VariableDisplayMode\n nodeDoubleClickAction: NodeDoubleClickAction\n /** A statement of last month's credit usage by email on the 1st. Default `false`. */\n monthlyStatementEmail: boolean\n}\n\n/**\n * What `update()` sends: only the fields to change. `promptTemplates` and\n * `textTemplates` REPLACE the stored value whole (send the full map or list;\n * a template key the server does not know, or a value equal to the default,\n * is dropped); `mcpPreferences` merges one axis at a time.\n */\nexport interface UserSettingsPatch {\n /** `false` needs the Standard plan or above on Nodaro Cloud (`ForbiddenError` otherwise). */\n publicOutputs?: boolean\n promptTemplates?: Record<string, string>\n /** Up to 100. */\n textTemplates?: UserTextTemplate[]\n preferredLocale?: UserSettingsLocale | null\n mcpPreferences?: UserMcpPreferences\n showRecentNodes?: boolean\n showMostUsedNodes?: boolean\n variableDisplayMode?: VariableDisplayMode\n nodeDoubleClickAction?: NodeDoubleClickAction\n monthlyStatementEmail?: boolean\n}\n\n/** What `update()` answers: the settings as saved (without `tier`). */\nexport type UserSettingsSaved = Omit<UserSettings, \"tier\">\n\nexport class UserSettingsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/user/settings` → the person's own settings. Throws\n * `UnauthorizedError` (401) when signed out, `NotFoundError` with no\n * profile row.\n */\n async get(): Promise<UserSettings> {\n const res = await this.client.request<{ data: UserSettings }>(\"GET\", \"/v1/user/settings\")\n return res.data\n }\n\n /**\n * `PATCH /v1/user/settings` → changes the fields sent and answers the\n * settings as saved. A `NodaroError` with status 400 names an invalid\n * value (`validation_error`), or says so for a patch with nothing to\n * change; `ForbiddenError` for `publicOutputs: false` below the Standard\n * plan; `NotFoundError` with no profile row.\n */\n async update(patch: UserSettingsPatch): Promise<UserSettingsSaved> {\n const res = await this.client.request<{ data: UserSettingsSaved }>(\"PATCH\", \"/v1/user/settings\", { body: patch })\n return res.data\n }\n}\n"]}
@@ -100,5 +100,5 @@ var TrendsResource = class {
100
100
  };
101
101
 
102
102
  exports.TrendsResource = TrendsResource;
103
- //# sourceMappingURL=chunk-E5MJK3W5.cjs.map
104
- //# sourceMappingURL=chunk-E5MJK3W5.cjs.map
103
+ //# sourceMappingURL=chunk-N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A,CAAU,IAAA,EAAM,WAAW,CAAC,CAAA;AAAA,EACrE;AAAA;AAAA,EAGA,MAAM,WAAW,IAAA,EAA6B;AAC5C,IAAA,MAAM,KAAK,MAAA,CAAO,OAAA,CAAc,UAAU,SAAA,CAAU,IAAA,EAAM,WAAW,CAAC,CAAA;AAAA,EACxE;AACF","file":"chunk-NWMO4MHE.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { CastSwapEngine } from \"./cast-swap.js\"\n\n/**\n * Trends — ready-made Nodaro Motion recipes. A trend is a short clip with slots\n * (the people, pets, products and place you can replace); fill its slots with\n * your own pictures and run it to get the clip back with them in it.\n *\n * Cloud edition only: `/v1/trends` 404s on self-hosted installs. Only\n * published trends exist here: a draft, unpublished or unknown slug is a 404\n * on every route. `\"runs\"` and `\"tags\"` are never slugs (`/v1/trends/runs` is\n * the run list, `/v1/trends/tags` the tag list): the slug methods throw a\n * `TypeError` for them before any request. `run()` answers 202 with a job id; follow it with\n * `client.jobs.get(jobId)` / `client.jobs.getStatus(jobId)` like any other\n * job, or read it back as a trend run with `getRun(jobId)` / `runs()`.\n *\n * Repeats: pass `{ idempotencyKey }` to `run()` and it is sent as the\n * `Idempotency-Key` header. A repeat with the same key answers with the first\n * run's `jobId`; nothing new is started or charged.\n *\n * Refusals (thrown as a `NodaroError` subclass; body `{ error: { code, message } }`):\n * - 400 `validation_error` (the body, a query, or a bad `cursor`);\n * `estimate()` / `run()` only, before anything is charged:\n * `missing_slot` (a required slot without pictures, or an optional one\n * left empty that the chosen example has no pictures for), `unknown_slot`,\n * `invalid_choice` (a chip the slot's kind does not take),\n * `chip_not_offered` (a chip of the kind that the slot's\n * {@link TrendDetailSlot.chips} does not list: the trend fixes it),\n * `example_out_of_range` (`example` names no example of the trend, or is\n * sent at all on a trend with none), `preview_unavailable` (the trend offers no\n * preview), `invalid_slot_mention` (a `{slot:<key>}` in `details` naming no\n * slot), `prompt_too_long` (shorten `details`), `draft_unsupported`\n * (`draft: true` on a trend whose `engine` has no draft: Nodaro Motion Pulse),\n * `resolution_unsupported` (a `resolution` not in the trend's\n * `resolutions`), `too_many_images` (a Nodaro Motion Pulse trend's run would send more\n * than 10 pictures: send fewer per slot). The slot errors carry the\n * slot's key as `slot` (in `NodaroError.details`), and `chip_not_offered`\n * the chip as `chip` too.\n * - 401 `unauthorized`.\n * - 404 `not_found`: the trend is not published (every method), or `run()`'s\n * `sessionId` is not a session you may use.\n * - 409 `trend_unavailable` (`estimate()` / `run()`): the trend's setup is out\n * of date — it cannot run until it is updated, so a retry gets the same answer.\n * - 502 `engine_error` (`estimate()` / `run()`).\n * - 503 `engine_unsupported` (this platform version cannot run trends yet),\n * `trend_unavailable` (`estimate()` / `run()`), `not_available` (this\n * server has no trend catalog yet).\n * - `estimate()` / `run()` answer the video engine's refusals with the trend\n * routes' OWN codes and fixed messages — never the engine's text or\n * `issues`: 400 `trend_run_rejected` (the inputs could not run), or\n * `clip_out_of_range` / `preview_out_of_range` / `video_unreadable` (this\n * trend's clip), `unsafe_url` (a picture is not a public http(s) address),\n * `raw_reference_token` (`details` holds `{image:` / `{video:` /\n * `{audio:`); 402 `insufficient_credits` (or a workspace cap) as given;\n * 413 `storage_limit_exceeded`; 422 `job_blocked` (the job policy\n * blocked it); 429 `rate_limited`; 503 `engine_unsupported`,\n * `estimate_unavailable`; 502 `engine_error` for anything else. `run()`\n * also answers 400 `validation_error` for an `idempotencyKey` outside\n * 8–200 characters.\n */\n\n/** `/v1/trends/runs` is the run list and `/v1/trends/tags` the tag list, so neither can be a trend's slug. */\nconst RESERVED_SLUGS: Readonly<Record<string, string>> = {\n runs: \"the run list; use runs()\",\n tags: \"the tag list; use tags()\",\n}\n\nfunction trendPath(slug: string, rest = \"\"): string {\n if (Object.hasOwn(RESERVED_SLUGS, slug)) {\n throw new TypeError(`\"${slug}\" is not a trend slug (it is reserved for ${RESERVED_SLUGS[slug]})`)\n }\n return `/v1/trends/${encodeURIComponent(slug)}${rest}`\n}\n\n/** What a slot holds. */\nexport type TrendSlotKind = \"person\" | \"location\" | \"product\" | \"pet\"\n\n/** A chip: make this trait anew from your pictures (`\"new\"`), or keep the clip's (`\"original\"`). */\nexport type TrendChoice = \"new\" | \"original\"\n\n/**\n * The chips a slot can take, by its kind: a person `body` / `outfit` / `hair`,\n * a pet `body` / `coat`, a product `shape` / `finish`, a location none.\n */\nexport interface TrendChips {\n body?: TrendChoice\n outfit?: TrendChoice\n hair?: TrendChoice\n coat?: TrendChoice\n shape?: TrendChoice\n finish?: TrendChoice\n}\n\n/** A chip's name: `body`, `outfit`, `hair`, `coat`, `shape` or `finish`. */\nexport type TrendChipKey = keyof TrendChips\n\nexport type TrendResolution = \"480p\" | \"720p\" | \"1080p\"\n\n/**\n * The engine a trend runs on, by its public id ({@link CastSwapEngine}):\n * `\"motion-prism\"` (Nodaro Motion Prism) or `\"motion-pulse\"` (Nodaro Motion Pulse).\n * The trend chooses it, never the person running it.\n */\nexport type TrendEngine = CastSwapEngine\n\n/** A trend in the catalog (`list()`). Text is in the resolved locale. */\nexport interface TrendCard {\n id: string\n slug: string\n name: string\n description?: string\n tags: string[]\n /** e.g. `\"trending\"`, `\"new\"`. */\n badges: string[]\n /**\n * The trend's first example, else (a trend with no example) its original's\n * display copy, as {@link TrendDetail.original}.\n */\n cover: { videoUrl: string; posterUrl?: string; width: number; height: number }\n /** How many slots of each kind the trend has. */\n needs: Record<TrendSlotKind, number>\n /** The length of a full run, in seconds. */\n durationSec: number\n isFavorite: boolean\n}\n\n/** One slot of a trend: what it asks you for. */\nexport interface TrendDetailSlot {\n /** The key to fill in {@link TrendRunRequest.slots}, and to mention in `details` as `{slot:<key>}`. */\n key: string\n label: string\n kind: TrendSlotKind\n /**\n * A required slot needs pictures; an optional one left empty takes the\n * chosen example's, or, on a trend with no example, stays as in the original.\n */\n required: boolean\n hint?: string\n /**\n * A picture showing who or what this slot is in the original (e.g. a frame\n * of that actor), when the trend has one. Show it on an empty slot; a run\n * never sends it.\n */\n hintImageUrl?: string\n /**\n * The chips you may set on this slot, in its kind's order; `[]` = none (show\n * no chips row). A chip of the kind that is not listed is fixed by the\n * trend: sending it is refused with `400 chip_not_offered`.\n */\n chips: TrendChipKey[]\n /** The starting value of the chips in {@link chips} (only those). */\n defaults?: TrendChips\n}\n\n/** A finished run shown on a trend's page, with the pictures it used per slot. */\nexport interface TrendExample {\n videoUrl: string\n posterUrl?: string\n width: number\n height: number\n /** Slot key → the pictures this example used for it. */\n slots: Record<string, string[]>\n}\n\n/**\n * The clip a trend recasts, as you may show it: a browser-safe copy (H.264\n * MP4) of the clip every run starts from. Its fields parallel\n * {@link TrendExample}'s.\n */\nexport interface TrendOriginal {\n videoUrl: string\n posterUrl?: string\n width: number\n height: number\n /** The copy's length, in seconds. */\n durationSec: number\n /**\n * Where the 4-second preview starts in the clip, in seconds (`0` included),\n * when the trend offers one ({@link TrendDetail.previewSec} is `4`); absent\n * otherwise.\n */\n previewStartSec?: number\n}\n\n/** A trend's page (`get()`). */\nexport interface TrendDetail extends TrendCard {\n /** The published version this page shows. */\n version: number\n /** `4` when the trend offers a 4-second preview run, else `null`. */\n previewSec: 4 | null\n /**\n * The original clip every run starts from, to show beside the examples.\n * Absent only on a version without a display copy (and from an older server).\n */\n original?: TrendOriginal\n /** The engine every run of this trend uses. Absent (an older server) = `\"motion-prism\"`. */\n engine?: TrendEngine\n /** Its name to show: \"Nodaro Motion Prism\" or \"Nodaro Motion Pulse\". Absent from an older server. */\n engineName?: string\n /**\n * The resolutions a run may ask for, the default first. Nodaro Motion Prism:\n * `[\"480p\", \"720p\", \"1080p\"]`, where 480p is a draft (show it as one);\n * Nodaro Motion Pulse: `[\"720p\", \"1080p\"]`, no draft. Offer exactly these.\n */\n resolutions: TrendResolution[]\n slots: TrendDetailSlot[]\n /** Finished runs to show beside the original; may be empty (a trend with only its original). */\n examples: TrendExample[]\n}\n\n/** What you put in one slot of a run: 1–3 pictures, and the chips the slot offers ({@link TrendDetailSlot.chips}). */\nexport interface TrendRunSlot extends TrendChips {\n images?: string[]\n}\n\n/** The body of `estimate()` and `run()`. */\nexport interface TrendRunRequest {\n /**\n * Slot key → what you put in it. Every required slot needs pictures; an\n * optional slot left out takes the chosen example's, or, on a trend with no\n * example, stays as in the original. 1–3 pictures per slot.\n */\n slots: Record<string, TrendRunSlot>\n /**\n * 1-based example whose pictures fill the optional slots you leave empty.\n * Default 1. Leave it out on a trend with no examples: sending one there\n * answers 400 `example_out_of_range` (and `0` is a `validation_error`).\n */\n example?: number\n /** Your own words, at most 1,000 characters. Mention a slot as `{slot:<key>}`. */\n details?: string\n /** `true` runs a 4-second preview (only when the trend's `previewSec` is `4`). */\n preview?: boolean\n /**\n * One of the trend's {@link TrendDetail.resolutions}; default its first\n * (`\"480p\"` on Nodaro Motion Prism, `\"720p\"` on Nodaro Motion Pulse). Another answers 400\n * `resolution_unsupported`.\n */\n resolution?: TrendResolution\n /**\n * A draft run, only at 480p on a Nodaro Motion Prism trend. Default `true` at\n * 480p. `true` on a Nodaro Motion Pulse trend answers 400 `draft_unsupported`.\n */\n draft?: boolean\n /**\n * A generation session of yours. Accepted (and checked: one you may not use\n * is a 404), but not yet applied: trend runs are not filed into sessions yet.\n */\n sessionId?: string\n /** Accepted, but not used by the run today. */\n projectId?: string\n /**\n * A full run's own preview: the `jobId` of a completed preview run of this\n * trend that you started. When that preview needed the trend's retry (the\n * clip refused at first), the full run is made that way from the start (the\n * quote includes it). Any other job is ignored, without an error. Must be a uuid\n * (else 400 `validation_error`).\n */\n previewJobId?: string\n /**\n * `run()`: your client app's slug (e.g. `\"tools\"`: lowercase letters,\n * digits and `-`, 1–40 characters, starting with a letter or digit), as on\n * any job: the run's job carries it as `input_data.origin`, so\n * `client.jobs.list({ origin })` finds it. Not a slug is a 400\n * `validation_error`; without it the run has no origin. `estimate()`\n * ignores it.\n */\n origin?: string\n}\n\n/** What a run would cost, in credits (`estimate()`). */\nexport interface TrendEstimate {\n /** The charge the run is expected to come to. */\n expectedCredits: number\n /** What is reserved when the run starts; the run is charged what it actually costs. */\n holdCredits: number\n /**\n * The parts of the quote, by name, for display only: some are alternatives\n * or sit outside the totals (`privacy`, the retry's, beside\n * `privacyCredits`), so read `expectedCredits` and `holdCredits`, never\n * their sum.\n */\n breakdown: Record<string, number>\n /**\n * Only on a trend that retries a clip the video model refuses: the extra\n * credits charged if that retry runs. Not included in `expectedCredits` or\n * `holdCredits`. 0 (or absent) when there is nothing extra to charge.\n */\n privacyCredits?: number\n /** @deprecated read {@link privacyCredits} (an older server answered this name). */\n maskingCredits?: number\n}\n\n/** Per-call options for {@link TrendsResource.run}. */\nexport interface TrendRunOptions {\n /**\n * Sent as the `Idempotency-Key` header, unchanged (an empty string sends no\n * header). The server takes 8–200 characters and answers 400 for any other\n * length. Reuse it when retrying the same run.\n */\n idempotencyKey?: string\n}\n\n/** One slot of a past run, as it was run. Labels are English. */\nexport interface TrendRunDisplaySlot extends TrendChips {\n key: string\n label: string\n kind: TrendSlotKind\n images: string[]\n /**\n * `true` when the slot was left empty and the example's pictures filled it.\n * `false` with no `images`: left empty on a trend with no example, so it\n * stayed as in the original.\n */\n fromExample: boolean\n}\n\n/**\n * One of your trend runs (`runs()`, `getRun()`). Stays readable after the\n * trend moves on or is unpublished.\n *\n * A Full Quality version of a draft is a run of its own, with its own status,\n * result and charge: `fullQualityOf` names the draft it was made from, and it\n * stays listed after that draft is deleted.\n */\nexport interface TrendRun {\n jobId: string\n status: string\n progress: number | null\n /**\n * Why a failed or cancelled run did not finish; `null` otherwise. `code` is\n * `safety-block` or `policy-block` when the job was blocked, `credits` when\n * it ran out of credits partway (it was refunded: ask the person to top up,\n * then run it again), else `cancelled` or `failed`. `message` is the same\n * fixed sentence for every code — branch on `code`, not on the text.\n */\n error: { code?: string; message: string } | null\n createdAt: string\n completedAt: string | null\n /** The trend and version it ran (name in English). */\n trend: { id: string; slug: string; version: number; name: string }\n /**\n * The 1-based example used for empty optional slots; `0` = the trend had no\n * example (none was used: never show it as \"Example 0\").\n */\n example: number\n slots: TrendRunDisplaySlot[]\n details?: string\n preview: boolean\n resolution: string\n draft: boolean\n /** The engine the run was made on. Absent (an older server) = `\"motion-prism\"`. */\n engine?: TrendEngine\n /** Its name to show: \"Nodaro Motion Prism\" or \"Nodaro Motion Pulse\". Absent from an older server. */\n engineName?: string\n /** The result, once completed. */\n videoUrl: string | null\n posterUrl: string | null\n /**\n * What the run was charged once settled, every step it ran included (its\n * reference preparation, mask and video); `null` until the run's own hold\n * settles. A step adds its charge once it settles.\n */\n creditsCharged: number | null\n /** The run's hold: its own plus its steps'. Absent from an older server. */\n creditsHeld?: number | null\n /** What went back from `creditsHeld` once every hold in the run settled; `null` until then. Absent from an older server. */\n creditsReleased?: number | null\n /** A Full Quality version: the job id of the run (a draft, or a Nodaro Motion Pulse 720p run) it was made from. `null` for any other run. */\n fullQualityOf: string | null\n /**\n * A draft's (or Nodaro Motion Pulse 720p run's) newest Full Quality try, if one was started: a pointer only,\n * to know an upgrade exists and how it is going. Its video and charge are on\n * that run, listed on its own (its `fullQualityOf` is this run's `jobId`) —\n * read it there (`getRun(fullQuality.jobId)`). Older tries of the draft (a\n * failed or cancelled one tried again) are not listed by `runs()`;\n * `getRun()` still reads one by its id.\n */\n fullQuality: { jobId: string; status: string } | null\n /**\n * Until when a completed run can be redone in Full Quality — a Nodaro Motion\n * Prism draft (the same take at 1080p) or a Nodaro Motion Pulse run at 720p (a new take at\n * 1080p); `null` otherwise.\n */\n fullQualityUntil: string | null\n}\n\nexport interface ListTrendsParams {\n /** Search text. */\n q?: string\n tag?: string\n /** `true` lists only your favorites. */\n favorites?: boolean\n /** A platform language for names and descriptions; default your profile's, then English. */\n locale?: string\n /** The previous page's `next`. */\n cursor?: string\n /** Page size, 1–60 (server default 30). */\n limit?: number\n}\n\nexport interface ListTrendRunsParams {\n /** Only runs of this trend (its slug). */\n trend?: string\n /** The previous page's `next`. */\n cursor?: string\n /** Page size, 1–60 (server default 30). */\n limit?: number\n}\n\n/** A tag in use on the published catalog (`tags()`). */\nexport interface TrendTag {\n /** The tag itself: pass it as `list({ tag })`. */\n tag: string\n /** The tag's label in the resolved locale; the tag itself when it has none. */\n label: string\n /** How many published trends carry it. */\n count: number\n}\n\nexport interface TrendPage<T> {\n data: T[]\n /** Pass back as `cursor` for the next page; `null` on the last one. */\n next: string | null\n}\n\nexport class TrendsResource {\n constructor(private client: NodaroClientCore) {}\n\n /** The published catalog in its curated order (`GET /v1/trends`), a page at a time. */\n list(params: ListTrendsParams = {}): Promise<TrendPage<TrendCard>> {\n const query: Record<string, string> = {}\n if (params.q) query.q = params.q\n if (params.tag) query.tag = params.tag\n if (params.favorites) query.favorites = \"1\"\n if (params.locale) query.locale = params.locale\n if (params.cursor) query.cursor = params.cursor\n if (params.limit !== undefined) query.limit = String(params.limit)\n return this.client.request(\"GET\", \"/v1/trends\", { query })\n }\n\n /** A published trend's page (`GET /v1/trends/:slug`). */\n async get(slug: string, params: { locale?: string } = {}): Promise<TrendDetail> {\n const query: Record<string, string> = {}\n if (params.locale) query.locale = params.locale\n const res = await this.client.request<{ data: TrendDetail }>(\"GET\", trendPath(slug), { query })\n return res.data\n }\n\n /** Quote a run before starting it (`POST /v1/trends/:slug/estimate`); spends nothing. */\n async estimate(slug: string, request: TrendRunRequest): Promise<TrendEstimate> {\n const res = await this.client.request<{ data: TrendEstimate }>(\n \"POST\",\n trendPath(slug, \"/estimate\"),\n { body: request },\n )\n return res.data\n }\n\n /**\n * Start a run (`POST /v1/trends/:slug/runs`, 202). Returns the job to follow.\n * With `options.idempotencyKey` (sent as the `Idempotency-Key` header) a\n * repeat with the same key answers with the first run's `jobId`.\n */\n async run(slug: string, request: TrendRunRequest, options?: TrendRunOptions): Promise<{ jobId: string }> {\n const res = await this.client.request<{ data: { jobId: string } }>(\n \"POST\",\n trendPath(slug, \"/runs\"),\n {\n body: request,\n ...(options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}),\n },\n )\n return res.data\n }\n\n /**\n * Your trend runs, newest first (`GET /v1/trends/runs`). A Full Quality\n * version of a draft is listed as its own run (`fullQualityOf`).\n */\n runs(params: ListTrendRunsParams = {}): Promise<TrendPage<TrendRun>> {\n const query: Record<string, string> = {}\n if (params.trend) query.trend = params.trend\n if (params.cursor) query.cursor = params.cursor\n if (params.limit !== undefined) query.limit = String(params.limit)\n return this.client.request(\"GET\", \"/v1/trends/runs\", { query })\n }\n\n /**\n * One of your trend runs by its job id (`GET /v1/trends/runs/:jobId`), in\n * the same shape as `runs()`. A job that is not your own trend run is a\n * `NotFoundError`.\n */\n async getRun(jobId: string): Promise<TrendRun> {\n const res = await this.client.request<{ data: TrendRun }>(\"GET\", `/v1/trends/runs/${encodeURIComponent(jobId)}`)\n return res.data\n }\n\n /**\n * The tags in use on the published catalog, each with its label in the\n * resolved locale (`GET /v1/trends/tags`), most used first.\n */\n async tags(params: { locale?: string } = {}): Promise<TrendTag[]> {\n const query: Record<string, string> = {}\n if (params.locale) query.locale = params.locale\n const res = await this.client.request<{ data: TrendTag[] }>(\"GET\", \"/v1/trends/tags\", { query })\n return res.data\n }\n\n /** Add a trend to your favorites (`PUT /v1/trends/:slug/favorite`). */\n async favorite(slug: string): Promise<void> {\n await this.client.request<void>(\"PUT\", trendPath(slug, \"/favorite\"))\n }\n\n /** Remove a trend from your favorites (`DELETE /v1/trends/:slug/favorite`). */\n async unfavorite(slug: string): Promise<void> {\n await this.client.request<void>(\"DELETE\", trendPath(slug, \"/favorite\"))\n }\n}\n"]}
@@ -142,5 +142,5 @@ var BillingResource = class {
142
142
  };
143
143
 
144
144
  exports.BillingResource = BillingResource;
145
- //# sourceMappingURL=chunk-6FZN3QQO.cjs.map
146
- //# sourceMappingURL=chunk-6FZN3QQO.cjs.map
145
+ //# sourceMappingURL=chunk-TVPYDC5T.cjs.map
146
+ //# sourceMappingURL=chunk-TVPYDC5T.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/billing.ts"],"names":[],"mappings":";;;AAsLO,IAAM,kB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AA;AAAA,EASA,MAAM,MAAA,CAAO,KAAA,GAA4B,EAAC,EAAkC;AAC1E,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAwC,QAAQ,iCAAA,EAAmC,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAChI,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,WAAW,KAAA,EAAiE;AAChF,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAA2C,QAAQ,yBAAA,EAA2B,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAC3H,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-TVPYDC5T.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Plans and prices, the subscription, and the billing surface — the shapes of\n * the `/v1/billing/*` routes an app may call. Mirrors the backend routes\n * (`backend/src/ee/routes/billing.ts`, `backend/src/routes/billing-surface.ts`),\n * the source of truth: keep these in sync if they change.\n *\n * Buying, the plan, the payment settings, the receipts and the invoices answer\n * a SIGNED-IN SESSION only (`supabaseAuth`, the credential a first-party web\n * app holds): those routes refuse an API key and an app's OAuth token with\n * `403 forbidden` (`ForbiddenError`). Their methods are marked so below.\n */\n\n/** A sum of money in its currency's major unit (`12` = 12.00), with its ISO-4217 code (`\"USD\"`). */\nexport interface BillingMoney {\n amount: number\n currency: string\n}\n\n/** The credits a price grants, and how often. */\nexport interface BillingPriceCredits {\n amount: number\n per: \"month\" | \"year\"\n}\n\n/** A monthly price, and what it grants. */\nexport interface BillingMonthlyPrice extends BillingMoney {\n /** The Stripe price id: pass it to {@link BillingResource.checkout} or {@link BillingResource.changePlan}; match the subscription's `stripe_price_id` to it to learn the interval. */\n priceId: string\n /** `null` when the price does not state it. */\n credits: BillingPriceCredits | null\n}\n\n/** A yearly price, what it comes to per month, and what it grants. */\nexport interface BillingYearlyPrice extends BillingMoney {\n /** The Stripe price id: pass it to {@link BillingResource.checkout} or {@link BillingResource.changePlan}; match the subscription's `stripe_price_id` to it to learn the interval. */\n priceId: string\n /** The yearly amount spread over the months it pays for; `null` when that cannot be said. */\n perMonth: number | null\n /** What the price grants — the plan's credits every month, as a monthly price; `null` when the price does not state it. */\n credits: BillingPriceCredits | null\n}\n\nexport interface BillingPlanPrices {\n /** `null` = Stripe cannot sell this price right now: show it as unavailable, never as free. */\n monthly: BillingMonthlyPrice | null\n yearly: BillingYearlyPrice | null\n}\n\n/** One plan on sale. */\nexport interface BillingPlan {\n /** `\"free\"`, `\"basic\"`, `\"standard\"`, … — the stable id. */\n id: string\n name: string\n /** `null` for the free plan: there is nothing to pay. */\n prices: BillingPlanPrices | null\n /** The free plan's one-time grant at sign-up; `null` on a paid plan, whose credits come with each price. */\n signupCredits: number | null\n /** How many nodes of one workflow run at once. */\n parallelism: number\n /** Storage for your media, in bytes. */\n storageBytes: number\n}\n\n/** A credit pack: this many credits for this price. */\nexport interface BillingTopUp {\n /** The pack's own id (`\"topup-25\"`), not a Stripe id. */\n id: string\n credits: number\n /** `null` when the pack's price cannot be stated right now: show it as unavailable. */\n price: BillingMoney | null\n /** The Stripe price id for {@link BillingResource.checkout} (mode `\"payment\"`); `null` with the price. A pack can always be bought as a load of `price.amount` through {@link BillingResource.loadCredits}. */\n priceId: string | null\n}\n\n/** The answer of `GET /v1/billing/plans`. */\nexport interface BillingPlansResult {\n /** The free plan first, then each paid plan from the smallest. */\n data: BillingPlan[]\n /** The credit packs, from the smallest. */\n topUps: BillingTopUp[]\n /** Any whole amount in this range can be loaded as credits, at the same rate as the packs. */\n topUpRange: { min: number; max: number; currency: string }\n}\n\n/** The account's latest subscription record. */\nexport interface BillingSubscription {\n id: string\n stripe_subscription_id: string | null\n /** The plan id: `\"basic\"`, `\"standard\"`, … */\n tier: string\n /** `\"active\"`, `\"trialing\"`, `\"past_due\"`, `\"paused\"`, `\"canceled\"`, `\"incomplete\"` or `\"expired\"`. */\n status: string\n stripe_price_id: string | null\n /** ISO-8601. */\n current_period_start: string | null\n /** ISO-8601: when the current period ends (and renews, unless cancelled). */\n current_period_end: string | null\n /** True when the subscription ends at `current_period_end` instead of renewing. */\n cancel_at_period_end: boolean\n /** ISO-8601: when a scheduled cancellation takes effect. */\n cancel_at: string | null\n /** ISO-8601: when it was cancelled. */\n canceled_at: string | null\n}\n\n/** The answer of `GET /v1/billing/subscription`. */\nexport interface BillingSubscriptionResult {\n /** `null` when the account never subscribed. */\n data: BillingSubscription | null\n /**\n * The tier the account's entitlements follow: usually a plan id from\n * `plans()` (`\"free\"` included); `\"payg\"` — no subscription, but credits\n * bought (every model, no watermark); or a tier that is not on sale, such\n * as `\"enterprise\"`.\n */\n effectiveTier: string\n}\n\n/** How this deployment bills, the same for every caller (`GET /v1/billing/surface`). */\nexport interface BillingSurface {\n /** The billing-surface contract version (an integer). */\n contract: number\n /** The registered billing provider; `\"none\"` = this deployment meters nothing. */\n providerId: string\n /** The unit costs display in by default (`\"credits\"`, `\"usd\"`, or a deployment's own label). */\n displayUnit: string\n canReport: boolean\n canQuote: boolean\n canAccount: boolean\n /** Whether a cost view belongs on this deployment. */\n mountCostTab: boolean\n /** One billing account pays for every user here. */\n deploymentPayer: boolean\n}\n\n/** One row of {@link BillingAccountSummary.byCategory}. */\nexport interface BillingUsageCategory {\n category: string\n count: number\n /** Spend in the display unit; `null` = unavailable, never 0. */\n amount: number | null\n spent: BillingMoney | null\n}\n\n/**\n * The caller's account as the deployment's billing provider sees it\n * (`GET /v1/billing/account`). Money and amounts are `null` when the provider\n * could not say: show that distinctly, never as 0. A field the provider leaves\n * out is a concept it does not have.\n */\nexport interface BillingAccountSummary {\n /** A plain string; `\"unknown\"` is a real answer. */\n plan: string\n balance: number | null\n dailyAllowance: number | null\n unit: string\n /** `\"external_wallet\"` when the balance comes from a wallet outside Nodaro. */\n balanceSource?: \"external_wallet\"\n /** ISO-8601 start of the current usage period. */\n periodStart?: string | null\n /** Generations this period. */\n generations?: number | null\n /** Money spent this period. */\n spent?: BillingMoney | null\n /** Pay-as-you-go state. */\n payg?: {\n enabled: boolean\n reserve: number | null\n rate: { creditsPerUnit: number; currency: string } | null\n monthlyCap: BillingMoney | null\n } | null\n /** The daily cap and when it resets; prefer it over `dailyAllowance` when present. `limit: 0` means blocked. */\n daily?: { limit: number; used: number; remaining: number; resetsAt: string } | null\n /** Money value of the pay-as-you-go reserve. */\n reserveValue?: BillingMoney | null\n byCategory?: BillingUsageCategory[] | null\n /** The total the balance is drawn from, where the provider grants each user an allocation. */\n allocated?: number | null\n}\n\nexport class BillingResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/billing/plans` → the plans and credit packs on sale, with their\n * prices. Public: works with no credential, the same for every caller.\n * Nodaro Cloud only — a self-hosted instance answers 404. Throws on `403\n * self_serve_disabled` (this deployment does not sell to its users) and on\n * `503` (`stripe_not_configured`, or prices briefly unavailable).\n */\n plans(): Promise<BillingPlansResult> {\n return this.client.request<BillingPlansResult>(\"GET\", \"/v1/billing/plans\")\n }\n\n /**\n * `GET /v1/billing/subscription` → the account's latest subscription\n * (`null` when it never subscribed) and the tier its entitlements follow.\n * Match `effectiveTier` to a {@link BillingPlan} `id` to mark the current\n * plan (no match: pay-as-you-go, or a tier not on sale). Needs a signed-in\n * session, a personal API token without a workflow limit, or an app's OAuth\n * token. Nodaro Cloud only — a self-hosted instance answers 404.\n */\n subscription(): Promise<BillingSubscriptionResult> {\n return this.client.request<BillingSubscriptionResult>(\"GET\", \"/v1/billing/subscription\")\n }\n\n /**\n * `GET /v1/billing/surface` → how this deployment bills: whether it meters\n * at all (`providerId !== \"none\"`) and in which unit costs display. Public,\n * every edition.\n */\n async surface(): Promise<BillingSurface> {\n const res = await this.client.request<{ data: BillingSurface }>(\"GET\", \"/v1/billing/surface\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/account` → the caller's plan and balance as the\n * deployment's billing provider reports them, in its display unit. `null`\n * when the provider could not answer — not a zero balance. Every edition.\n */\n async account(): Promise<BillingAccountSummary | null> {\n const res = await this.client.request<{ data: BillingAccountSummary | null }>(\"GET\", \"/v1/billing/account\")\n return res.data\n }\n\n // ── Signed-in session only (ForbiddenError on an API key or an app token) ──\n\n /**\n * `GET /v1/billing/transactions` → the account's credit purchases, newest\n * first: subscription payments and credit packs, each with its Stripe\n * receipt link when one was captured. **Signed-in session only.**\n */\n async purchases(): Promise<BillingPurchase[]> {\n const res = await this.client.request<{ data: BillingPurchase[] }>(\"GET\", \"/v1/billing/transactions\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/invoices` → every payment as a document, newest first:\n * a Stripe invoice (with its PDF) for each subscription payment, a hosted\n * receipt for each credit pack or load. **Signed-in session only.**\n */\n async invoices(): Promise<BillingDocument[]> {\n const res = await this.client.request<{ data: BillingDocument[] }>(\"GET\", \"/v1/billing/invoices\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/payment-method` → the card and the billing details on\n * file with Stripe; both `null` for an account that has not bought yet\n * (never an error). **Signed-in session only.**\n */\n async paymentMethod(): Promise<BillingPaymentMethod> {\n const res = await this.client.request<{ data: BillingPaymentMethod }>(\"GET\", \"/v1/billing/payment-method\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/auto-recharge` → the automatic top-up setting: when the\n * balance falls under `thresholdCredits`, `amountUsd` is loaded from the\n * saved card. **Signed-in session only.**\n */\n async autoRecharge(): Promise<BillingAutoRecharge> {\n const res = await this.client.request<{ data: BillingAutoRecharge }>(\"GET\", \"/v1/billing/auto-recharge\")\n return res.data\n }\n\n /**\n * `PUT /v1/billing/auto-recharge` → changes the automatic top-up. Enabling\n * needs both `thresholdCredits` (100–100,000) and `amountUsd` (a whole\n * amount in the load range); the server answers `400` otherwise. A change\n * clears the failure count. **Signed-in session only.**\n */\n async setAutoRecharge(input: BillingAutoRechargeInput): Promise<BillingAutoRechargeSaved> {\n const res = await this.client.request<{ data: BillingAutoRechargeSaved }>(\"PUT\", \"/v1/billing/auto-recharge\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/create-checkout-session` → a Stripe Checkout page for a\n * plan or a credit pack (`priceId` from {@link BillingPlansResult}): send\n * the person to `url`. Pass `returnPath` (a path on your own origin, such\n * as `\"/billing\"`) to have Stripe bring them back to your app with\n * `checkout=success` or `checkout=cancelled` in the query; without it the\n * Nodaro app's own pages are used. `ForbiddenError` with the code\n * `self_serve_disabled` on a deployment that does not sell to its users.\n * **Signed-in session only.**\n */\n async checkout(input: BillingCheckoutInput): Promise<BillingCheckoutSession> {\n const res = await this.client.request<{ data: BillingCheckoutSession }>(\"POST\", \"/v1/billing/create-checkout-session\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/create-load-session` → a Stripe Checkout page that loads\n * a whole amount (`amountUsd`, within {@link BillingPlansResult.topUpRange})\n * as credits at the packs' rate; `credits` is what it will grant. The card\n * is saved for auto top-up. `returnPath` as in {@link checkout}.\n * **Signed-in session only.**\n */\n async loadCredits(input: BillingLoadInput): Promise<BillingLoadSession> {\n const res = await this.client.request<{ data: BillingLoadSession }>(\"POST\", \"/v1/billing/create-load-session\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/manage-subscription` → a Stripe Customer Portal page\n * (the card, the billing address, the invoices, cancelling): send the person\n * to `url`; `returnPath` is where the portal's Back goes (default the app's\n * `/billing`). `NotFoundError` before a first purchase — Stripe does not\n * know the account yet. **Signed-in session only.**\n */\n async portal(input: BillingPortalInput = {}): Promise<BillingPortalSession> {\n const res = await this.client.request<{ data: BillingPortalSession }>(\"POST\", \"/v1/billing/manage-subscription\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/change-plan` → moves the active subscription to another\n * plan's price (`newPriceId`, a subscription price from the plans list),\n * prorated by Stripe; the new tier applies at once. `NotFoundError` with no\n * active subscription; `400` on a pack's price or the current one.\n * **Signed-in session only.**\n */\n async changePlan(input: BillingChangePlanInput): Promise<BillingChangePlanResult> {\n const res = await this.client.request<{ data: BillingChangePlanResult }>(\"POST\", \"/v1/billing/change-plan\", { body: input })\n return res.data\n }\n}\n\n// ── Types of the signed-in-session methods ──\n\n/** One credit purchase (`billing.purchases()`), as the `transactions` row names it. */\nexport interface BillingPurchase {\n id: string\n /** The Stripe payment or subscription id. */\n stripe_transaction_id: string | null\n /** `\"subscription\"` (a plan payment), `\"topup\"` (a credit pack or a load) or `\"refund\"` (money given back: `credits_granted` negative). */\n type: string\n /** What was paid, in US dollars (on a refund, the sum given back). */\n amount_usd: number\n /** Negative on a refund. */\n credits_granted: number\n /** The plan paid for, on a subscription payment. */\n tier: string | null\n /** ISO-8601. */\n created_at: string\n /** Stripe's hosted receipt; `null` when none was captured. */\n receipt_url: string | null\n}\n\n/** A payment document: a Stripe invoice (a subscription payment) or a receipt (a credit purchase). */\nexport interface BillingDocument {\n id: string\n kind: \"invoice\" | \"receipt\"\n /** The invoice number Stripe printed; `null` on a receipt. */\n number: string | null\n /** ISO-8601. */\n at: string\n amount: BillingMoney\n /** The credits the payment granted; `null` on an invoice (the plan's credits come with the period). Negative on a refund. */\n credits: number | null\n /** `\"paid\"`, `\"open\"`, `\"void\"`, `\"uncollectible\"`, or `\"refunded\"` (a receipt for money given back: `amount` and `credits` negative). */\n status: string\n description: string | null\n /** The PDF, on an invoice; `null` on a receipt. */\n pdfUrl: string | null\n /** The hosted page: Stripe's invoice page, or the receipt. */\n url: string | null\n}\n\n/** The card on file, as Stripe shows it. */\nexport interface BillingCard {\n /** `\"visa\"`, `\"mastercard\"`, … */\n brand: string\n last4: string\n expMonth: number\n expYear: number\n}\n\n/** The name, email and country on file. */\nexport interface BillingDetails {\n name: string | null\n email: string | null\n /** ISO-3166 alpha-2. */\n country: string | null\n}\n\n/** The answer of `billing.paymentMethod()`: both `null` before a first purchase. */\nexport interface BillingPaymentMethod {\n card: BillingCard | null\n billingDetails: BillingDetails | null\n}\n\n/** The automatic top-up setting (`billing.autoRecharge()`). */\nexport interface BillingAutoRecharge {\n enabled: boolean\n /** Load when the balance falls under this many credits; `null` when never set. */\n thresholdCredits: number | null\n /** The whole dollar amount loaded each time; `null` when never set. */\n amountUsd: number | null\n /** Failed attempts in a row; the server stops trying after a few, until the setting is saved again. */\n failureCount: number\n /** ISO-8601; `null` before the first attempt. */\n lastAttemptAt: string | null\n /** Whether a card is saved to charge; without one, enabling cannot work. */\n hasSavedCard: boolean\n}\n\n/** What `billing.setAutoRecharge()` sends; `thresholdCredits` and `amountUsd` are both required to enable. */\nexport interface BillingAutoRechargeInput {\n enabled: boolean\n thresholdCredits?: number\n amountUsd?: number\n}\n\n/** What `billing.setAutoRecharge()` answers: the fields as sent (`null` for one left out, even when a stored value remains); read {@link BillingResource.autoRecharge} for the whole setting. */\nexport interface BillingAutoRechargeSaved {\n enabled: boolean\n thresholdCredits: number | null\n amountUsd: number | null\n}\n\n/** What `billing.checkout()` sends. */\nexport interface BillingCheckoutInput {\n /** A plan's monthly or yearly price id, or a credit pack's (`BillingTopUp.id`). */\n priceId: string\n /** Inferred from the price when omitted. */\n mode?: \"subscription\" | \"payment\"\n /** A path on the calling origin Stripe brings the person back to (`\"/billing\"`, a query allowed): one leading `/`, no host, no `#`. Wins over `embedded`. */\n returnPath?: string\n /** Set by an embedded first-party surface: return to the app's public checkout-complete page. */\n embedded?: boolean\n}\n\n/** A Stripe Checkout page to send the person to. */\nexport interface BillingCheckoutSession {\n url: string | null\n}\n\n/** What `billing.loadCredits()` sends. */\nexport interface BillingLoadInput {\n /** A whole dollar amount within `topUpRange`. */\n amountUsd: number\n /** As in {@link BillingCheckoutInput.returnPath}; wins over `embedded`. */\n returnPath?: string\n embedded?: boolean\n}\n\n/** A Stripe Checkout page for a load, and the credits it grants. */\nexport interface BillingLoadSession {\n url: string | null\n credits: number\n}\n\n/** What `billing.portal()` sends. */\nexport interface BillingPortalInput {\n /** Where the portal's Back goes: a path on the calling origin; default the app's `/billing`. */\n returnPath?: string\n}\n\n/** A Stripe Customer Portal page to send the person to. */\nexport interface BillingPortalSession {\n url: string\n}\n\n/** What `billing.changePlan()` sends. */\nexport interface BillingChangePlanInput {\n /** A subscription price id from the plans list. */\n newPriceId: string\n}\n\n/** What `billing.changePlan()` answers. */\nexport interface BillingChangePlanResult {\n subscriptionId: string\n /** The plan now in force: `\"basic\"`, `\"standard\"`, … */\n tier: string\n}\n"]}
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ // src/resources/user-settings.ts
4
+ var UserSettingsResource = class {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ client;
9
+ /**
10
+ * `GET /v1/user/settings` → the person's own settings. Throws
11
+ * `UnauthorizedError` (401) when signed out, `NotFoundError` with no
12
+ * profile row.
13
+ */
14
+ async get() {
15
+ const res = await this.client.request("GET", "/v1/user/settings");
16
+ return res.data;
17
+ }
18
+ /**
19
+ * `PATCH /v1/user/settings` → changes the fields sent and answers the
20
+ * settings as saved. A `NodaroError` with status 400 names an invalid
21
+ * value (`validation_error`), or says so for a patch with nothing to
22
+ * change; `ForbiddenError` for `publicOutputs: false` below the Standard
23
+ * plan; `NotFoundError` with no profile row.
24
+ */
25
+ async update(patch) {
26
+ const res = await this.client.request("PATCH", "/v1/user/settings", { body: patch });
27
+ return res.data;
28
+ }
29
+ };
30
+
31
+ exports.UserSettingsResource = UserSettingsResource;
32
+ //# sourceMappingURL=chunk-UIDVH3GP.cjs.map
33
+ //# sourceMappingURL=chunk-UIDVH3GP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/user-settings.ts"],"names":[],"mappings":";;;AAqFO,IAAM,uBAAN,MAA2B;AAAA,EAChC,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpB,MAAM,GAAA,GAA6B;AACjC,IAAA,MAAM,MAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,OAAO,mBAAmB,CAAA;AACxF,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAO,KAAA,EAAsD;AACjE,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAqC,SAAS,mBAAA,EAAqB,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAChH,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-UIDVH3GP.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * The signed-in person's own settings — the shape of `GET` / `PATCH\n * /v1/user/settings` (`backend/src/routes/user-settings.ts`, the source of\n * truth: keep these in sync if they change). A first-party app renders the\n * ones it cares about (the monthly statement opt-in on a billing screen, the\n * interface language) and sends back only the fields it changes.\n */\n\n/** How `{nodeRef}` placeholders render in prompt fields. */\nexport type VariableDisplayMode = \"raw\" | \"annotated\" | \"resolved\"\n/** What double-clicking a canvas node does. */\nexport type NodeDoubleClickAction = \"zoom\" | \"settings\"\n/** The interface languages Nodaro ships; the server refuses any other value. */\nexport type UserSettingsLocale = \"en\" | \"es\" | \"fr\" | \"de\" | \"pt-BR\" | \"ru\" | \"hi\" | \"ja\" | \"ko\" | \"zh-CN\" | \"he\" | \"ar\"\n\n/** One of the person's own Generate Text templates. */\nexport interface UserTextTemplate {\n id: string\n /** Up to 80 characters. */\n label: string\n /** Up to 10,000 characters. */\n systemPrompt: string\n defaultInput?: string\n /** 1–16,384. */\n defaultMaxTokens?: number\n llmModel?: string\n reasoningEffort?: string\n fansOut?: boolean\n requiresImageRef?: boolean\n}\n\n/** Per-user MCP defaults, sparse: a key left out keeps its stored value. */\nexport interface UserMcpPreferences {\n image?: { model?: string; aspectRatio?: string; resolution?: string; quality?: string }\n video?: { model?: string; aspectRatio?: string; duration?: number; resolution?: string }\n audio?: { ttsModel?: string; musicModel?: string }\n flows?: { enabled?: boolean }\n}\n\nexport interface UserSettings {\n /** The stored billing tier (`\"free\"`, `\"basic\"`, …). */\n tier: string | null\n /** Whether generations are visible in the public gallery. */\n publicOutputs: boolean\n /** Per-template overrides of the system prompts, by template key. */\n promptTemplates: Record<string, string>\n /** The person's own Generate Text templates. */\n textTemplates: UserTextTemplate[]\n /** The interface language; `null` = the browser's. */\n preferredLocale: UserSettingsLocale | null\n mcpPreferences: UserMcpPreferences\n showRecentNodes: boolean\n showMostUsedNodes: boolean\n variableDisplayMode: VariableDisplayMode\n nodeDoubleClickAction: NodeDoubleClickAction\n /** A statement of last month's credit usage by email on the 1st. Default `false`. */\n monthlyStatementEmail: boolean\n}\n\n/**\n * What `update()` sends: only the fields to change. `promptTemplates` and\n * `textTemplates` REPLACE the stored value whole (send the full map or list;\n * a template key the server does not know, or a value equal to the default,\n * is dropped); `mcpPreferences` merges one axis at a time.\n */\nexport interface UserSettingsPatch {\n /** `false` needs the Standard plan or above on Nodaro Cloud (`ForbiddenError` otherwise). */\n publicOutputs?: boolean\n promptTemplates?: Record<string, string>\n /** Up to 100. */\n textTemplates?: UserTextTemplate[]\n preferredLocale?: UserSettingsLocale | null\n mcpPreferences?: UserMcpPreferences\n showRecentNodes?: boolean\n showMostUsedNodes?: boolean\n variableDisplayMode?: VariableDisplayMode\n nodeDoubleClickAction?: NodeDoubleClickAction\n monthlyStatementEmail?: boolean\n}\n\n/** What `update()` answers: the settings as saved (without `tier`). */\nexport type UserSettingsSaved = Omit<UserSettings, \"tier\">\n\nexport class UserSettingsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/user/settings` → the person's own settings. Throws\n * `UnauthorizedError` (401) when signed out, `NotFoundError` with no\n * profile row.\n */\n async get(): Promise<UserSettings> {\n const res = await this.client.request<{ data: UserSettings }>(\"GET\", \"/v1/user/settings\")\n return res.data\n }\n\n /**\n * `PATCH /v1/user/settings` → changes the fields sent and answers the\n * settings as saved. A `NodaroError` with status 400 names an invalid\n * value (`validation_error`), or says so for a patch with nothing to\n * change; `ForbiddenError` for `publicOutputs: false` below the Standard\n * plan; `NotFoundError` with no profile row.\n */\n async update(patch: UserSettingsPatch): Promise<UserSettingsSaved> {\n const res = await this.client.request<{ data: UserSettingsSaved }>(\"PATCH\", \"/v1/user/settings\", { body: patch })\n return res.data\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { UploadsResource } from './chunk-WY4QRJZW.js';
2
+ import { UserSettingsResource } from './chunk-LR5TGCJP.js';
2
3
  import { VideoProResource } from './chunk-ERLXU47J.js';
3
4
  import { VoicesResource } from './chunk-T7N7DFQJ.js';
4
5
  import { WebhooksResource } from './chunk-YN6CBIIB.js';
@@ -10,7 +11,7 @@ import { ShotsResource } from './chunk-WVFAQBS7.js';
10
11
  import { StudioResource } from './chunk-AUKHMT53.js';
11
12
  import { TemplatesResource } from './chunk-M7VSFZMV.js';
12
13
  import { TrashResource } from './chunk-2SQ7V6EX.js';
13
- import { TrendsResource } from './chunk-YXVMQEJX.js';
14
+ import { TrendsResource } from './chunk-35CNQ3WW.js';
14
15
  import { TutorialsResource } from './chunk-HPXE3NZW.js';
15
16
  import { PalettesResource } from './chunk-WEQWU2IC.js';
16
17
  import { PickerCatalogsResource } from './chunk-KFZOJBI5.js';
@@ -39,14 +40,14 @@ import { CollectionsResource } from './chunk-4WRDR4GN.js';
39
40
  import { CommunityResource } from './chunk-SFB4YLCS.js';
40
41
  import { CompetitorsResource } from './chunk-BU5A6K4C.js';
41
42
  import { CopilotResource } from './chunk-D2ILCSOQ.js';
42
- import { NodaroClientCore } from './chunk-XISHBW5I.js';
43
+ import { NodaroClientCore } from './chunk-F4MFMHTQ.js';
43
44
  import { CreaturesResource } from './chunk-CK3AMMSC.js';
44
45
  import { CreditsResource } from './chunk-7QK2NXJA.js';
45
46
  import { DeveloperAppsResource } from './chunk-65E3JBFZ.js';
46
47
  import { AppsResource } from './chunk-7LODCIQK.js';
47
48
  import { AudioResource } from './chunk-3QFTP5P5.js';
48
- import { BillingResource } from './chunk-WYYDWJFF.js';
49
- import { CastSwapResource } from './chunk-OCRUDBPG.js';
49
+ import { BillingResource } from './chunk-ZVKEPVDQ.js';
50
+ import { CastSwapResource } from './chunk-DV6GTEX5.js';
50
51
  import { CatalogsResource } from './chunk-KG4R454Z.js';
51
52
  import { CharactersResource } from './chunk-EJSGJDZY.js';
52
53
 
@@ -80,6 +81,8 @@ var NodaroClient = class _NodaroClient extends NodaroClientCore {
80
81
  media;
81
82
  audio;
82
83
  credits;
84
+ /** The signed-in person's own settings (the interface language, the monthly statement opt-in, …). */
85
+ userSettings;
83
86
  /** Plans and prices, the subscription, and how this deployment bills. */
84
87
  billing;
85
88
  uploads;
@@ -138,6 +141,7 @@ var NodaroClient = class _NodaroClient extends NodaroClientCore {
138
141
  this.media = new MediaResource(this);
139
142
  this.audio = new AudioResource(this);
140
143
  this.credits = new CreditsResource(this);
144
+ this.userSettings = new UserSettingsResource(this);
141
145
  this.billing = new BillingResource(this);
142
146
  this.uploads = new UploadsResource(this);
143
147
  this.library = new LibraryResource(this);
@@ -192,5 +196,5 @@ function createClient(opts) {
192
196
  }
193
197
 
194
198
  export { NodaroClient, createClient };
195
- //# sourceMappingURL=chunk-EC6MC46Y.js.map
196
- //# sourceMappingURL=chunk-EC6MC46Y.js.map
199
+ //# sourceMappingURL=chunk-WD556UAW.js.map
200
+ //# sourceMappingURL=chunk-WD556UAW.js.map