segmind 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,3 +1,6 @@
1
+ import { S as SessionToken, a as SessionTokenProvider } from './errors-CcHEuSmR.cjs';
2
+ export { A as APIConnectionError, I as InferenceFailed, b as InferenceTimeout, c as InsufficientCredits, R as RateLimited, d as SegmindError } from './errors-CcHEuSmR.cjs';
3
+
1
4
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
2
5
  /** Returns the signed-in user's token, or null when there is none. Called before every request. */
3
6
  type TokenProvider = () => string | null | undefined | Promise<string | null | undefined>;
@@ -209,7 +212,10 @@ declare class Files {
209
212
  private stage;
210
213
  /** A file in the caller's asset library: presign, PUT, then confirm to register it. */
211
214
  private persist;
212
- /** A PUT to the same key is idempotent, so it retries. `bare` keeps the API key off the storage host. */
215
+ /**
216
+ * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
217
+ * sent again, unlike a stream. `bare` keeps the API key off the storage host.
218
+ */
213
219
  private put;
214
220
  }
215
221
 
@@ -432,6 +438,37 @@ declare class PixelflowJob {
432
438
  wait(options?: PixelflowWaitOptions): Promise<PixelflowStatus>;
433
439
  }
434
440
 
441
+ interface CreateSessionTokenOptions {
442
+ /** The session model the token opens, and the only one. */
443
+ slug: string;
444
+ /** The most the session may spend, in credits: above 0, at most 100. The gateway's default applies when omitted. */
445
+ creditCeiling?: number;
446
+ /** Seconds the token can be used to open a session, at most 120. A session outlives its token. */
447
+ ttl?: number;
448
+ /** What the session is recorded as. Default `SDK-JS`; pass `SDK-RN` for a phone app's sessions. */
449
+ initiator?: Initiator;
450
+ signal?: AbortSignal;
451
+ }
452
+ /**
453
+ * Session tokens for realtime models. A token is minted on a server with the
454
+ * API key, opens one session of one model, and caps what that session may
455
+ * spend, so it is safe to hand to a browser or a phone app.
456
+ */
457
+ declare class Realtime {
458
+ private readonly client;
459
+ constructor(client: Segmind);
460
+ /**
461
+ * Mints a session token. Serve it from your backend to the app that opens
462
+ * the session with `connect()` from `segmind/realtime`.
463
+ */
464
+ createToken(options: CreateSessionTokenOptions): Promise<SessionToken>;
465
+ /**
466
+ * A `tokenProvider` that mints with this client's key, for opening sessions
467
+ * from a server: `connect(slug, { tokenProvider: segmind.realtime.tokenProvider() })`.
468
+ */
469
+ tokenProvider(options?: Omit<CreateSessionTokenOptions, 'slug' | 'signal'>): SessionTokenProvider;
470
+ }
471
+
435
472
  /**
436
473
  * What a registration subscribes to. `PIXELFLOW` covers PixelFlow runs; the
437
474
  * others are the platform's remaining subscription types.
@@ -592,6 +629,8 @@ declare class Segmind {
592
629
  readonly webhooks: Webhooks;
593
630
  /** Run published PixelFlow workflows. */
594
631
  readonly pixelflows: PixelFlows;
632
+ /** Session tokens for realtime models. The sessions themselves open from `segmind/realtime`. */
633
+ readonly realtime: Realtime;
595
634
  /** @internal */
596
635
  readonly http: HttpClient;
597
636
  constructor(options?: ClientOptions);
@@ -754,64 +793,7 @@ declare function imageUrl(input: ImageInput, options?: {
754
793
  mimeType?: string;
755
794
  }): Promise<ImageUrlPart>;
756
795
 
