segmind 0.5.1 → 0.6.1

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.cjs CHANGED
@@ -1,189 +1,25 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
29
2
 
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- APIConnectionError: () => APIConnectionError,
34
- Accounts: () => Accounts,
35
- ChatResponse: () => ChatResponse,
36
- DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
37
- DEFAULT_CONSOLE_URL: () => DEFAULT_CONSOLE_URL,
38
- DEFAULT_SPOT_URL: () => DEFAULT_SPOT_URL,
39
- DEFAULT_WAIT_INTERVAL_MS: () => DEFAULT_WAIT_INTERVAL_MS,
40
- DEFAULT_WAIT_TIMEOUT_MS: () => DEFAULT_WAIT_TIMEOUT_MS,
41
- Files: () => Files,
42
- Generations: () => Generations,
43
- InferenceFailed: () => InferenceFailed,
44
- InferenceTimeout: () => InferenceTimeout,
45
- InsufficientCredits: () => InsufficientCredits,
46
- Job: () => Job,
47
- Models: () => Models,
48
- PixelFlows: () => PixelFlows,
49
- PixelflowJob: () => PixelflowJob,
50
- RateLimited: () => RateLimited,
51
- Segmind: () => Segmind,
52
- SegmindError: () => SegmindError,
53
- VERSION: () => VERSION,
54
- Webhooks: () => Webhooks,
55
- accounts: () => accounts,
56
- chat: () => chat,
57
- chatSync: () => chatSync,
58
- files: () => files,
59
- generations: () => generations,
60
- imageUrl: () => imageUrl,
61
- job: () => job,
62
- models: () => models,
63
- pixelflows: () => pixelflows,
64
- run: () => run,
65
- runSync: () => runSync,
66
- submit: () => submit,
67
- submitChat: () => submitChat,
68
- webhooks: () => webhooks
69
- });
70
- module.exports = __toCommonJS(index_exports);
71
3
 
72
- // src/core/errors.ts
73
- var SegmindError = class extends Error {
74
- /** HTTP status, when the error came from a response. */
75
- status;
76
- /** The server's error text (`error` in the response body), when it sent one. */
77
- detail;
78
- /** The v2 request id the error belongs to, when there is one. */
79
- requestId;
80
- /** The parsed response body, or its text when it was not JSON. */
81
- body;
82
- constructor(message, options = {}) {
83
- super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
84
- this.name = new.target.name;
85
- this.status = options.status;
86
- this.detail = options.detail;
87
- this.requestId = options.requestId;
88
- this.body = options.body;
89
- }
90
- /** Reads the response body and builds the error. Consumes the body. */
91
- static fromResponse(response, requestId) {
92
- return errorFromResponse(response, requestId);
93
- }
94
- };
95
- var APIConnectionError = class extends SegmindError {
96
- };
97
- var InsufficientCredits = class extends SegmindError {
98
- };
99
- var RateLimited = class extends SegmindError {
100
- retryAfterMs;
101
- constructor(message, options = {}) {
102
- super(message, options);
103
- this.retryAfterMs = options.retryAfterMs;
104
- }
105
- };
106
- var InferenceFailed = class extends SegmindError {
107
- /** The status body that reported the failure. */
108
- statusBody;
109
- constructor(requestId, statusBody, detail) {
110
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
111
- super(detail ? `request ${requestId} failed: ${detail}` : `request ${requestId} failed`, {
112
- detail,
113
- requestId,
114
- body: statusBody
115
- });
116
- this.statusBody = statusBody;
117
- }
118
- };
119
- var InferenceTimeout = class extends SegmindError {
120
- elapsedMs;
121
- constructor(requestId, elapsedMs) {
122
- super(`request ${requestId} did not finish within ${Math.round(elapsedMs)} ms`, { requestId });
123
- this.elapsedMs = elapsedMs;
124
- }
125
- };
126
- async function errorFromResponse(response, requestId) {
127
- const text = await response.text().catch(() => "");
128
- let body = text;
129
- try {
130
- body = text ? JSON.parse(text) : void 0;
131
- } catch {
132
- }
133
- const detail = errorDetail(body) ?? plainText(body);
134
- const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
135
- const options = { status: response.status, detail, requestId, body };
136
- if (response.status === 429) {
137
- return new RateLimited(message, { ...options, retryAfterMs: parseRetryAfter(response.headers.get("retry-after")) });
138
- }
139
- if (response.status === 402 || isOutOfCredits(detail)) return new InsufficientCredits(message, options);
140
- return new SegmindError(message, options);
141
- }
142
- function requestFailure(requestId, statusBody, detail) {
143
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
144
- if (isOutOfCredits(detail)) {
145
- return new InsufficientCredits(`request ${requestId} failed: ${detail}`, { detail, requestId, body: statusBody });
146
- }
147
- return new InferenceFailed(requestId, statusBody, detail);
148
- }
149
- function parseRetryAfter(value, now = Date.now()) {
150
- if (!value) return void 0;
151
- const seconds = Number(value);
152
- if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
153
- const date = Date.parse(value);
154
- return Number.isNaN(date) ? void 0 : Math.max(date - now, 0);
155
- }
156
- function isOutOfCredits(detail) {
157
- return detail?.startsWith("Insufficient credits.") ?? false;
158
- }
159
- function plainText(body) {
160
- if (typeof body !== "string" || !body || body.trimStart().startsWith("<")) return void 0;
161
- return body.slice(0, 500);
162
- }
163
- function errorDetail(body) {
164
- if (!body || typeof body !== "object") return void 0;
165
- const record2 = body;
166
- for (const key of ["error", "message", "detail"]) {
167
- const value = record2[key];
168
- if (typeof value === "string" && value) return value;
169
- if (value && typeof value === "object" && typeof value.message === "string") {
170
- return value.message;
171
- }
172
- }
173
- return void 0;
174
- }
4
+
5
+
6
+
7
+
8
+
9
+
10
+ var _chunk74UKKBOOcjs = require('./chunk-74UKKBOO.cjs');
175
11
 
176
12
  // src/chat.ts
