wavespeed 0.0.14 → 0.2.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.d.ts CHANGED
@@ -1,121 +1,22 @@
1
1
  /**
2
- * Input parameters for image generation
2
+ * WaveSpeedAI JavaScript/TypeScript Client — Official JavaScript/TypeScript SDK for WaveSpeedAI inference platform.
3
+ *
4
+ * This library provides a clean, unified, and high-performance API integration layer for your applications.
5
+ * Effortlessly connect to all WaveSpeedAI models and inference services with zero infrastructure overhead.
6
+ *
7
+ * Example usage:
8
+ * import wavespeed from 'wavespeed';
9
+ *
10
+ * const output = await wavespeed.run(
11
+ * "wavespeed-ai/z-image/turbo",
12
+ * { prompt: "A beautiful sunset" }
13
+ * );
14
+ * console.log(output["outputs"][0]);
3
15
  */
4
- /**
5
- * Prediction status
6
- */
7
- export type PredictionStatus = 'created' | 'processing' | 'completed' | 'failed';
8
- /**
9
- * Prediction URLs
10
- */
11
- export interface PredictionUrls {
12
- get: string;
13
- }
14
- export interface UploadFileResp {
15
- code: number;
16
- message: string;
17
- data: {
18
- type: string;
19
- download_url: string;
20
- filename: string;
21
- size: number;
22
- };
23
- }
24
- /**
25
- * Request options for fetch
26
- */
27
- export interface RequestOptions extends RequestInit {
28
- timeout?: number;
29
- maxRetries?: number;
30
- webhook?: string;
31
- isUpload?: boolean;
32
- filename?: string;
33
- }
34
- /**
35
- * Prediction model representing an image generation job
36
- */
37
- export declare class Prediction {
38
- id: string;
39
- model: string;
40
- status: PredictionStatus;
41
- input: Record<string, any>;
42
- outputs: string[];
43
- urls: PredictionUrls;
44
- has_nsfw_contents: boolean[];
45
- created_at: string;
46
- error?: string;
47
- executionTime?: number;
48
- private client;
49
- constructor(data: any, client: WaveSpeed);
50
- /**
51
- * Wait for the prediction to complete
52
- */
53
- wait(): Promise<Prediction>;
54
- /**
55
- * Reload the prediction status
56
- */
57
- reload(): Promise<Prediction>;
58
- }
59
- /**
60
- * WaveSpeed client for generating images
61
- */
62
- export declare class WaveSpeed {
63
- private apiKey;
64
- private baseUrl;
65
- readonly pollInterval: number;
66
- readonly timeout: number;
67
- /**
68
- * Create a new WaveSpeed client
69
- *
70
- * @param apiKey Your WaveSpeed API key (or set WAVESPEED_API_KEY environment variable)
71
- * @param options Additional client options
72
- */
73
- constructor(apiKey?: string, options?: {
74
- baseUrl?: string;
75
- pollInterval?: number;
76
- timeout?: number;
77
- });
78
- /**
79
- * Fetch with timeout support
80
- *
81
- * @param path API path
82
- * @param options Fetch options
83
- */
84
- fetchWithTimeout(path: string, options?: RequestOptions): Promise<Response>;
85
- /**
86
- * Calculate backoff time with exponential backoff and jitter
87
- * @param retryCount Current retry attempt number
88
- * @param initialBackoff Initial backoff time in ms
89
- * @returns Backoff time in ms
90
- * @private
91
- */
92
- _getBackoffTime(retryCount: number, initialBackoff: number): number;
93
- /**
94
- * Generate an image and wait for the result
95
- *
96
- * @param modelId Model ID to use for prediction
97
- * @param input Input parameters for the prediction
98
- * @param options Additional fetch options
99
- */
100
- run(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>;
101
- /**
102
- * Create a prediction without waiting for it to complete
103
- *
104
- * @param modelId Model ID to use for prediction
105
- * @param input Input parameters for the prediction
106
- * @param options Additional fetch options
107
- */
108
- create(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>;
109
- /**
110
- * Upload a file (binary) to the /media/upload/binary endpoint
111
- * @param filePath Absolute path to the file to upload
112
- * @returns The API response JSON
113
- */
114
- /**
115
- * Upload a file (binary) to the /media/upload/binary endpoint (browser Blob version)
116
- * @param file Blob to upload
117
- * @returns The API response JSON
118
- */
119
- upload(file: File | Blob, options?: RequestOptions): Promise<string>;
120
- }
121
- export default WaveSpeed;
16
+ import { version } from './version';
17
+ import './config';
18
+ import { Client, run, upload } from './api';
19
+ import type { RunOptions } from './api/client';
20
+ export { version, Client, run, upload };
21
+ export type { RunOptions };
22
+ export default Client;
package/dist/index.js CHANGED
@@ -1,272 +1,30 @@
1
1
  "use strict";
2
2
  /**
3
- * Input parameters for image generation
3
+ * WaveSpeedAI JavaScript/TypeScript Client — Official JavaScript/TypeScript SDK for WaveSpeedAI inference platform.
4
+ *
5
+ * This library provides a clean, unified, and high-performance API integration layer for your applications.
6
+ * Effortlessly connect to all WaveSpeedAI models and inference services with zero infrastructure overhead.
7
+ *
8
+ * Example usage:
9
+ * import wavespeed from 'wavespeed';
10
+ *
11
+ * const output = await wavespeed.run(
12
+ * "wavespeed-ai/z-image/turbo",
13
+ * { prompt: "A beautiful sunset" }
14
+ * );
15
+ * console.log(output["outputs"][0]);
4
16
  */
5
17
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.WaveSpeed = exports.Prediction = void 0;
7
- /**
8
- * Prediction model representing an image generation job
9
- */
10
- class Prediction {
11
- constructor(data, client) {
12
- this.id = data.id;
13
- this.model = data.model;
14
- this.status = data.status;
15
- this.input = data.input;
16
- this.outputs = data.outputs || [];
17
- this.urls = data.urls;
18
- this.has_nsfw_contents = data.has_nsfw_contents || [];
19
- this.created_at = data.created_at;
20
- this.error = data.error;
21
- this.executionTime = data.executionTime;
22
- this.client = client;
23
- }
24
- /**
25
- * Wait for the prediction to complete
26
- */
27
- async wait() {
28
- if (this.status === 'completed' || this.status === 'failed') {
29
- return this;
30
- }
31
- return new Promise((resolve, reject) => {
32
- const checkStatus = async () => {
33
- try {
34
- const updated = await this.reload();
35
- if (updated.status === 'completed' || updated.status === 'failed') {
36
- resolve(updated);
37
- }
38
- else {
39
- setTimeout(checkStatus, this.client.pollInterval * 1000);
40
- }
41
- }
42
- catch (error) {
43
- reject(error);
44
- }
45
- };
46
- checkStatus();
47
- });
48
- }
49
- /**
50
- * Reload the prediction status
51
- */
52
- async reload() {
53
- const response = await this.client.fetchWithTimeout(`predictions/${this.id}/result`);
54
- if (!response.ok) {
55
- const errorText = await response.text();
56
- throw new Error(`Failed to reload prediction: ${response.status} ${errorText}`);
57
- }
58
- const data = await response.json();
59
- const updatedPrediction = new Prediction(data.data, this.client);
60
- // Update this instance with new data
61
- Object.assign(this, updatedPrediction);
62
- return this;
63
- }
64
- }
65
- exports.Prediction = Prediction;
66
- /**
67
- * WaveSpeed client for generating images
68
- */
69
- class WaveSpeed {
70
- /**
71
- * Create a new WaveSpeed client
72
- *
73
- * @param apiKey Your WaveSpeed API key (or set WAVESPEED_API_KEY environment variable)
74
- * @param options Additional client options
75
- */
76
- constructor(apiKey, options = {}) {
77
- this.baseUrl = 'https://api.wavespeed.ai/api/v2/';
78
- // Browser-friendly environment variable handling
79
- const getEnvVar = (name) => {
80
- // Try to get from process.env for Node.js environments
81
- if (typeof process !== 'undefined' && process.env && process.env[name]) {
82
- return process.env[name];
83
- }
84
- return undefined;
85
- };
86
- this.apiKey = apiKey || getEnvVar('WAVESPEED_API_KEY') || '';
87
- if (!this.apiKey) {
88
- throw new Error('API key is required. Provide it as a parameter or set the WAVESPEED_API_KEY environment variable.');
89
- }
90
- if (options.baseUrl) {
91
- this.baseUrl = options.baseUrl;
92
- }
93
- this.pollInterval = options.pollInterval || Number(getEnvVar('WAVESPEED_POLL_INTERVAL')) || 0.5;
94
- this.timeout = options.timeout || Number(getEnvVar('WAVESPEED_TIMEOUT')) || 120;
95
- }
96
- /**
97
- * Fetch with timeout support
98
- *
99
- * @param path API path
100
- * @param options Fetch options
101
- */
102
- async fetchWithTimeout(path, options = {}) {
103
- const { timeout = this.timeout * 1000, ...fetchOptions } = options;
104
- // Ensure headers exist
105
- if (options.isUpload) {
106
- fetchOptions.headers = {
107
- 'Authorization': `Bearer ${this.apiKey}`,
108
- };
109
- }
110
- else {
111
- fetchOptions.headers = {
112
- 'Authorization': `Bearer ${this.apiKey}`,
113
- 'content-type': 'application/json',
114
- ...(fetchOptions.headers || {}),
115
- };
116
- }
117
- // Default retry options
118
- const maxRetries = options.maxRetries || 3;
119
- const initialBackoff = 1000; // 1 second
120
- let retryCount = 0;
121
- // Function to determine if a response should be retried
122
- const shouldRetry = (response) => {
123
- // Retry on rate limit (429) for all requests
124
- // For GET requests, also retry on server errors (5xx)
125
- const method = (fetchOptions.method || 'GET').toUpperCase();
126
- return response.status === 429 || (method === 'GET' && response.status >= 500);
127
- };
128
- while (true) {
129
- // Use AbortController for timeout (supported in modern browsers)
130
- const controller = new AbortController();
131
- const timeoutId = setTimeout(() => controller.abort(), timeout);
132
- try {
133
- // Construct the full URL by joining baseUrl and path
134
- const url = new URL(path.startsWith('/') ? path.substring(1) : path, this.baseUrl).toString();
135
- const response = await fetch(url, {
136
- ...fetchOptions,
137
- signal: controller.signal
138
- });
139
- // If the response is successful or we've used all retries, return it
140
- if (response.ok || !shouldRetry(response) || retryCount >= maxRetries) {
141
- return response;
142
- }
143
- // Otherwise, increment retry count and wait before retrying
144
- retryCount++;
145
- const backoffTime = this._getBackoffTime(retryCount, initialBackoff);
146
- // Log retry information if console is available
147
- if (typeof console !== 'undefined') {
148
- console.warn(`Request failed with status ${response.status}. Retrying (${retryCount}/${maxRetries}) in ${Math.round(backoffTime)}ms...`);
149
- }
150
- // Wait for backoff time before retrying
151
- await new Promise(resolve => setTimeout(resolve, backoffTime));
152
- }
153
- catch (error) {
154
- // If the error is due to timeout or network issues and we have retries left
155
- if (error instanceof Error &&
156
- (error.name === 'AbortError' || error.name === 'TypeError') &&
157
- retryCount < maxRetries) {
158
- retryCount++;
159
- const backoffTime = this._getBackoffTime(retryCount, initialBackoff);
160
- // Log retry information if console is available
161
- if (typeof console !== 'undefined') {
162
- console.warn(`Request failed with error: ${error.message}. Retrying (${retryCount}/${maxRetries}) in ${Math.round(backoffTime)}ms...`);
163
- }
164
- // Wait for backoff time before retrying
165
- await new Promise(resolve => setTimeout(resolve, backoffTime));
166
- }
167
- else {
168
- // If we're out of retries or it's a non-retryable error, throw it
169
- throw error;
170
- }
171
- }
172
- finally {
173
- clearTimeout(timeoutId);
174
- }
175
- }
176
- }
177
- /**
178
- * Calculate backoff time with exponential backoff and jitter
179
- * @param retryCount Current retry attempt number
180
- * @param initialBackoff Initial backoff time in ms
181
- * @returns Backoff time in ms
182
- * @private
183
- */
184
- _getBackoffTime(retryCount, initialBackoff) {
185
- const backoff = initialBackoff * Math.pow(2, retryCount);
186
- // Add jitter (random value between 0 and backoff/2)
187
- return backoff + Math.random() * (backoff / 2);
188
- }
189
- /**
190
- * Generate an image and wait for the result
191
- *
192
- * @param modelId Model ID to use for prediction
193
- * @param input Input parameters for the prediction
194
- * @param options Additional fetch options
195
- */
196
- async run(modelId, input, options) {
197
- const prediction = await this.create(modelId, input, options);
198
- return prediction.wait();
199
- }
200
- /**
201
- * Create a prediction without waiting for it to complete
202
- *
203
- * @param modelId Model ID to use for prediction
204
- * @param input Input parameters for the prediction
205
- * @param options Additional fetch options
206
- */
207
- async create(modelId, input, options) {
208
- // Build URL with webhook if provided in options
209
- let url = `${modelId}`;
210
- if (options === null || options === void 0 ? void 0 : options.webhook) {
211
- url += `?webhook=${options.webhook}`;
212
- }
213
- const response = await this.fetchWithTimeout(url, {
214
- method: 'POST',
215
- body: JSON.stringify(input),
216
- ...options
217
- });
218
- if (!response.ok) {
219
- const errorText = await response.text();
220
- throw new Error(`Failed to create prediction: ${response.status} ${errorText}`);
221
- }
222
- const data = await response.json();
223
- if (data.code !== 200) {
224
- throw new Error(`Failed to create prediction: ${data.code} ${data}`);
225
- }
226
- return new Prediction(data.data, this);
227
- }
228
- /**
229
- * Upload a file (binary) to the /media/upload/binary endpoint
230
- * @param filePath Absolute path to the file to upload
231
- * @returns The API response JSON
232
- */
233
- /**
234
- * Upload a file (binary) to the /media/upload/binary endpoint (browser Blob version)
235
- * @param file Blob to upload
236
- * @returns The API response JSON
237
- */
238
- async upload(file, options) {
239
- const form = new FormData();
240
- if (options === null || options === void 0 ? void 0 : options.filename) {
241
- form.append('file', file, options.filename);
242
- }
243
- else {
244
- form.append('file', file);
245
- }
246
- // Only set Authorization header; browser will set Content-Type
247
- if (options == null) {
248
- options = { isUpload: true };
249
- }
250
- else {
251
- options.isUpload = true;
252
- }
253
- const response = await this.fetchWithTimeout('media/upload/binary', {
254
- method: 'POST',
255
- body: form,
256
- ...options
257
- });
258
- if (!response.ok) {
259
- const errorText = await response.text();
260
- throw new Error(`Failed to upload file: ${response.status} ${errorText}`);
261
- }
262
- const resp = await response.json();
263
- return resp.data.download_url;
264
- }
265
- }
266
- exports.WaveSpeed = WaveSpeed;
267
- // Export default and named exports for different import styles
268
- exports.default = WaveSpeed;
269
- // Add browser global for UMD-style usage
270
- if (typeof window !== 'undefined') {
271
- window.WaveSpeed = WaveSpeed;
272
- }
18
+ exports.upload = exports.run = exports.Client = exports.version = void 0;
19
+ // Import version
20
+ const version_1 = require("./version");
21
+ Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_1.version; } });
22
+ // Import config to auto-load environment variables
23
+ require("./config");
24
+ // Import API client
25
+ const api_1 = require("./api");
26
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return api_1.Client; } });
27
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return api_1.run; } });
28
+ Object.defineProperty(exports, "upload", { enumerable: true, get: function () { return api_1.upload; } });
29
+ // Default export (Client class)
30
+ exports.default = api_1.Client;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Version information for WaveSpeed SDK.
3
+ * This file provides version information from package.json.
4
+ */
5
+ export declare const version: string;
6
+ export default version;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ /**
3
+ * Version information for WaveSpeed SDK.
4
+ * This file provides version information from package.json.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.version = void 0;
8
+ // For CommonJS build, we'll read version at runtime
9
+ let _version = '0.0.0';
10
+ try {
11
+ // Try to read from package.json
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const packagePath = path.join(__dirname, '../package.json');
15
+ if (fs.existsSync(packagePath)) {
16
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
17
+ _version = packageJson.version;
18
+ }
19
+ }
20
+ catch (err) {
21
+ // Fallback to default version if package.json cannot be read
22
+ _version = '0.1.0';
23
+ }
24
+ exports.version = _version;
25
+ exports.default = exports.version;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wavespeed",
3
- "version": "0.0.14",
3
+ "version": "0.2.1",
4
4
  "description": "WaveSpeed Client SDK for Wavespeed API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,8 +18,12 @@
18
18
  "sdk",
19
19
  "wavespeed"
20
20
  ],
21
- "author": "",
21
+ "author": "WaveSpeedAI <support@wavespeed.ai>",
22
22
  "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/WaveSpeedAI/wavespeed-javascript.git"
26
+ },
23
27
  "devDependencies": {
24
28
  "@types/jest": "^29.5.5",
25
29
  "@types/node": "^20.8.2",
@@ -30,7 +34,6 @@
30
34
  "ts-jest": "^29.1.1",
31
35
  "typescript": "^5.2.2"
32
36
  },
33
- "dependencies": {},
34
37
  "files": [
35
38
  "dist"
36
39
  ]