757
- interface SegmindErrorOptions {
758
- status?: number;
759
- detail?: string;
760
- requestId?: string;
761
- body?: unknown;
762
- cause?: unknown;
763
- }
764
- /** Base class of every error the SDK throws (except an `AbortSignal`'s own reason). */
765
- declare class SegmindError extends Error {
766
- /** HTTP status, when the error came from a response. */
767
- readonly status: number | undefined;
768
- /** The server's error text (`error` in the response body), when it sent one. */
769
- readonly detail: string | undefined;
770
- /** The v2 request id the error belongs to, when there is one. */
771
- readonly requestId: string | undefined;
772
- /** The parsed response body, or its text when it was not JSON. */
773
- readonly body: unknown;
774
- constructor(message: string, options?: SegmindErrorOptions);
775
- /** Reads the response body and builds the error. Consumes the body. */
776
- static fromResponse(response: Response, requestId?: string): Promise<SegmindError>;
777
- }
778
- /** The request never got a response: DNS, TLS, connection reset, or the client's timeout. */
779
- declare class APIConnectionError extends SegmindError {
780
- }
781
- /**
782
- * The account cannot pay for the request. The gateway reports this at submit, or
783
- * as a failed job when the balance is positive but below the model's cost, so
784
- * this one class covers both. `detail` holds the server's message.
785
- */
786
- declare class InsufficientCredits extends SegmindError {
787
- }
788
- /**
789
- * Too many requests, after the SDK's own retries for calls that are safe to
790
- * repeat. `retryAfterMs` is set when the server sent `Retry-After` and the
791
- * runtime could read it: a browser only sees the header if the server exposes it.
792
- */
793
- declare class RateLimited extends SegmindError {
794
- readonly retryAfterMs: number | undefined;
795
- constructor(message: string, options?: SegmindErrorOptions & {
796
- retryAfterMs?: number;
797
- });
798
- }
799
- /** A v2 request reached `FAILED`. The server's error text is in `detail`. */
800
- declare class InferenceFailed extends SegmindError {
801
- /** The status body that reported the failure. */
802
- readonly statusBody: Record<string, unknown>;
803
- constructor(requestId: string, statusBody: Record<string, unknown>, detail?: string);
804
- }
805
- /**
806
- * `wait()` ran past its timeout. The request may still finish on the server:
807
- * `job.status()` or a new `wait()` picks it up again.
808
- */
809
- declare class InferenceTimeout extends SegmindError {
810
- readonly elapsedMs: number;
811
- constructor(requestId: string, elapsedMs: number);
812
- }
813
-
814
- declare const VERSION = "0.5.0";
796
+ declare const VERSION = "0.6.0";
815
797
 
816
798
  /** `new Segmind().run(...)` with the key from `SEGMIND_API_KEY`. */
817
799
  declare const run: (slug: string, params?: Params, options?: RunOptions) => Promise<RunResult>;
@@ -847,5 +829,5 @@ declare const webhooks: Pick<Webhooks, 'get' | 'add' | 'update' | 'delete' | 'lo
847
829
  /** `new Segmind().pixelflows` with the key from `SEGMIND_API_KEY`. */
848
830
  declare const pixelflows: Pick<PixelFlows, 'run' | 'submit' | 'getStatus' | 'poll'>;
849
831
 