177
13
  var ChatResponse = class {
178
14
  constructor(raw) {
179
15
  this.raw = raw;
180
16
  }
181
- raw;
17
+
182
18
  /** The assistant's text. Throws when the body holds none (inspect `raw`). */
183
19
  get text() {
184
20
  const text = extractText(this.raw);
185
21
  if (text === void 0) {
186
- throw new SegmindError(
22
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
187
23
  `could not find assistant text in the response (top-level keys: ${Object.keys(this.raw).sort().join(", ")}); inspect ChatResponse.raw`,
188
24
  { body: this.raw }
189
25
  );
@@ -196,7 +32,7 @@ var ChatResponse = class {
196
32
  try {
197
33
  return JSON.parse(text);
198
34
  } catch (err) {
199
- throw new SegmindError(`ChatResponse.text is not valid JSON: ${err.message}`, {
35
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`ChatResponse.text is not valid JSON: ${err.message}`, {
200
36
  body: text,
201
37
  cause: err
202
38
  });
@@ -204,28 +40,28 @@ var ChatResponse = class {
204
40
  }
205
41
  /** The provider's token usage (`usage` or Gemini's `usageMetadata`). */
206
42
  get usage() {
207
- return (record(this.raw.usage) ?? record(this.raw.usageMetadata)) || void 0;
43
+ return (_nullishCoalesce(record(this.raw.usage), () => ( record(this.raw.usageMetadata)))) || void 0;
208
44
  }
209
45
  /** Why generation stopped (`finish_reason`, `stop_reason` or `finishReason`). */
210
46
  get finishReason() {
211
- if (Array.isArray(this.raw.choices)) return str(record(this.raw.choices[0])?.finish_reason);
47
+ if (Array.isArray(this.raw.choices)) return str(_optionalChain([record, 'call', _ => _(this.raw.choices[0]), 'optionalAccess', _2 => _2.finish_reason]));
212
48
  if ("stop_reason" in this.raw) return str(this.raw.stop_reason);
213
- if (Array.isArray(this.raw.candidates)) return str(record(this.raw.candidates[0])?.finishReason);
49
+ if (Array.isArray(this.raw.candidates)) return str(_optionalChain([record, 'call', _3 => _3(this.raw.candidates[0]), 'optionalAccess', _4 => _4.finishReason]));
214
50
  return void 0;
215
51
  }
216
52
  /** Tool calls in the OpenAI shape, when the model made any. */
217
53
  get toolCalls() {
218
54
  if (!Array.isArray(this.raw.choices)) return [];
219
- const calls = record(record(this.raw.choices[0])?.message)?.tool_calls;
55
+ const calls = _optionalChain([record, 'call', _5 => _5(_optionalChain([record, 'call', _6 => _6(this.raw.choices[0]), 'optionalAccess', _7 => _7.message])), 'optionalAccess', _8 => _8.tool_calls]);
220
56
  return Array.isArray(calls) ? calls : [];
221
57
  }
222
58
  };
223
59
  function chatBody(params) {
224
60
  if (params.messages === void 0 && params.prompt === void 0) {
225
- throw new SegmindError('chat: pass messages: [...] or prompt: "..."');
61
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)('chat: pass messages: [...] or prompt: "..."');
226
62
  }
227
63
  if (params.stream === true) {
228
- throw new SegmindError("chat: streaming is not supported yet; omit stream or set it to false");
64
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("chat: streaming is not supported yet; omit stream or set it to false");
229
65
  }
230
66
  return params;
231
67
  }
@@ -235,7 +71,7 @@ function chatFromRunResult(body) {
235
71
  try {
236
72
  const parsed = JSON.parse(output);
237
73
  if (record(parsed)) return new ChatResponse(parsed);
238
- } catch {
74
+ } catch (e2) {
239
75
  }
240
76
  return new ChatResponse({ choices: [{ message: { content: output } }] });
241
77
  }
@@ -244,21 +80,21 @@ function chatFromRunResult(body) {
244
80
  }
245
81
  function extractText(raw) {
246
82
  if ("choices" in raw) {
247
- const content = record(record(Array.isArray(raw.choices) ? raw.choices[0] : void 0)?.message)?.content;
83
+ const content = _optionalChain([record, 'call', _9 => _9(_optionalChain([record, 'call', _10 => _10(Array.isArray(raw.choices) ? raw.choices[0] : void 0), 'optionalAccess', _11 => _11.message])), 'optionalAccess', _12 => _12.content]);
248
84
  if (typeof content === "string") return content;
249
85
  if (Array.isArray(content)) {
250
- return content.map(record).filter((part) => part && (part.type === void 0 || part.type === "text")).map((part) => str(part.text) ?? "").join("");
86
+ return content.map(record).filter((part) => part && (part.type === void 0 || part.type === "text")).map((part) => _nullishCoalesce(str(part.text), () => ( ""))).join("");
251
87
  }
252
88
  return void 0;
253
89
  }
254
90
  if (Array.isArray(raw.content)) {
255
- return raw.content.map(record).filter((part) => part?.type === "text").map((part) => str(part.text) ?? "").join("");
91
+ return raw.content.map(record).filter((part) => _optionalChain([part, 'optionalAccess', _13 => _13.type]) === "text").map((part) => _nullishCoalesce(str(part.text), () => ( ""))).join("");
256
92
  }
257
93
  if ("candidates" in raw) {
258
94
  const candidate = record(Array.isArray(raw.candidates) ? raw.candidates[0] : void 0);
259
- const parts = record(candidate?.content)?.parts;
95
+ const parts = _optionalChain([record, 'call', _14 => _14(_optionalChain([candidate, 'optionalAccess', _15 => _15.content])), 'optionalAccess', _16 => _16.parts]);
260
96
  if (!Array.isArray(parts)) return candidate ? "" : void 0;
261
- return parts.map((part) => str(record(part)?.text) ?? "").join("");
97
+ return parts.map((part) => _nullishCoalesce(str(_optionalChain([record, 'call', _17 => _17(part), 'optionalAccess', _18 => _18.text])), () => ( ""))).join("");
262
98
  }
263
99
  return void 0;
264
100
  }
@@ -272,9 +108,9 @@ function str(value) {
272
108
  // src/core/env.ts
273
109
  var g = globalThis;
274
110
  function detectRuntime() {
275
- if (g.navigator?.product === "ReactNative") return "react-native";
111
+ if (_optionalChain([g, 'access', _19 => _19.navigator, 'optionalAccess', _20 => _20.product]) === "ReactNative") return "react-native";
276
112
  if (typeof g.window !== "undefined" && typeof g.document !== "undefined") return "browser";
277
- if (g.process?.versions?.node) return "node";
113
+ if (_optionalChain([g, 'access', _21 => _21.process, 'optionalAccess', _22 => _22.versions, 'optionalAccess', _23 => _23.node])) return "node";
278
114
  return "other";
279
115
  }
280
116
  function initiatorHeaders(options) {
@@ -285,17 +121,17 @@ function initiatorHeaders(options) {
285
121
  }
286
122
  function readEnv(name) {
287
123
  try {
288
- const value = g.process?.env?.[name];
289
- return value?.trim() ? value.trim() : void 0;
290
- } catch {
124
+ const value = _optionalChain([g, 'access', _24 => _24.process, 'optionalAccess', _25 => _25.env, 'optionalAccess', _26 => _26[name]]);
125
+ return _optionalChain([value, 'optionalAccess', _27 => _27.trim, 'call', _28 => _28()]) ? value.trim() : void 0;
126
+ } catch (e3) {
291
127
  return void 0;
292
128
  }
293
129
  }
294
130
  function nodeVersion() {
295
- return g.process?.versions?.node ? g.process.version : void 0;
131
+ return _optionalChain([g, 'access', _29 => _29.process, 'optionalAccess', _30 => _30.versions, 'optionalAccess', _31 => _31.node]) ? g.process.version : void 0;
296
132
  }
297
133
  function randomRequestId() {
298
- const uuid = g.crypto?.randomUUID?.();
134
+ const uuid = _optionalChain([g, 'access', _32 => _32.crypto, 'optionalAccess', _33 => _33.randomUUID, 'optionalCall', _34 => _34()]);
299
135
  if (uuid) return uuid;
300
136
  let id = "";
301
137
  for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);
@@ -315,36 +151,36 @@ function toBase64(bytes) {
315
151
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
316
152
  var MAX_RETRY_DELAY_MS = 6e4;
317
153
  function retryDelay(attempt, retryAfter, now = Date.now()) {
318
- const asked = parseRetryAfter(retryAfter, now);
154
+ const asked = _chunk74UKKBOOcjs.parseRetryAfter.call(void 0, retryAfter, now);
319
155
  if (asked !== void 0) return Math.min(asked, MAX_RETRY_DELAY_MS);
320
156
  const base = Math.min(500 * 2 ** attempt, 8e3);
321
157
  return base * (0.75 + Math.random() * 0.25);
322
158
  }
323
159
  function pollDelay(interval, elapsedMs, fallback) {
324
- const delay = typeof interval === "function" ? interval(elapsedMs) : interval ?? fallback;
160
+ const delay = typeof interval === "function" ? interval(elapsedMs) : _nullishCoalesce(interval, () => ( fallback));
325
161
  return Number.isFinite(delay) && delay >= 0 ? delay : fallback;
326
162
  }
327
163
  function sleep(ms, signal) {
328
164
  return new Promise((resolve, reject) => {
329
- if (signal?.aborted) return reject(signal.reason);
165
+ if (_optionalChain([signal, 'optionalAccess', _35 => _35.aborted])) return reject(signal.reason);
330
166
  const timer = setTimeout(() => {
331
- signal?.removeEventListener("abort", onAbort);
167
+ _optionalChain([signal, 'optionalAccess', _36 => _36.removeEventListener, 'call', _37 => _37("abort", onAbort)]);
332
168
  resolve();
333
169
  }, ms);
334
170
  const onAbort = () => {
335
171
  clearTimeout(timer);
336
172
  reject(signal.reason);
337
173
  };
338
- signal?.addEventListener("abort", onAbort, { once: true });
174
+ _optionalChain([signal, 'optionalAccess', _38 => _38.addEventListener, 'call', _39 => _39("abort", onAbort, { once: true })]);
339
175
  });
340
176
  }
341
177
  var HttpClient = class {
342
178
  constructor(config) {
343
179
  this.config = config;
344
180
  }
345
- config;
181
+
346
182
  /** The hook call in flight, so that requests failing together share one refresh. */
347
- unauthorized;
183
+
348
184
  /** The response whatever its status, after retries when `retry` is set. */
349
185
  async fetchRaw(req) {
350
186
  let attempt = 0;
@@ -356,7 +192,7 @@ var HttpClient = class {
356
192
  try {
357
193
  response = await this.attempt(req, token);
358
194
  } catch (err) {
359
- if (canRetry && err instanceof APIConnectionError) {
195
+ if (canRetry && err instanceof _chunk74UKKBOOcjs.APIConnectionError) {
360
196
  await sleep(retryDelay(attempt, null), req.signal);
361
197
  attempt++;
362
198
  continue;
@@ -365,11 +201,11 @@ var HttpClient = class {
365
201
  }
366
202
  if (response.status === 401 && !reauthenticated && await this.reauthenticate(req, token)) {
367
203
  reauthenticated = true;
368
- await response.body?.cancel().catch(() => void 0);
204
+ await _optionalChain([response, 'access', _40 => _40.body, 'optionalAccess', _41 => _41.cancel, 'call', _42 => _42(), 'access', _43 => _43.catch, 'call', _44 => _44(() => void 0)]);
369
205
  continue;
370
206
  }
371
207
  if (canRetry && RETRYABLE_STATUS.has(response.status)) {
372
- await response.body?.cancel().catch(() => void 0);
208
+ await _optionalChain([response, 'access', _45 => _45.body, 'optionalAccess', _46 => _46.cancel, 'call', _47 => _47(), 'access', _48 => _48.catch, 'call', _49 => _49(() => void 0)]);
373
209
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), req.signal);
374
210
  attempt++;
375
211
  continue;
@@ -380,7 +216,7 @@ var HttpClient = class {
380
216
  /** The response, or a `SegmindError` for any status outside 2xx. */
381
217
  async request(req) {
382
218
  const response = await this.fetchRaw(req);
383
- if (!response.ok) throw await SegmindError.fromResponse(response);
219
+ if (!response.ok) throw await _chunk74UKKBOOcjs.SegmindError.fromResponse(response);
384
220
  return response;
385
221
  }
386
222
  /** The parsed JSON body of a 2xx response. */
@@ -390,9 +226,9 @@ var HttpClient = class {
390
226
  async sessionToken(req) {
391
227
  if (!this.config.tokenProvider || req.bare) return void 0;
392
228
  try {
393
- return await this.config.tokenProvider() ?? void 0;
229
+ return await _asyncNullishCoalesce(await this.config.tokenProvider(), async () => ( void 0));
394
230
  } catch (err) {
395
- throw new SegmindError(`tokenProvider failed: ${describe(err)}`, { cause: err });
231
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`tokenProvider failed: ${describe(err)}`, { cause: err });
396
232
  }
397
233
  }
398
234
  /** Tells the app its token was refused. True when it now has a different one to try. */
@@ -407,14 +243,14 @@ var HttpClient = class {
407
243
  }
408
244
  const next = await this.config.tokenProvider();
409
245
  return Boolean(next) && next !== refused;
410
- } catch {
246
+ } catch (e4) {
411
247
  return false;
412
248
  }
413
249
  }
414
250
  async attempt(req, token) {
415
251
  const { signal } = req;
416
- if (signal?.aborted) throw signal.reason;
417
- const timeout = req.timeout ?? this.config.timeout;
252
+ if (_optionalChain([signal, 'optionalAccess', _50 => _50.aborted])) throw signal.reason;
253
+ const timeout = _nullishCoalesce(req.timeout, () => ( this.config.timeout));
418
254
  const controller = new AbortController();
419
255
  let timedOut = false;
420
256
  const timer = setTimeout(() => {
@@ -422,12 +258,12 @@ var HttpClient = class {
422
258
  controller.abort();
423
259
  }, timeout);
424
260
  const onAbort = () => controller.abort(signal.reason);
425
- signal?.addEventListener("abort", onAbort, { once: true });
261
+ _optionalChain([signal, 'optionalAccess', _51 => _51.addEventListener, 'call', _52 => _52("abort", onAbort, { once: true })]);
426
262
  const headers = req.bare ? { ...req.headers } : { ...this.config.headers, ...req.headers };
427
263
  if (this.config.apiKey && !req.bare) headers["x-api-key"] = this.config.apiKey;
428
264
  if (token) headers.Authorization = `Bearer ${token}`;
429
265
  if (req.body !== void 0) headers["content-type"] = "application/json";
430
- const body = req.rawBody ?? (req.body === void 0 ? void 0 : JSON.stringify(req.body));
266
+ const body = _nullishCoalesce(req.rawBody, () => ( (req.body === void 0 ? void 0 : JSON.stringify(req.body))));
431
267
  try {
432
268
  return await this.config.fetch(withQuery(req.url, req.query), {
433
269
  method: req.method,
@@ -436,12 +272,12 @@ var HttpClient = class {
436
272
  signal: controller.signal
437
273
  });
438
274
  } catch (err) {
439
- if (signal?.aborted) throw signal.reason ?? err;
275
+ if (_optionalChain([signal, 'optionalAccess', _53 => _53.aborted])) throw _nullishCoalesce(signal.reason, () => ( err));
440
276
  const reason = timedOut ? `request timed out after ${timeout} ms` : `connection error: ${describe(err)}`;
441
- throw new APIConnectionError(`${req.method} ${req.url}: ${reason}`, { cause: err });
277
+ throw new (0, _chunk74UKKBOOcjs.APIConnectionError)(`${req.method} ${req.url}: ${reason}`, { cause: err });
442
278
  } finally {
443
279
  clearTimeout(timer);
444
- signal?.removeEventListener("abort", onAbort);
280
+ _optionalChain([signal, 'optionalAccess', _54 => _54.removeEventListener, 'call', _55 => _55("abort", onAbort)]);
445
281
  }
446
282
  }
447
283
  };
@@ -450,7 +286,7 @@ async function readJson(response) {
450
286
  try {
451
287
  return JSON.parse(text);
452
288
  } catch (err) {
453
- throw new SegmindError(`${response.status} response was not JSON`, {
289
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${response.status} response was not JSON`, {
454
290
  status: response.status,
455
291
  body: text.slice(0, 500),
456
292
  cause: err
@@ -518,18 +354,18 @@ async function openFileInput(input, options) {
518
354
  let mimeType = options.mimeType;
519
355
  if (typeof input === "string") {
520
356
  if (detectRuntime() !== "node") {
521
- throw new SegmindError(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
357
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
522
358
  }
523
- const { openAsBlob } = await import(
359
+ const { openAsBlob } = await Promise.resolve().then(() => _interopRequireWildcard(require(
524
360
  /* webpackIgnore: true */
525
361
  /* turbopackIgnore: true */
526
362
  /* @vite-ignore */
527
363
  "node:fs"
528
- );
364
+ )));
529
365
  try {
530
366
  body = await openAsBlob(input);
531
367
  } catch (err) {
532
- throw new SegmindError(`${options.caller}: cannot read ${JSON.stringify(input)}: ${err.message}`, {
368
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: cannot read ${JSON.stringify(input)}: ${err.message}`, {
533
369
  cause: err
534
370
  });
535
371
  }
@@ -545,7 +381,7 @@ async function openFileInput(input, options) {
545
381
  if (!name || !name.includes(".")) {
546
382
  const extension = mimeType ? EXTENSION_BY_MIME[mimeType] : void 0;
547
383
  if (!extension) {
548
- throw new SegmindError(`${options.caller}: cannot tell the file type; pass { filename: 'name.ext' } or { mimeType }`);
384
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: cannot tell the file type; pass { filename: 'name.ext' } or { mimeType }`);
549
385
  }
550
386
  name = `${name || "upload"}.${extension}`;
551
387
  }
@@ -579,7 +415,7 @@ var Files = class {
579
415
  constructor(client2) {
580
416
  this.client = client2;
581
417
  }
582
- client;
418
+
583
419
  async upload(input, options = {}) {
584
420
  if (Array.isArray(input)) {
585
421
  const uploaded = [];
@@ -603,7 +439,7 @@ var Files = class {
603
439
  retry: true
604
440
  });
605
441
  if (!ticket.upload_url || !ticket.url) {
606
- throw new SegmindError("files.upload: the presign response had no upload_url or url", { body: ticket });
442
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("files.upload: the presign response had no upload_url or url", { body: ticket });
607
443
  }
608
444
  const headers = { ...ticket.required_headers };
609
445
  delete headers["Content-Length"];
@@ -615,7 +451,7 @@ var Files = class {
615
451
  async persist(file, signal) {
616
452
  const contentType = file.mimeType;
617
453
  if (!contentType) {
618
- throw new SegmindError(`files.upload: cannot tell the type of ${file.filename}; pass { mimeType } to persist it`);
454
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`files.upload: cannot tell the type of ${file.filename}; pass { mimeType } to persist it`);
619
455
  }
620
456
  const { http, assetsURL } = this.client;
621
457
  const ticket = await http.json({
@@ -626,7 +462,7 @@ var Files = class {
626
462
  retry: true
627
463
  });
628
464
  if (!ticket.presignedUrl || !ticket.s3Key || !ticket.publicUrl) {
629
- throw new SegmindError("files.upload: the asset presign response had no presignedUrl, s3Key or publicUrl", {
465
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("files.upload: the asset presign response had no presignedUrl, s3Key or publicUrl", {
630
466
  body: ticket
631
467
  });
632
468
  }
@@ -638,7 +474,7 @@ var Files = class {
638
474
  signal,
639
475
  retry: true
640
476
  });
641
- return confirmed.asset?.url ?? ticket.publicUrl;
477
+ return _nullishCoalesce(_optionalChain([confirmed, 'access', _56 => _56.asset, 'optionalAccess', _57 => _57.url]), () => ( ticket.publicUrl));
642
478
  }
643
479
  /**
644
480
  * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
@@ -654,11 +490,11 @@ var Generations = class {
654
490
  constructor(client2) {
655
491
  this.client = client2;
656
492
  }
657
- client;
493
+
658
494
  /** Generated outputs, newest first. */
659
495
  async list(options = {}) {
660
496
  return this.read("/inference-request/generations", options.signal, {
661
- page: options.page ?? 1,
497
+ page: _nullishCoalesce(options.page, () => ( 1)),
662
498
  per_page: options.perPage,
663
499
  model_name: options.modelName,
664
500
  start_date: options.startDate,
@@ -678,13 +514,13 @@ var Generations = class {
678
514
  */
679
515
  async history(options = {}) {
680
516
  return this.read("/inference-request/request-history", options.signal, {
681
- page: options.page ?? 1,
682
- per_page: options.perPage ?? 20,
517
+ page: _nullishCoalesce(options.page, () => ( 1)),
518
+ per_page: _nullishCoalesce(options.perPage, () => ( 20)),
683
519
  from_date: options.fromDate,
684
520
  to_date: options.toDate,
685
521
  model_name: options.modelName,
686
522
  status: options.status,
687
- initiator: [options.initiator ?? []].flat().join(",") || void 0,
523
+ initiator: [_nullishCoalesce(options.initiator, () => ( []))].flat().join(",") || void 0,
688
524
  key_suffix: options.keySuffix,
689
525
  user_id: options.userId,
690
526
  user_email: options.userEmail,
@@ -714,12 +550,12 @@ var Job = class {
714
550
  this.statusUrl = submitResponse.status_url;
715
551
  this.responseUrl = submitResponse.response_url;
716
552
  }
717
- http;
718
- submitResponse;
719
- transform;
720
- requestId;
721
- statusUrl;
722
- responseUrl;
553
+
554
+
555
+
556
+
557
+
558
+
723
559
  /** The current state, without waiting. */
724
560
  async status(options = {}) {
725
561
  return await this.read(this.statusUrl, options.signal);
@@ -730,9 +566,9 @@ var Job = class {
730
566
  */
731
567
  async result(options = {}) {
732
568
  const body = await this.read(this.responseUrl, options.signal);
733
- if (body.status === "FAILED") throw requestFailure(this.requestId, body);
569
+ if (body.status === "FAILED") throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, body);
734
570
  if (body.status !== void 0 && body.status !== "COMPLETED") {
735
- throw new SegmindError(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
571
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
736
572
  requestId: this.requestId,
737
573
  body
738
574
  });
@@ -741,15 +577,15 @@ var Job = class {
741
577
  }
742
578
  /** Polls until the request finishes, then returns its result. */
743
579
  async wait(options = {}) {
744
- const timeout = options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS;
580
+ const timeout = _nullishCoalesce(options.timeout, () => ( DEFAULT_WAIT_TIMEOUT_MS));
745
581
  const started = Date.now();
746
582
  for (; ; ) {
747
583
  const status = await this.status({ signal: options.signal });
748
- options.onStatus?.(status);
584
+ _optionalChain([options, 'access', _58 => _58.onStatus, 'optionalCall', _59 => _59(status)]);
749
585
  if (status.status === "COMPLETED") return this.result({ signal: options.signal });
750
- if (status.status === "FAILED") throw requestFailure(this.requestId, status);
586
+ if (status.status === "FAILED") throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, status);
751
587
  const elapsed = Date.now() - started;
752
- if (elapsed >= timeout) throw new InferenceTimeout(this.requestId, elapsed);
588
+ if (elapsed >= timeout) throw new (0, _chunk74UKKBOOcjs.InferenceTimeout)(this.requestId, elapsed);
753
589
  const delay = pollDelay(options.interval, elapsed, DEFAULT_WAIT_INTERVAL_MS);
754
590
  await sleep(Math.min(delay, timeout - elapsed), options.signal);
755
591
  }
@@ -762,7 +598,7 @@ var Job = class {
762
598
  async read(url, signal) {
763
599
  const response = await this.http.fetchRaw({ method: "GET", url, signal, retry: true });
764
600
  if (response.ok) return readJson(response);
765
- const error = await SegmindError.fromResponse(response, this.requestId);
601
+ const error = await _chunk74UKKBOOcjs.SegmindError.fromResponse(response, this.requestId);
766
602
  const body = error.body;
767
603
  if (body && typeof body === "object" && TERMINAL.has(String(body.status))) {
768
604
  return body;
@@ -780,7 +616,7 @@ var PixelFlows = class {
780
616
  constructor(client2) {
781
617
  this.client = client2;
782
618
  }
783
- client;
619
+
784
620
  /** Runs a workflow and waits for its outputs. */
785
621
  async run(slug, inputs = {}, options = {}) {
786
622
  const job2 = await this.submit(slug, inputs, options);
@@ -789,7 +625,7 @@ var PixelFlows = class {
789
625
  /** Starts a workflow and returns a job to wait on. Never retried: a run bills. */
790
626
  async submit(slug, inputs = {}, options = {}) {
791
627
  const clean = slug.trim().replace(/^\/+/, "");
792
- if (!clean) throw new SegmindError("pixelflows: a workflow slug is required");
628
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("pixelflows: a workflow slug is required");
793
629
  const route = options.engine === "v1" ? "/workflows/" : "/workflows/v2/";
794
630
  const body = await this.client.http.json({
795
631
  method: "POST",
@@ -800,7 +636,7 @@ var PixelFlows = class {
800
636
  });
801
637
  const requestId = body.request_id;
802
638
  if (typeof requestId !== "string" || !requestId) {
803
- throw new SegmindError("pixelflows: the submit response had no request_id", { body });
639
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("pixelflows: the submit response had no request_id", { body });
804
640
  }
805
641
  return new PixelflowJob(this, requestId);
806
642
  }
@@ -824,8 +660,8 @@ var PixelflowJob = class {
824
660
  this.pixelflows = pixelflows2;
825
661
  this.requestId = requestId;
826
662
  }
827
- pixelflows;
828
- requestId;
663
+
664
+
829
665
  status(options = {}) {
830
666
  return this.pixelflows.getStatus(this.requestId, options);
831
667
  }
@@ -835,16 +671,16 @@ var PixelflowJob = class {
835
671
  * timeout, so `wait()` can be called again.
836
672
  */
837
673
  async wait(options = {}) {
838
- const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
674
+ const timeout = _nullishCoalesce(options.timeout, () => ( DEFAULT_TIMEOUT_MS));
839
675
  const started = Date.now();
840
676
  for (; ; ) {
841
677
  const state = await this.status({ signal: options.signal });
842
- options.onStatus?.(state);
678
+ _optionalChain([options, 'access', _60 => _60.onStatus, 'optionalCall', _61 => _61(state)]);
843
679
  if (DONE.has(state.status)) return state;
844
- if (FAILED.has(state.status)) throw requestFailure(this.requestId, state.raw, failureDetail(state.raw));
680
+ if (FAILED.has(state.status)) throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, state.raw, failureDetail(state.raw));
845
681
  const elapsed = Date.now() - started;
846
682
  const delay = pollDelay(options.interval, elapsed, DEFAULT_INTERVAL_MS);
847
- if (elapsed + delay > timeout) throw new InferenceTimeout(this.requestId, elapsed);
683
+ if (elapsed + delay > timeout) throw new (0, _chunk74UKKBOOcjs.InferenceTimeout)(this.requestId, elapsed);
848
684
  await sleep(delay, options.signal);
849
685
  }
850
686
  }
@@ -854,10 +690,10 @@ function toStatus(body) {
854
690
  if (typeof raw.output === "string") {
855
691
  try {
856
692
  raw.output = JSON.parse(raw.output);
857
- } catch {
693
+ } catch (e5) {
858
694
  }
859
695
  }
860
- const status = String(raw.status ?? "UNKNOWN").toUpperCase();
696
+ const status = String(_nullishCoalesce(raw.status, () => ( "UNKNOWN"))).toUpperCase();
861
697
  return { status, outputs: DONE.has(status) ? flattenOutputs(raw.output) : {}, raw };
862
698
  }
863
699
  function flattenOutputs(output) {
@@ -879,25 +715,57 @@ function unwrap(value) {
879
715
  return value;
880
716
  }
881
717
  function failureDetail(body) {
882
- const error = body.error_message ?? body.error;
718
+ const error = _nullishCoalesce(body.error_message, () => ( body.error));
883
719
  if (typeof error === "string") return error;
884
720
  if (error && typeof error === "object") {
885
721
  const e = error;
886
- const text = e.details ?? e.error_message ?? e.error;
722
+ const text = _nullishCoalesce(_nullishCoalesce(e.details, () => ( e.error_message)), () => ( e.error));
887
723
  if (typeof text === "string") return text;
888
724
  }
889
725
  return void 0;
890
726
  }
891
727
 
728
+ // src/realtime-tokens.ts
729
+ var Realtime = class {
730
+ constructor(client2) {
731
+ this.client = client2;
732
+ }
733
+
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
+
892
760
  // src/version.ts
893
- var VERSION = "0.5.1";
761
+ var VERSION = "0.6.1";
894
762
 
895
763
  // src/webhooks.ts
896
764
  var Webhooks = class {
897
765
  constructor(client2) {
898
766
  this.client = client2;
899
767
  }
900
- client;
768
+
901
769
  /** Every registration; `[]` when you have none. */
902
770
  async get(options = {}) {
903
771
  return this.call("GET", "/get", { signal: options.signal, retry: true });
@@ -956,7 +824,7 @@ var Webhooks = class {
956
824
  };
957
825
  function requireTypes(eventTypes) {
958
826
  if (!Array.isArray(eventTypes) || eventTypes.length === 0) {
959
- throw new SegmindError('webhooks: pass at least one event type, e.g. ["PIXELFLOW"]');
827
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)('webhooks: pass at least one event type, e.g. ["PIXELFLOW"]');
960
828
  }
961
829
  return eventTypes;
962
830
  }
@@ -967,42 +835,44 @@ var DEFAULT_SPOT_URL = "https://api.spotprod.segmind.com";
967
835
  var DEFAULT_CONSOLE_URL = "https://cloud.segmind.com/api";
968
836
  var DEFAULT_ASSETS_URL = "https://platform-api.segmind.com";
969
837
  var Segmind = class {
970
- baseURL;
971
- spotURL;
972
- consoleURL;
973
- assetsURL;
974
- models;
975
- accounts;
838
+
839
+
840
+
841
+
842
+
843
+
976
844
  /** Upload files to pass as model inputs. */
977
- files;
845
+
978
846
  /** Your generations and request history. */
979
- generations;
847
+
980
848
  /** Your webhook registrations. */
981
- webhooks;
849
+
982
850
  /** Run published PixelFlow workflows. */
983
- pixelflows;
851
+
852
+ /** Session tokens for realtime models. The sessions themselves open from `segmind/realtime`. */
853
+
984
854
  /** @internal */
985
- http;
855
+
986
856
  constructor(options = {}) {
987
857
  if (options.apiKey && options.tokenProvider) {
988
- throw new SegmindError("Pass either apiKey or tokenProvider, not both.");
858
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("Pass either apiKey or tokenProvider, not both.");
989
859
  }
990
- const apiKey = options.apiKey ?? (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"));
860
+ const apiKey = _nullishCoalesce(options.apiKey, () => ( (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"))));
991
861
  const runtime = detectRuntime();
992
862
  if (apiKey && (runtime === "browser" || runtime === "react-native") && !options.dangerouslyAllowBrowser) {
993
- throw new SegmindError(
863
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
994
864
  "An API key in a browser or mobile app exposes it to every user. Call Segmind from your backend instead, or pass dangerouslyAllowBrowser: true if you accept that risk."
995
865
  );
996
866
  }
997
867
  if (!apiKey && !options.tokenProvider) {
998
- throw new SegmindError("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
868
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
999
869
  }
1000
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
1001
- if (!fetchImpl) throw new SegmindError("No fetch implementation available: pass { fetch }.");
1002
- this.baseURL = trimBase(options.baseURL ?? readEnv("SEGMIND_BASE_URL") ?? DEFAULT_BASE_URL);
1003
- this.spotURL = trimSlash(options.spotURL ?? DEFAULT_SPOT_URL);
1004
- this.consoleURL = trimSlash(options.consoleURL ?? DEFAULT_CONSOLE_URL);
1005
- this.assetsURL = trimSlash(options.assetsURL ?? DEFAULT_ASSETS_URL);
870
+ const fetchImpl = _nullishCoalesce(options.fetch, () => ( _optionalChain([globalThis, 'access', _62 => _62.fetch, 'optionalAccess', _63 => _63.bind, 'call', _64 => _64(globalThis)])));
871
+ if (!fetchImpl) throw new (0, _chunk74UKKBOOcjs.SegmindError)("No fetch implementation available: pass { fetch }.");
872
+ this.baseURL = trimBase(_nullishCoalesce(_nullishCoalesce(options.baseURL, () => ( readEnv("SEGMIND_BASE_URL"))), () => ( DEFAULT_BASE_URL)));
873
+ this.spotURL = trimSlash(_nullishCoalesce(options.spotURL, () => ( DEFAULT_SPOT_URL)));
874
+ this.consoleURL = trimSlash(_nullishCoalesce(options.consoleURL, () => ( DEFAULT_CONSOLE_URL)));
875
+ this.assetsURL = trimSlash(_nullishCoalesce(options.assetsURL, () => ( DEFAULT_ASSETS_URL)));
1006
876
  const headers = {
1007
877
  "X-Initiator": "SDK-JS",
1008
878
  ...initiatorHeaders(options),
@@ -1015,8 +885,8 @@ var Segmind = class {
1015
885
  tokenProvider: options.tokenProvider,
1016
886
  onUnauthorized: options.onUnauthorized,
1017
887
  fetch: fetchImpl,
1018
- timeout: options.timeout ?? 6e5,
1019
- maxRetries: options.maxRetries ?? 2,
888
+ timeout: _nullishCoalesce(options.timeout, () => ( 6e5)),
889
+ maxRetries: _nullishCoalesce(options.maxRetries, () => ( 2)),
1020
890
  headers
1021
891
  });
1022
892
  this.models = new Models(this);
@@ -1025,6 +895,7 @@ var Segmind = class {
1025
895
  this.generations = new Generations(this);
1026
896
  this.webhooks = new Webhooks(this);
1027
897
  this.pixelflows = new PixelFlows(this);
898
+ this.realtime = new Realtime(this);
1028
899
  }
1029
900
  /**
1030
901
  * Runs a model and returns its result: submits to the v2 queue, then polls
@@ -1065,7 +936,7 @@ var Segmind = class {
1065
936
  */
1066
937
  job(requestId) {
1067
938
  const clean = requestId.trim();
1068
- if (!clean) throw new SegmindError("A request id is required.");
939
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("A request id is required.");
1069
940
  const url = `${this.baseURL}/v2/requests/${encodeURIComponent(clean)}`;
1070
941
  return new Job(this.http, {
1071
942
  request_id: clean,
@@ -1091,7 +962,7 @@ var Segmind = class {
1091
962
  async submitJob(slug, params, options, transform) {
1092
963
  const url = `${this.baseURL}/v2/${path(slug)}`;
1093
964
  const maxRetries = this.http.config.maxRetries;
1094
- let requestId = options.requestId ?? randomRequestId();
965
+ let requestId = _nullishCoalesce(options.requestId, () => ( randomRequestId()));
1095
966
  for (let attempt = 0; ; attempt++) {
1096
967
  const canRetry = attempt < maxRetries;
1097
968
  let response;
@@ -1104,7 +975,7 @@ var Segmind = class {
1104
975
  signal: options.signal
1105
976
  });
1106
977
  } catch (err) {
1107
- if (canRetry && err instanceof APIConnectionError) {
978
+ if (canRetry && err instanceof _chunk74UKKBOOcjs.APIConnectionError) {
1108
979
  await sleep(retryDelay(attempt, null), options.signal);
1109
980
  continue;
1110
981
  }
@@ -1113,7 +984,7 @@ var Segmind = class {
1113
984
  if (response.ok || response.status === 409) {
1114
985
  const body = await readJson(response);
1115
986
  if (response.status === 409 && !body.status_url) {
1116
- throw new SegmindError(`409 ${String(body.error ?? "conflict")}`, {
987
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`409 ${String(_nullishCoalesce(body.error, () => ( "conflict")))}`, {
1117
988
  status: 409,
1118
989
  requestId,
1119
990
  body
@@ -1122,17 +993,17 @@ var Segmind = class {
1122
993
  return new Job(this.http, onBase(validateSubmit(body, response.status), this.baseURL), transform);
1123
994
  }
1124
995
  if (canRetry && response.status === 503) {
1125
- await response.body?.cancel().catch(() => void 0);
996
+ await _optionalChain([response, 'access', _65 => _65.body, 'optionalAccess', _66 => _66.cancel, 'call', _67 => _67(), 'access', _68 => _68.catch, 'call', _69 => _69(() => void 0)]);
1126
997
  requestId = randomRequestId();
1127
998
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
1128
999
  continue;
1129
1000
  }
1130
1001
  if (canRetry && (response.status === 429 || response.status === 502 || response.status === 504)) {
1131
- await response.body?.cancel().catch(() => void 0);
1002
+ await _optionalChain([response, 'access', _70 => _70.body, 'optionalAccess', _71 => _71.cancel, 'call', _72 => _72(), 'access', _73 => _73.catch, 'call', _74 => _74(() => void 0)]);
1132
1003
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
1133
1004
  continue;
1134
1005
  }
1135
- throw await SegmindError.fromResponse(response, requestId);
1006
+ throw await _chunk74UKKBOOcjs.SegmindError.fromResponse(response, requestId);
1136
1007
  }
1137
1008
  }
1138
1009
  };
@@ -1141,7 +1012,7 @@ var Models = class {
1141
1012
  constructor(client2) {
1142
1013
  this.client = client2;
1143
1014
  }
1144
- client;
1015
+
1145
1016
  /** One page of the catalog. Pass `offset` from the previous page while `has_more` is true. */
1146
1017
  async list(params = {}, options = {}) {
1147
1018
  return this.client.http.json({
@@ -1196,7 +1067,7 @@ var Accounts = class {
1196
1067
  constructor(client2) {
1197
1068
  this.client = client2;
1198
1069
  }
1199
- client;
1070
+
1200
1071
  /** Account details for the API key. */
1201
1072
  async current(options = {}) {
1202
1073
  return this.client.http.json({
@@ -1219,7 +1090,7 @@ var Accounts = class {
1219
1090
  };
1220
1091
  function validateSubmit(body, status) {
1221
1092
  if (!body.request_id || !body.status_url || !body.response_url) {
1222
- throw new SegmindError(
1093
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
1223
1094
  `v2 submit returned ${status} without request_id, status_url and response_url (keys: ${Object.keys(body).sort().join(", ")})`,
1224
1095
  { status, body }
1225
1096
  );
@@ -1228,7 +1099,7 @@ function validateSubmit(body, status) {
1228
1099
  }
1229
1100
  function path(slug) {
1230
1101
  const clean = slug.trim().replace(/^\/+/, "");
1231
- if (!clean) throw new SegmindError("A model slug is required.");
1102
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("A model slug is required.");
1232
1103
  return clean;
1233
1104
  }
1234
1105
  function onBase(body, baseURL) {
@@ -1300,4 +1171,43 @@ var pixelflows = {
1300
1171
  getStatus: (requestId, options) => client().pixelflows.getStatus(requestId, options),
1301
1172
  poll: (requestId, options) => client().pixelflows.poll(requestId, options)
1302
1173
  };
1174
+
1175
+
1176
+
1177
+
1178
+
1179
+
1180
+
1181
+
1182
+
1183
+
1184
+
1185
+
1186
+
1187
+
1188
+
1189
+
1190
+
1191
+
1192
+
1193
+
1194
+
1195
+
1196
+
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+ exports.APIConnectionError = _chunk74UKKBOOcjs.APIConnectionError; exports.Accounts = Accounts; exports.ChatResponse = ChatResponse; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_CONSOLE_URL = DEFAULT_CONSOLE_URL; exports.DEFAULT_SPOT_URL = DEFAULT_SPOT_URL; exports.DEFAULT_WAIT_INTERVAL_MS = DEFAULT_WAIT_INTERVAL_MS; exports.DEFAULT_WAIT_TIMEOUT_MS = DEFAULT_WAIT_TIMEOUT_MS; exports.Files = Files; exports.Generations = Generations; exports.InferenceFailed = _chunk74UKKBOOcjs.InferenceFailed; exports.InferenceTimeout = _chunk74UKKBOOcjs.InferenceTimeout; exports.InsufficientCredits = _chunk74UKKBOOcjs.InsufficientCredits; exports.Job = Job; exports.Models = Models; exports.PixelFlows = PixelFlows; exports.PixelflowJob = PixelflowJob; exports.RateLimited = _chunk74UKKBOOcjs.RateLimited; exports.Realtime = Realtime; exports.Segmind = Segmind; exports.SegmindError = _chunk74UKKBOOcjs.SegmindError; exports.VERSION = VERSION; exports.Webhooks = Webhooks; exports.accounts = accounts; exports.chat = chat; exports.chatSync = chatSync; exports.files = files; exports.generations = generations; exports.imageUrl = imageUrl; exports.job = job; exports.models = models; exports.pixelflows = pixelflows; exports.run = run; exports.runSync = runSync; exports.submit = submit; exports.submitChat = submitChat; exports.webhooks = webhooks;
1303
1213
  //# sourceMappingURL=index.cjs.map