850
- export { APIConnectionError, Accounts, ChatResponse, DEFAULT_BASE_URL, DEFAULT_CONSOLE_URL, DEFAULT_SPOT_URL, DEFAULT_WAIT_INTERVAL_MS, DEFAULT_WAIT_TIMEOUT_MS, Files, Generations, InferenceFailed, InferenceTimeout, InsufficientCredits, Job, Models, PixelFlows, PixelflowJob, RateLimited, Segmind, SegmindError, VERSION, Webhooks, accounts, chat, chatSync, files, generations, imageUrl, job, models, pixelflows, run, runSync, submit, submitChat, webhooks };
851
- export type { AccountCredits, CallOptions, ChatMessage, ChatParams, ClientOptions, FileInput, Generation, GenerationsListOptions, HistoryOptions, ImageInput, ImageUrlPart, Initiator, InitiatorOptions, JobState, JobStatus, ModelInfo, ModelInput, ModelListParams, ModelOutput, ModelSort, ModelsPage, Page, Params, PixelflowStatus, PixelflowSubmitOptions, PixelflowWaitOptions, PollInterval, RequestRecord, RunOptions, RunResult, SubmitOptions, SubmitResponse, TokenProvider, UploadOptions, UploadedFile, WaitOptions, Webhook, WebhookDelivery, WebhookEventType };
832
+ export { Accounts, ChatResponse, DEFAULT_BASE_URL, DEFAULT_CONSOLE_URL, DEFAULT_SPOT_URL, DEFAULT_WAIT_INTERVAL_MS, DEFAULT_WAIT_TIMEOUT_MS, Files, Generations, Job, Models, PixelFlows, PixelflowJob, Realtime, Segmind, SessionToken, SessionTokenProvider, VERSION, Webhooks, accounts, chat, chatSync, files, generations, imageUrl, job, models, pixelflows, run, runSync, submit, submitChat, webhooks };
833
+ export type { AccountCredits, CallOptions, ChatMessage, ChatParams, ClientOptions, CreateSessionTokenOptions, FileInput, Generation, GenerationsListOptions, HistoryOptions, ImageInput, ImageUrlPart, Initiator, InitiatorOptions, JobState, JobStatus, ModelInfo, ModelInput, ModelListParams, ModelOutput, ModelSort, ModelsPage, Page, Params, PixelflowStatus, PixelflowSubmitOptions, PixelflowWaitOptions, PollInterval, RequestRecord, RunOptions, RunResult, SubmitOptions, SubmitResponse, TokenProvider, UploadOptions, UploadedFile, WaitOptions, Webhook, WebhookDelivery, WebhookEventType };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { S as SessionToken, a as SessionTokenProvider } from './errors-CcHEuSmR.js';
2
+ export { A as APIConnectionError, I as InferenceFailed, b as InferenceTimeout, c as InsufficientCredits, R as RateLimited, d as SegmindError } from './errors-CcHEuSmR.js';
3
+
1
4
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
2
5
  /** Returns the signed-in user's token, or null when there is none. Called before every request. */
3
6
  type TokenProvider = () => string | null | undefined | Promise<string | null | undefined>;
@@ -209,7 +212,10 @@ declare class Files {
209
212
  private stage;
210
213
  /** A file in the caller's asset library: presign, PUT, then confirm to register it. */
211
214
  private persist;
212
- /** A PUT to the same key is idempotent, so it retries. `bare` keeps the API key off the storage host. */
215
+ /**
216
+ * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
217
+ * sent again, unlike a stream. `bare` keeps the API key off the storage host.
218
+ */
213
219
  private put;
214
220
  }
215
221
 
@@ -432,6 +438,37 @@ declare class PixelflowJob {
432
438
  wait(options?: PixelflowWaitOptions): Promise<PixelflowStatus>;
433
439
  }
434
440
 
441
+ interface CreateSessionTokenOptions {
442
+ /** The session model the token opens, and the only one. */
443
+ slug: string;
444
+ /** The most the session may spend, in credits: above 0, at most 100. The gateway's default applies when omitted. */
445
+ creditCeiling?: number;
446
+ /** Seconds the token can be used to open a session, at most 120. A session outlives its token. */
447
+ ttl?: number;
448
+ /** What the session is recorded as. Default `SDK-JS`; pass `SDK-RN` for a phone app's sessions. */
449
+ initiator?: Initiator;
450
+ signal?: AbortSignal;
451
+ }
452
+ /**
453
+ * Session tokens for realtime models. A token is minted on a server with the
454
+ * API key, opens one session of one model, and caps what that session may
455
+ * spend, so it is safe to hand to a browser or a phone app.
456
+ */
457
+ declare class Realtime {
458
+ private readonly client;
459
+ constructor(client: Segmind);
460
+ /**
461
+ * Mints a session token. Serve it from your backend to the app that opens
462
+ * the session with `connect()` from `segmind/realtime`.
463
+ */
464
+ createToken(options: CreateSessionTokenOptions): Promise<SessionToken>;
465
+ /**
466
+ * A `tokenProvider` that mints with this client's key, for opening sessions
467
+ * from a server: `connect(slug, { tokenProvider: segmind.realtime.tokenProvider() })`.
468
+ */
469
+ tokenProvider(options?: Omit<CreateSessionTokenOptions, 'slug' | 'signal'>): SessionTokenProvider;
470
+ }
471
+
435
472
  /**
436
473
  * What a registration subscribes to. `PIXELFLOW` covers PixelFlow runs; the
437
474
  * others are the platform's remaining subscription types.
@@ -592,6 +629,8 @@ declare class Segmind {
592
629
  readonly webhooks: Webhooks;
593
630
  /** Run published PixelFlow workflows. */
594
631
  readonly pixelflows: PixelFlows;
632
+ /** Session tokens for realtime models. The sessions themselves open from `segmind/realtime`. */
633
+ readonly realtime: Realtime;
595
634
  /** @internal */
596
635
  readonly http: HttpClient;
597
636
  constructor(options?: ClientOptions);
@@ -754,64 +793,7 @@ declare function imageUrl(input: ImageInput, options?: {
754
793
  mimeType?: string;
755
794
  }): Promise<ImageUrlPart>;
756
795
 
757
- interface SegmindErrorOptions {
758
- status?: number;
759
- detail?: string;
760
- requestId?: string;
761
- body?: unknown;
762
- cause?: unknown;
763
- }
764
- /** Base class of every error the SDK throws (except an `AbortSignal`'s own reason). */
765
- declare class SegmindError extends Error {
766
- /** HTTP status, when the error came from a response. */
767
- readonly status: number | undefined;
768
- /** The server's error text (`error` in the response body), when it sent one. */
769
- readonly detail: string | undefined;
770
- /** The v2 request id the error belongs to, when there is one. */
771
- readonly requestId: string | undefined;
772
- /** The parsed response body, or its text when it was not JSON. */
773
- readonly body: unknown;
774
- constructor(message: string, options?: SegmindErrorOptions);
775
- /** Reads the response body and builds the error. Consumes the body. */
776
- static fromResponse(response: Response, requestId?: string): Promise<SegmindError>;
777
- }
778
- /** The request never got a response: DNS, TLS, connection reset, or the client's timeout. */
779
- declare class APIConnectionError extends SegmindError {
780
- }
781
- /**
782
- * The account cannot pay for the request. The gateway reports this at submit, or
783
- * as a failed job when the balance is positive but below the model's cost, so
784
- * this one class covers both. `detail` holds the server's message.
785
- */
786
- declare class InsufficientCredits extends SegmindError {
787
- }
788
- /**
789
- * Too many requests, after the SDK's own retries for calls that are safe to
790
- * repeat. `retryAfterMs` is set when the server sent `Retry-After` and the
791
- * runtime could read it: a browser only sees the header if the server exposes it.
792
- */
793
- declare class RateLimited extends SegmindError {
794
- readonly retryAfterMs: number | undefined;
795
- constructor(message: string, options?: SegmindErrorOptions & {
796
- retryAfterMs?: number;
797
- });
798
- }
799
- /** A v2 request reached `FAILED`. The server's error text is in `detail`. */
800
- declare class InferenceFailed extends SegmindError {
801
- /** The status body that reported the failure. */
802
- readonly statusBody: Record<string, unknown>;
803
- constructor(requestId: string, statusBody: Record<string, unknown>, detail?: string);
804
- }
805
- /**
806
- * `wait()` ran past its timeout. The request may still finish on the server:
807
- * `job.status()` or a new `wait()` picks it up again.
808
- */
809
- declare class InferenceTimeout extends SegmindError {
810
- readonly elapsedMs: number;
811
- constructor(requestId: string, elapsedMs: number);
812
- }
813
-
814
- declare const VERSION = "0.5.0";
796
+ declare const VERSION = "0.6.0";
815
797
 
816
798
  /** `new Segmind().run(...)` with the key from `SEGMIND_API_KEY`. */
817
799
  declare const run: (slug: string, params?: Params, options?: RunOptions) => Promise<RunResult>;
@@ -847,5 +829,5 @@ declare const webhooks: Pick<Webhooks, 'get' | 'add' | 'update' | 'delete' | 'lo
847
829
  /** `new Segmind().pixelflows` with the key from `SEGMIND_API_KEY`. */
848
830
  declare const pixelflows: Pick<PixelFlows, 'run' | 'submit' | 'getStatus' | 'poll'>;
849
831
 
850
- export { APIConnectionError, Accounts, ChatResponse, DEFAULT_BASE_URL, DEFAULT_CONSOLE_URL, DEFAULT_SPOT_URL, DEFAULT_WAIT_INTERVAL_MS, DEFAULT_WAIT_TIMEOUT_MS, Files, Generations, InferenceFailed, InferenceTimeout, InsufficientCredits, Job, Models, PixelFlows, PixelflowJob, RateLimited, Segmind, SegmindError, VERSION, Webhooks, accounts, chat, chatSync, files, generations, imageUrl, job, models, pixelflows, run, runSync, submit, submitChat, webhooks };
851
- export type { AccountCredits, CallOptions, ChatMessage, ChatParams, ClientOptions, FileInput, Generation, GenerationsListOptions, HistoryOptions, ImageInput, ImageUrlPart, Initiator, InitiatorOptions, JobState, JobStatus, ModelInfo, ModelInput, ModelListParams, ModelOutput, ModelSort, ModelsPage, Page, Params, PixelflowStatus, PixelflowSubmitOptions, PixelflowWaitOptions, PollInterval, RequestRecord, RunOptions, RunResult, SubmitOptions, SubmitResponse, TokenProvider, UploadOptions, UploadedFile, WaitOptions, Webhook, WebhookDelivery, WebhookEventType };
832
+ export { Accounts, ChatResponse, DEFAULT_BASE_URL, DEFAULT_CONSOLE_URL, DEFAULT_SPOT_URL, DEFAULT_WAIT_INTERVAL_MS, DEFAULT_WAIT_TIMEOUT_MS, Files, Generations, Job, Models, PixelFlows, PixelflowJob, Realtime, Segmind, SessionToken, SessionTokenProvider, VERSION, Webhooks, accounts, chat, chatSync, files, generations, imageUrl, job, models, pixelflows, run, runSync, submit, submitChat, webhooks };
833
+ export type { AccountCredits, CallOptions, ChatMessage, ChatParams, ClientOptions, CreateSessionTokenOptions, FileInput, Generation, GenerationsListOptions, HistoryOptions, ImageInput, ImageUrlPart, Initiator, InitiatorOptions, JobState, JobStatus, ModelInfo, ModelInput, ModelListParams, ModelOutput, ModelSort, ModelsPage, Page, Params, PixelflowStatus, PixelflowSubmitOptions, PixelflowWaitOptions, PollInterval, RequestRecord, RunOptions, RunResult, SubmitOptions, SubmitResponse, TokenProvider, UploadOptions, UploadedFile, WaitOptions, Webhook, WebhookDelivery, WebhookEventType };
package/dist/index.js CHANGED
@@ -1,106 +1,13 @@
1
- // src/core/errors.ts
2
- var SegmindError = class extends Error {
3
- /** HTTP status, when the error came from a response. */
4
- status;
5
- /** The server's error text (`error` in the response body), when it sent one. */
6
- detail;
7
- /** The v2 request id the error belongs to, when there is one. */
8
- requestId;
9
- /** The parsed response body, or its text when it was not JSON. */
10
- body;
11
- constructor(message, options = {}) {
12
- super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
13
- this.name = new.target.name;
14
- this.status = options.status;
15
- this.detail = options.detail;
16
- this.requestId = options.requestId;
17
- this.body = options.body;
18
- }
19
- /** Reads the response body and builds the error. Consumes the body. */
20
- static fromResponse(response, requestId) {
21
- return errorFromResponse(response, requestId);
22
- }
23
- };
24
- var APIConnectionError = class extends SegmindError {
25
- };
26
- var InsufficientCredits = class extends SegmindError {
27
- };
28
- var RateLimited = class extends SegmindError {
29
- retryAfterMs;
30
- constructor(message, options = {}) {
31
- super(message, options);
32
- this.retryAfterMs = options.retryAfterMs;
33
- }
34
- };
35
- var InferenceFailed = class extends SegmindError {
36
- /** The status body that reported the failure. */
37
- statusBody;
38
- constructor(requestId, statusBody, detail) {
39
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
40
- super(detail ? `request ${requestId} failed: ${detail}` : `request ${requestId} failed`, {
41
- detail,
42
- requestId,
43
- body: statusBody
44
- });
45
- this.statusBody = statusBody;
46
- }
47
- };
48
- var InferenceTimeout = class extends SegmindError {
49
- elapsedMs;
50
- constructor(requestId, elapsedMs) {
51
- super(`request ${requestId} did not finish within ${Math.round(elapsedMs)} ms`, { requestId });
52
- this.elapsedMs = elapsedMs;
53
- }
54
- };
55
- async function errorFromResponse(response, requestId) {
56
- const text = await response.text().catch(() => "");
57
- let body = text;
58
- try {
59
- body = text ? JSON.parse(text) : void 0;
60
- } catch {
61
- }
62
- const detail = errorDetail(body) ?? plainText(body);
63
- const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
64
- const options = { status: response.status, detail, requestId, body };
65
- if (response.status === 429) {
66
- return new RateLimited(message, { ...options, retryAfterMs: parseRetryAfter(response.headers.get("retry-after")) });
67
- }
68
- if (response.status === 402 || isOutOfCredits(detail)) return new InsufficientCredits(message, options);
69
- return new SegmindError(message, options);
70
- }
71
- function requestFailure(requestId, statusBody, detail) {
72
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
73
- if (isOutOfCredits(detail)) {
74
- return new InsufficientCredits(`request ${requestId} failed: ${detail}`, { detail, requestId, body: statusBody });
75
- }
76
- return new InferenceFailed(requestId, statusBody, detail);
77
- }
78
- function parseRetryAfter(value, now = Date.now()) {
79
- if (!value) return void 0;
80
- const seconds = Number(value);
81
- if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
82
- const date = Date.parse(value);
83
- return Number.isNaN(date) ? void 0 : Math.max(date - now, 0);
84
- }
85
- function isOutOfCredits(detail) {
86
- return detail?.startsWith("Insufficient credits.") ?? false;
87
- }
88
- function plainText(body) {
89
- if (typeof body !== "string" || !body || body.trimStart().startsWith("<")) return void 0;
90
- return body.slice(0, 500);
91
- }
92
- function errorDetail(body) {
93
- if (!body || typeof body !== "object") return void 0;
94
- const record2 = body;
95
- for (const key of ["error", "message", "detail"]) {
96
- const value = record2[key];
97
- if (typeof value === "string" && value) return value;
98
- if (value && typeof value === "object" && typeof value.message === "string") {
99
- return value.message;
100
- }
101
- }
102
- return void 0;
103
- }
1
+ import {
2
+ APIConnectionError,
3
+ InferenceFailed,
4
+ InferenceTimeout,
5
+ InsufficientCredits,
6
+ RateLimited,
7
+ SegmindError,
8
+ parseRetryAfter,
9
+ requestFailure
10
+ } from "./chunk-PS5KUT7P.js";
104
11
 
105
12
  // src/chat.ts
106
13
  var ChatResponse = class {
@@ -441,22 +348,22 @@ function mimeFromName(name) {
441
348
  const extension = name.includes(".") ? name.split(".").pop().toLowerCase() : "";
442
349
  return MIME_BY_EXTENSION[extension];
443
350
  }
444
- async function readFileInput(input, options) {
445
- let bytes;
351
+ async function openFileInput(input, options) {
352
+ let body;
446
353
  let name = options.filename;
447
354
  let mimeType = options.mimeType;
448
355
  if (typeof input === "string") {
449
356
  if (detectRuntime() !== "node") {
450
357
  throw new SegmindError(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
451
358
  }
452
- const { readFile } = await import(
359
+ const { openAsBlob } = await import(
453
360
  /* webpackIgnore: true */
454
361
  /* turbopackIgnore: true */
455
362
  /* @vite-ignore */
456
- "node:fs/promises"
363
+ "node:fs"
457
364
  );
458
365
  try {
459
- bytes = new Uint8Array(await readFile(input));
366
+ body = await openAsBlob(input);
460
367
  } catch (err) {
461
368
  throw new SegmindError(`${options.caller}: cannot read ${JSON.stringify(input)}: ${err.message}`, {
462
369
  cause: err
@@ -464,13 +371,13 @@ async function readFileInput(input, options) {
464
371
  }
465
372
  name ??= input.split(/[\\/]/).pop();
466
373
  } else if (typeof Blob !== "undefined" && input instanceof Blob) {
467
- bytes = new Uint8Array(await input.arrayBuffer());
374
+ body = input;
468
375
  name ??= input.name || void 0;
469
376
  mimeType ??= input.type || void 0;
470
377
  } else {
471
- bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
378
+ body = input instanceof Uint8Array ? input : new Uint8Array(input);
472
379
  }
473
- mimeType ??= name && mimeFromName(name) || sniff(bytes);
380
+ mimeType ??= name && mimeFromName(name) || sniff(await head(body));
474
381
  if (!name || !name.includes(".")) {
475
382
  const extension = mimeType ? EXTENSION_BY_MIME[mimeType] : void 0;
476
383
  if (!extension) {
@@ -478,7 +385,17 @@ async function readFileInput(input, options) {
478
385
  }
479
386
  name = `${name || "upload"}.${extension}`;
480
387
  }
481
- return { bytes, filename: name, mimeType };
388
+ const size = body instanceof Uint8Array ? body.byteLength : body.size;
389
+ return { body, size, filename: name, mimeType };
390
+ }
391
+ async function readFileInput(input, options) {
392
+ const { body, filename, mimeType } = await openFileInput(input, options);
393
+ const bytes = body instanceof Uint8Array ? body : new Uint8Array(await body.arrayBuffer());
394
+ return { bytes, filename, mimeType };
395
+ }
396
+ async function head(body) {
397
+ if (body instanceof Uint8Array) return body;
398
+ return new Uint8Array(await body.slice(0, 16).arrayBuffer());
482
399
  }
483
400
  function sniff(bytes) {
484
401
  const at = (offset, signature) => signature.every((b, i) => bytes[offset + i] === b);
@@ -508,16 +425,16 @@ var Files = class {
508
425
  return this.uploadOne(input, options);
509
426
  }
510
427
  async uploadOne(input, options) {
511
- const file = await readFileInput(input, { ...options, caller: "files.upload" });
428
+ const file = await openFileInput(input, { ...options, caller: "files.upload" });
512
429
  const url = options.persist ? await this.persist(file, options.signal) : await this.stage(file, options.signal);
513
- return { url, filename: file.filename, size: file.bytes.byteLength, persistent: options.persist === true };
430
+ return { url, filename: file.filename, size: file.size, persistent: options.persist === true };
514
431
  }
515
432
  /** A temporary model input on the inference API's input bucket. */
516
433
  async stage(file, signal) {
517
434
  const ticket = await this.client.http.json({
518
435
  method: "POST",
519
436
  url: `${this.client.spotURL}/inference-request/input-presign`,
520
- body: { filename: file.filename, size: file.bytes.byteLength },
437
+ body: { filename: file.filename, size: file.size },
521
438
  signal,
522
439
  retry: true
523
440
  });
@@ -540,7 +457,7 @@ var Files = class {
540
457
  const ticket = await http.json({
541
458
  method: "POST",
542
459
  url: `${assetsURL}/upload-asset/presign`,
543
- body: { filename: file.filename, contentType, size: file.bytes.byteLength },
460
+ body: { filename: file.filename, contentType, size: file.size },
544
461
  signal,
545
462
  retry: true
546
463
  });
@@ -559,9 +476,12 @@ var Files = class {
559
476
  });
560
477
  return confirmed.asset?.url ?? ticket.publicUrl;
561
478
  }
562
- /** A PUT to the same key is idempotent, so it retries. `bare` keeps the API key off the storage host. */
479
+ /**
480
+ * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
481
+ * sent again, unlike a stream. `bare` keeps the API key off the storage host.
482
+ */
563
483
  async put(url, file, headers, signal) {
564
- await this.client.http.request({ method: "PUT", url, rawBody: file.bytes, headers, bare: true, signal, retry: true });
484
+ await this.client.http.request({ method: "PUT", url, rawBody: file.body, headers, bare: true, signal, retry: true });
565
485
  }
566
486
  };
567
487
 
@@ -805,8 +725,40 @@ function failureDetail(body) {
805
725
  return void 0;
806
726
  }
807
727
 
728
+ // src/realtime-tokens.ts
729
+ var Realtime = class {
730
+ constructor(client2) {
731
+ this.client = client2;
732
+ }
733
+ client;
734
+ /**
735
+ * Mints a session token. Serve it from your backend to the app that opens
736
+ * the session with `connect()` from `segmind/realtime`.
737
+ */
738
+ async createToken(options) {
739
+ const body = { slug: options.slug };
740
+ if (options.creditCeiling !== void 0) body.credit_ceiling = options.creditCeiling;
741
+ if (options.ttl !== void 0) body.ttl = options.ttl;
742
+ return this.client.http.json({
743
+ method: "POST",
744
+ url: `${this.client.baseURL}/v1/realtime/token`,
745
+ body,
746
+ headers: options.initiator ? { "X-Initiator": options.initiator } : void 0,
747
+ signal: options.signal,
748
+ retry: true
749
+ });
750
+ }
751
+ /**
752
+ * A `tokenProvider` that mints with this client's key, for opening sessions
753
+ * from a server: `connect(slug, { tokenProvider: segmind.realtime.tokenProvider() })`.
754
+ */
755
+ tokenProvider(options = {}) {
756
+ return (slug) => this.createToken({ ...options, slug });
757
+ }
758
+ };
759
+
808
760
  // src/version.ts
809
- var VERSION = "0.5.0";
761
+ var VERSION = "0.6.0";
810
762
 
811
763
  // src/webhooks.ts
812
764
  var Webhooks = class {
@@ -897,6 +849,8 @@ var Segmind = class {
897
849
  webhooks;
898
850
  /** Run published PixelFlow workflows. */
899
851
  pixelflows;
852
+ /** Session tokens for realtime models. The sessions themselves open from `segmind/realtime`. */
853
+ realtime;
900
854
  /** @internal */
901
855
  http;
902
856
  constructor(options = {}) {
@@ -941,6 +895,7 @@ var Segmind = class {
941
895
  this.generations = new Generations(this);
942
896
  this.webhooks = new Webhooks(this);
943
897
  this.pixelflows = new PixelFlows(this);
898
+ this.realtime = new Realtime(this);
944
899
  }
945
900
  /**
946
901
  * Runs a model and returns its result: submits to the v2 queue, then polls
@@ -1235,6 +1190,7 @@ export {
1235
1190
  PixelFlows,
1236
1191
  PixelflowJob,
1237
1192
  RateLimited,
1193
+ Realtime,
1238
1194
  Segmind,
1239
1195
  SegmindError,
1240
1196
  VERSION,