diffio 0.4.63 → 1.0.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/README.md +208 -296
- package/dist/Client.d.ts +85 -148
- package/dist/Client.js +73 -798
- package/dist/api/resources/account.d.ts +38 -0
- package/dist/api/resources/account.js +96 -0
- package/dist/api/resources/editing.d.ts +54 -0
- package/dist/api/resources/editing.js +168 -0
- package/dist/api/resources/generations.d.ts +52 -0
- package/dist/api/resources/generations.js +145 -0
- package/dist/api/resources/index.d.ts +5 -7
- package/dist/api/resources/index.js +18 -15
- package/dist/api/resources/models.d.ts +9 -0
- package/dist/api/resources/models.js +23 -0
- package/dist/api/resources/projects.d.ts +51 -0
- package/dist/api/resources/projects.js +128 -0
- package/dist/api/types.d.ts +423 -222
- package/dist/api/types.js +2 -0
- package/dist/core/edgeUpload.d.ts +39 -39
- package/dist/core/edgeUpload.js +170 -125
- package/dist/core/files.d.ts +15 -0
- package/dist/core/files.js +121 -0
- package/dist/core/node.d.ts +7 -0
- package/dist/core/node.js +17 -0
- package/dist/core/pagination.d.ts +33 -0
- package/dist/core/pagination.js +64 -0
- package/dist/core/poll.d.ts +23 -0
- package/dist/core/poll.js +30 -0
- package/dist/core/retry.d.ts +8 -7
- package/dist/core/retry.js +39 -25
- package/dist/core/transport.d.ts +75 -0
- package/dist/core/transport.js +220 -0
- package/dist/core/url.d.ts +10 -0
- package/dist/core/url.js +38 -0
- package/dist/core/webhookSignature.d.ts +20 -0
- package/dist/core/webhookSignature.js +147 -0
- package/dist/errors/index.d.ts +60 -18
- package/dist/errors/index.js +61 -13
- package/dist/index.d.ts +8 -1
- package/dist/index.js +9 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -7
- package/dist/BaseClient.d.ts +0 -26
- package/dist/BaseClient.js +0 -17
- package/dist/api/resources/account/client/Client.d.ts +0 -15
- package/dist/api/resources/account/client/Client.js +0 -15
- package/dist/api/resources/apiKeys/client/Client.d.ts +0 -27
- package/dist/api/resources/apiKeys/client/Client.js +0 -21
- package/dist/api/resources/audioIsolation/client/Client.d.ts +0 -43
- package/dist/api/resources/audioIsolation/client/Client.js +0 -33
- package/dist/api/resources/generations/client/Client.d.ts +0 -48
- package/dist/api/resources/generations/client/Client.js +0 -36
- package/dist/api/resources/projects/client/Client.d.ts +0 -21
- package/dist/api/resources/projects/client/Client.js +0 -19
- package/dist/api/resources/usage/client/Client.d.ts +0 -11
- package/dist/api/resources/usage/client/Client.js +0 -12
- package/dist/api/resources/webhooks/client/Client.d.ts +0 -29
- package/dist/api/resources/webhooks/client/Client.js +0 -76
- package/dist/api/serialization.d.ts +0 -21
- package/dist/api/serialization.js +0 -274
package/dist/Client.js
CHANGED
|
@@ -1,816 +1,91 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
3
|
exports.DiffioClient = void 0;
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
const supplier_1 = require("./core/supplier");
|
|
40
|
-
const url_1 = require("./core/url");
|
|
41
|
-
const retry_1 = require("./core/retry");
|
|
4
|
+
const transport_1 = require("./core/transport");
|
|
5
|
+
const files_1 = require("./core/files");
|
|
42
6
|
const errors_1 = require("./errors");
|
|
43
|
-
const edgeUpload_1 = require("./core/edgeUpload");
|
|
44
|
-
const serialization_1 = require("./api/serialization");
|
|
45
7
|
const resources_1 = require("./api/resources");
|
|
46
|
-
|
|
47
|
-
const DEFAULT_BASE_URL = "https://api.diffio.ai";
|
|
48
|
-
const API_PREFIX = "v1";
|
|
49
|
-
/** Generation endpoint for each supported model, as api/model_registry.json in diffio-ui lists them. */
|
|
50
|
-
const MODEL_ENDPOINTS = {
|
|
51
|
-
"diffio-4.7-flash": "diffio-4.7-flash-generation",
|
|
52
|
-
"diffio-4.7-pro": "diffio-4.7-pro-generation"
|
|
53
|
-
};
|
|
54
|
-
/** Deprecated aliases (the registry's `aliases`); each runs the matching 4.7 model, without a warning. */
|
|
55
|
-
const DEPRECATED_MODEL_KEYS = {
|
|
56
|
-
"diffio-4.6-flash": "diffio-4.7-flash",
|
|
57
|
-
"diffio-4.6-pro": "diffio-4.7-pro",
|
|
58
|
-
"diffio-4.5-flash": "diffio-4.7-flash",
|
|
59
|
-
"diffio-4.5-pro": "diffio-4.7-pro"
|
|
60
|
-
};
|
|
61
|
-
/** The registry's `freeDefault` model; Pro is paid-only, so it cannot be the default for every key. */
|
|
62
|
-
const DEFAULT_MODEL_KEY = "diffio-4.7-flash";
|
|
63
|
-
const SUPPORTED_MODEL_KEYS = Object.keys(MODEL_ENDPOINTS);
|
|
64
|
-
const hasOwn = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
|
|
65
|
-
/** Returns the generation endpoint for a model key, or undefined when the SDK does not support it. */
|
|
66
|
-
function generationEndpointForModel(model) {
|
|
67
|
-
const modelKey = hasOwn(DEPRECATED_MODEL_KEYS, model) ? DEPRECATED_MODEL_KEYS[model] : model;
|
|
68
|
-
return hasOwn(MODEL_ENDPOINTS, modelKey) ? MODEL_ENDPOINTS[modelKey] : undefined;
|
|
69
|
-
}
|
|
70
|
-
/** Per-request timeout for one edge upload call; a 32 MiB part needs about 1 Mbit/s to finish in time. */
|
|
71
|
-
const DEFAULT_EDGE_UPLOAD_TIMEOUT_SECONDS = 300;
|
|
72
|
-
/** complete_project_upload is idempotent, so it is retried even when the client disables retries by default. */
|
|
73
|
-
const DEFAULT_COMPLETE_UPLOAD_MAX_RETRIES = 3;
|
|
74
|
-
const DEFAULT_RETRY_STATUS_CODES = [408, 429, 500, 502, 503, 504];
|
|
75
|
-
const DEFAULT_RETRY_BACKOFF = 0.5;
|
|
76
|
-
const DEFAULT_TIMEOUT_SECONDS = 60;
|
|
77
|
-
/** How long waitForGeneration polls by default; fleet generations can queue and run for minutes (matches the Python SDK). */
|
|
78
|
-
const DEFAULT_GENERATION_WAIT_TIMEOUT_SECONDS = 600;
|
|
79
|
-
const WEBHOOK_EVENT_TYPES = [
|
|
80
|
-
"generation.queued",
|
|
81
|
-
"generation.processing",
|
|
82
|
-
"generation.failed",
|
|
83
|
-
"generation.completed"
|
|
84
|
-
];
|
|
85
|
-
const WEBHOOK_MODES = ["test", "live"];
|
|
8
|
+
/** Client for Diffio API v2 (`https://api.diffio.ai/v2`). */
|
|
86
9
|
class DiffioClient {
|
|
87
10
|
constructor(options = {}) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
this.
|
|
100
|
-
this.
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
resolvedContentLength = getFileSize(filePath);
|
|
115
|
-
}
|
|
116
|
-
const payload = {
|
|
117
|
-
fileName: resolvedFileName,
|
|
118
|
-
contentType: resolvedContentType
|
|
119
|
-
};
|
|
120
|
-
if (resolvedContentLength != null) {
|
|
121
|
-
payload.contentLength = Number(resolvedContentLength);
|
|
122
|
-
}
|
|
123
|
-
if (params) {
|
|
124
|
-
payload.params = params;
|
|
125
|
-
}
|
|
126
|
-
if (fileFormat != null) {
|
|
127
|
-
payload.fileFormat = fileFormat;
|
|
128
|
-
}
|
|
129
|
-
const response = await this._requestJson("POST", "create_project", payload, requestOptions);
|
|
130
|
-
const apiProjectId = typeof response?.apiProjectId === "string" ? response.apiProjectId : undefined;
|
|
131
|
-
const session = (0, edgeUpload_1.parseEdgeUploadSession)(response?.upload);
|
|
132
|
-
if (!apiProjectId || !session) {
|
|
133
|
-
throw new errors_1.DiffioUploadError("upload/invalid-response", "create_project did not return an upload session (apiProjectId and upload are required).", { responseBody: response, apiProjectId });
|
|
134
|
-
}
|
|
135
|
-
try {
|
|
136
|
-
const sizeBytes = getFileSize(filePath);
|
|
137
|
-
const fileHandle = await openFileForReading(filePath);
|
|
138
|
-
try {
|
|
139
|
-
await (0, edgeUpload_1.uploadProjectMediaToEdge)({
|
|
140
|
-
session,
|
|
141
|
-
sizeBytes,
|
|
142
|
-
readPartBytes: (startByte, endByte) => readFileBytes(fileHandle, startByte, endByte),
|
|
143
|
-
sendEdgeRequest: (request) => this._sendEdgeUploadRequest(request, requestOptions)
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
finally {
|
|
147
|
-
await fileHandle.close();
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
catch (error) {
|
|
151
|
-
if (error instanceof errors_1.DiffioUploadError) {
|
|
152
|
-
error.apiProjectId = error.apiProjectId ?? apiProjectId;
|
|
153
|
-
}
|
|
154
|
-
throw error;
|
|
155
|
-
}
|
|
156
|
-
const uploadCompletion = await this.completeProjectUpload({ apiProjectId, requestOptions });
|
|
157
|
-
return (0, serialization_1.createProjectUploadResult)(response, session, uploadCompletion);
|
|
11
|
+
this.transport = new transport_1.Transport({
|
|
12
|
+
apiKey: options.apiKey,
|
|
13
|
+
baseUrl: options.baseUrl,
|
|
14
|
+
endUser: options.endUser ?? null,
|
|
15
|
+
timeout: options.timeout,
|
|
16
|
+
maxRetries: options.maxRetries,
|
|
17
|
+
retryBackoff: options.retryBackoff,
|
|
18
|
+
retryStatusCodes: options.retryStatusCodes,
|
|
19
|
+
headers: options.headers,
|
|
20
|
+
fetch: options.fetch
|
|
21
|
+
});
|
|
22
|
+
this.models = new resources_1.ModelsResource(this.transport);
|
|
23
|
+
this.projects = new resources_1.ProjectsResource(this.transport);
|
|
24
|
+
this.generations = new resources_1.GenerationsResource(this.transport);
|
|
25
|
+
this.edits = new resources_1.EditsResource(this.transport);
|
|
26
|
+
this.mix = new resources_1.MixResource(this.transport);
|
|
27
|
+
this.exports = new resources_1.ExportsResource(this.transport);
|
|
28
|
+
this.transcripts = new resources_1.TranscriptsResource(this.transport);
|
|
29
|
+
this.assistant = new resources_1.AssistantResource(this.transport);
|
|
30
|
+
this.shares = new resources_1.SharesResource(this.transport);
|
|
31
|
+
this.usage = new resources_1.UsageResource(this.transport);
|
|
32
|
+
this.webhooks = new resources_1.WebhooksResource(this.transport);
|
|
33
|
+
}
|
|
34
|
+
/** The v2 base URL calls go to, such as `https://api.diffio.ai/v2`. */
|
|
35
|
+
baseUrl() {
|
|
36
|
+
return this.transport.baseUrl();
|
|
158
37
|
}
|
|
159
38
|
/**
|
|
160
|
-
*
|
|
161
|
-
*
|
|
39
|
+
* One call: creates a project with a generation, uploads the file, waits for the restore and downloads the
|
|
40
|
+
* result. Throws DiffioResourceFailedError when the restore fails and DiffioTimeoutError on timeout.
|
|
162
41
|
*/
|
|
163
|
-
async
|
|
164
|
-
const {
|
|
165
|
-
if (
|
|
166
|
-
throw new
|
|
167
|
-
|
|
168
|
-
|
|
42
|
+
async restoreAudio(params) {
|
|
43
|
+
const { file, model = "diffio-flash", outputPath, file_name, content_type, metadata, label, sampling, downloadFile = "audio", timeout, pollInterval, onProgress, onUploadProgress, idempotencyKey, ...requestOptions } = params ?? {};
|
|
44
|
+
if (file === undefined || file === null)
|
|
45
|
+
throw new TypeError("file is required");
|
|
46
|
+
const resolved = await (0, files_1.resolveFileInput)(file);
|
|
47
|
+
await resolved.source.close?.();
|
|
48
|
+
const fileName = file_name ?? resolved.file_name;
|
|
49
|
+
if (!fileName)
|
|
50
|
+
throw new errors_1.DiffioError("file_name is required when file is bytes or a Blob without a name");
|
|
51
|
+
const contentType = content_type ?? resolved.content_type ?? (0, files_1.guessContentType)(fileName) ?? undefined;
|
|
52
|
+
const generationParams = { model };
|
|
53
|
+
if (label !== undefined)
|
|
54
|
+
generationParams.label = label;
|
|
55
|
+
if (sampling !== undefined)
|
|
56
|
+
generationParams.sampling = sampling;
|
|
57
|
+
const created = await this.projects.create({
|
|
58
|
+
file_name: fileName,
|
|
59
|
+
...(contentType ? { content_type: contentType } : {}),
|
|
60
|
+
size_bytes: resolved.source.sizeBytes,
|
|
61
|
+
...(metadata ? { metadata } : {}),
|
|
62
|
+
generation: generationParams
|
|
63
|
+
}, { ...requestOptions, idempotencyKey });
|
|
64
|
+
const project = await this.projects.upload(created, file, { ...requestOptions, onUploadProgress });
|
|
65
|
+
let generationId = created.latest_generation?.id;
|
|
66
|
+
if (!generationId) {
|
|
67
|
+
const generation = await this.generations.create(created.id, generationParams, requestOptions);
|
|
68
|
+
generationId = generation.id;
|
|
69
|
+
}
|
|
70
|
+
const generation = await this.generations.wait(created.id, generationId, {
|
|
169
71
|
...requestOptions,
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
return (0, serialization_1.parseCompleteProjectUploadResponse)(response);
|
|
174
|
-
}
|
|
175
|
-
/** Sends one edge upload call with the session's upload token; never the API key or SDK default headers. */
|
|
176
|
-
async _sendEdgeUploadRequest(request, requestOptions) {
|
|
177
|
-
const fetchFn = this._options.fetch ?? globalThis.fetch;
|
|
178
|
-
if (!fetchFn) {
|
|
179
|
-
throw new errors_1.DiffioApiError("fetch is not available in this runtime");
|
|
180
|
-
}
|
|
181
|
-
const timeoutSeconds = requestOptions?.timeoutInSeconds ?? requestOptions?.timeout ?? DEFAULT_EDGE_UPLOAD_TIMEOUT_SECONDS;
|
|
182
|
-
// A Uint8Array or string body has a known length, so fetch sends the Content-Length the edge requires.
|
|
183
|
-
const response = await fetchWithTimeout(fetchFn, request.url, {
|
|
184
|
-
method: request.method,
|
|
185
|
-
headers: {
|
|
186
|
-
Authorization: `Bearer ${request.bearerToken}`,
|
|
187
|
-
"Content-Type": request.contentType
|
|
188
|
-
},
|
|
189
|
-
body: request.body
|
|
190
|
-
}, timeoutSeconds * 1000, requestOptions?.abortSignal);
|
|
191
|
-
return { status: response.status, bodyText: await response.text() };
|
|
192
|
-
}
|
|
193
|
-
/** Retries generation admission only when the caller supplies a nonblank idempotency key. */
|
|
194
|
-
async createGeneration(options) {
|
|
195
|
-
const { apiProjectId, model = DEFAULT_MODEL_KEY, sampling, params, idempotencyKey, requestOptions } = options;
|
|
196
|
-
const endpoint = generationEndpointForModel(model);
|
|
197
|
-
if (!endpoint) {
|
|
198
|
-
throw new errors_1.DiffioApiError(`Unsupported model: ${model}. Use ${SUPPORTED_MODEL_KEYS.join(" or ")}.`);
|
|
199
|
-
}
|
|
200
|
-
const payload = { apiProjectId };
|
|
201
|
-
if (sampling != null) {
|
|
202
|
-
payload.sampling = sampling;
|
|
203
|
-
}
|
|
204
|
-
if (params) {
|
|
205
|
-
payload.params = params;
|
|
206
|
-
}
|
|
207
|
-
if (idempotencyKey != null) {
|
|
208
|
-
payload.idempotencyKey = idempotencyKey;
|
|
209
|
-
}
|
|
210
|
-
const generationRequestOptions = idempotencyKey?.trim()
|
|
211
|
-
? requestOptions
|
|
212
|
-
: { ...requestOptions, maxRetries: 0 };
|
|
213
|
-
const response = await this._requestJson("POST", endpoint, payload, generationRequestOptions);
|
|
214
|
-
return (0, serialization_1.parseCreateGenerationResponse)(response);
|
|
215
|
-
}
|
|
216
|
-
async listProjects(options = {}) {
|
|
217
|
-
const response = await this._requestJson("POST", "list_projects", {}, options.requestOptions);
|
|
218
|
-
return (0, serialization_1.parseListProjectsResponse)(response);
|
|
219
|
-
}
|
|
220
|
-
async listProjectGenerations(options) {
|
|
221
|
-
const { apiProjectId, requestOptions } = options;
|
|
222
|
-
if (!apiProjectId) {
|
|
223
|
-
throw new errors_1.DiffioApiError("apiProjectId is required");
|
|
224
|
-
}
|
|
225
|
-
const response = await this._requestJson("POST", "list_project_generations", { apiProjectId }, requestOptions);
|
|
226
|
-
return (0, serialization_1.parseListProjectGenerationsResponse)(response);
|
|
227
|
-
}
|
|
228
|
-
async getGenerationProgress(options) {
|
|
229
|
-
const { generationId, apiProjectId, requestOptions } = options;
|
|
230
|
-
const payload = { generationId };
|
|
231
|
-
if (apiProjectId != null) {
|
|
232
|
-
payload.apiProjectId = apiProjectId;
|
|
233
|
-
}
|
|
234
|
-
const response = await this._requestJson("POST", "get_generation_progress", payload, requestOptions);
|
|
235
|
-
return (0, serialization_1.parseGenerationProgressResponse)(response);
|
|
236
|
-
}
|
|
237
|
-
/** Waits for media completion and settlement; transcription may still be pending or unavailable. */
|
|
238
|
-
async waitForGeneration(options) {
|
|
239
|
-
const { generationId, apiProjectId, pollInterval = 2, timeout, timeoutInSeconds, onProgress, showProgress, requestOptions } = options;
|
|
240
|
-
const timeoutSeconds = timeoutInSeconds ?? timeout ?? DEFAULT_GENERATION_WAIT_TIMEOUT_SECONDS;
|
|
241
|
-
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
242
|
-
let lastProgress = null;
|
|
243
|
-
while (Date.now() < deadline) {
|
|
244
|
-
const progress = await this.getGenerationProgress({ generationId, apiProjectId, requestOptions });
|
|
245
|
-
lastProgress = progress;
|
|
246
|
-
await reportProgress(progress, onProgress, showProgress);
|
|
247
|
-
if (progress.status === "complete") {
|
|
248
|
-
return progress;
|
|
249
|
-
}
|
|
250
|
-
if (progress.status === "failed") {
|
|
251
|
-
throw new errors_1.DiffioApiError("Generation failed" +
|
|
252
|
-
` (preProcessing=${progress.preProcessing.status},` +
|
|
253
|
-
` inference=${progress.inference.status},` +
|
|
254
|
-
` error=${progress.error},` +
|
|
255
|
-
` details=${progress.errorDetails})`);
|
|
256
|
-
}
|
|
257
|
-
await sleepSeconds(pollInterval);
|
|
258
|
-
}
|
|
259
|
-
throw new errors_1.DiffioApiError("Timed out waiting for generation completion" +
|
|
260
|
-
` (lastStatus=${lastProgress ? lastProgress.status : "unknown"})`);
|
|
261
|
-
}
|
|
262
|
-
async getGenerationDownload(options) {
|
|
263
|
-
const { generationId, apiProjectId, downloadType, requestOptions } = options;
|
|
264
|
-
const payload = { generationId, apiProjectId };
|
|
265
|
-
if (downloadType != null) {
|
|
266
|
-
if (downloadType !== "audio" && downloadType !== "video" && downloadType !== "transcript") {
|
|
267
|
-
throw new errors_1.DiffioApiError("downloadType must be audio, video, or transcript");
|
|
268
|
-
}
|
|
269
|
-
payload.downloadType = downloadType;
|
|
270
|
-
}
|
|
271
|
-
const response = await this._requestJson("POST", "get_generation_download", payload, requestOptions);
|
|
272
|
-
return (0, serialization_1.parseGenerationDownloadResponse)(response);
|
|
273
|
-
}
|
|
274
|
-
async getAccountSettings(options = {}) {
|
|
275
|
-
const response = await this._requestJson("POST", "account/settings/get", {}, options.requestOptions);
|
|
276
|
-
return (0, serialization_1.parseAccountSettingsResponse)(response);
|
|
277
|
-
}
|
|
278
|
-
async updateAccountSettings(options) {
|
|
279
|
-
const { billingPolicy, requestOptions } = options;
|
|
280
|
-
if (!billingPolicy || typeof billingPolicy !== "object" || Array.isArray(billingPolicy)) {
|
|
281
|
-
throw new errors_1.DiffioApiError("billingPolicy must be an object");
|
|
282
|
-
}
|
|
283
|
-
const response = await this._requestJson("POST", "account/settings/update", { billingPolicy }, requestOptions);
|
|
284
|
-
return (0, serialization_1.parseAccountSettingsResponse)(response);
|
|
285
|
-
}
|
|
286
|
-
async createApiKey(options) {
|
|
287
|
-
const { label, scopes, resourceBounds, requestOptions } = options;
|
|
288
|
-
if (!label) {
|
|
289
|
-
throw new errors_1.DiffioApiError("label is required");
|
|
290
|
-
}
|
|
291
|
-
if (!Array.isArray(scopes)) {
|
|
292
|
-
throw new errors_1.DiffioApiError("scopes must be an array");
|
|
293
|
-
}
|
|
294
|
-
const response = await this._requestJson("POST", "api_keys/create", { label, scopes, resourceBounds: resourceBounds ?? {} }, requestOptions);
|
|
295
|
-
return (0, serialization_1.parseApiKeyResponse)(response);
|
|
296
|
-
}
|
|
297
|
-
async listApiKeys(options = {}) {
|
|
298
|
-
const response = await this._requestJson("POST", "api_keys/list", {}, options.requestOptions);
|
|
299
|
-
return (0, serialization_1.parseApiKeysListResponse)(response);
|
|
300
|
-
}
|
|
301
|
-
async rotateApiKey(options) {
|
|
302
|
-
const { keyId, requestOptions } = options;
|
|
303
|
-
if (!keyId) {
|
|
304
|
-
throw new errors_1.DiffioApiError("keyId is required");
|
|
305
|
-
}
|
|
306
|
-
const response = await this._requestJson("POST", "api_keys/rotate", { keyId }, requestOptions);
|
|
307
|
-
return (0, serialization_1.parseApiKeyResponse)(response);
|
|
308
|
-
}
|
|
309
|
-
async revokeApiKey(options) {
|
|
310
|
-
const { keyId, requestOptions } = options;
|
|
311
|
-
if (!keyId) {
|
|
312
|
-
throw new errors_1.DiffioApiError("keyId is required");
|
|
313
|
-
}
|
|
314
|
-
const response = await this._requestJson("POST", "api_keys/revoke", { keyId }, requestOptions);
|
|
315
|
-
return (0, serialization_1.parseApiKeyResponse)(response);
|
|
316
|
-
}
|
|
317
|
-
async getUsageSummary(options = {}) {
|
|
318
|
-
const payload = {};
|
|
319
|
-
if (options.apiKeyId != null) {
|
|
320
|
-
payload.apiKeyId = options.apiKeyId;
|
|
321
|
-
}
|
|
322
|
-
const response = await this._requestJson("POST", "usage/summary", payload, options.requestOptions);
|
|
323
|
-
return (0, serialization_1.parseUsageSummaryResponse)(response);
|
|
324
|
-
}
|
|
325
|
-
async configureWebhook(options) {
|
|
326
|
-
const { mode, url, eventTypes, apiKeyId, requestOptions } = options;
|
|
327
|
-
if (!WEBHOOK_MODES.includes(mode)) {
|
|
328
|
-
throw new errors_1.DiffioApiError("mode must be test or live");
|
|
329
|
-
}
|
|
330
|
-
if (!url) {
|
|
331
|
-
throw new errors_1.DiffioApiError("url is required");
|
|
332
|
-
}
|
|
333
|
-
if (!Array.isArray(eventTypes) || eventTypes.length === 0) {
|
|
334
|
-
throw new errors_1.DiffioApiError("eventTypes must be a non-empty array");
|
|
335
|
-
}
|
|
336
|
-
const payload = { mode, url, eventTypes };
|
|
337
|
-
if (apiKeyId != null) {
|
|
338
|
-
payload.apiKeyId = apiKeyId;
|
|
339
|
-
}
|
|
340
|
-
const response = await this._requestJson("POST", "webhooks/configure", payload, requestOptions);
|
|
341
|
-
return (0, serialization_1.parseWebhookConfigureResponse)(response);
|
|
342
|
-
}
|
|
343
|
-
async sendWebhookTestEvent(options) {
|
|
344
|
-
const { eventType, mode, apiKeyId, samplePayload, requestOptions } = options;
|
|
345
|
-
if (!WEBHOOK_EVENT_TYPES.includes(eventType)) {
|
|
346
|
-
throw new errors_1.DiffioApiError("eventType is not supported");
|
|
347
|
-
}
|
|
348
|
-
if (!WEBHOOK_MODES.includes(mode)) {
|
|
349
|
-
throw new errors_1.DiffioApiError("mode must be test or live");
|
|
350
|
-
}
|
|
351
|
-
if (samplePayload != null && (typeof samplePayload !== "object" || Array.isArray(samplePayload))) {
|
|
352
|
-
throw new errors_1.DiffioApiError("samplePayload must be an object");
|
|
353
|
-
}
|
|
354
|
-
const payload = { eventType, mode };
|
|
355
|
-
if (apiKeyId != null) {
|
|
356
|
-
payload.apiKeyId = apiKeyId;
|
|
357
|
-
}
|
|
358
|
-
if (samplePayload != null) {
|
|
359
|
-
payload.samplePayload = samplePayload;
|
|
360
|
-
}
|
|
361
|
-
const response = await this._requestJson("POST", "webhooks/send_test_event", payload, requestOptions);
|
|
362
|
-
return (0, serialization_1.parseWebhookTestEventResponse)(response);
|
|
363
|
-
}
|
|
364
|
-
async restoreAudio(options) {
|
|
365
|
-
const metadata = initRestoreMetadata();
|
|
366
|
-
metadata.downloadType = options.downloadType ?? "audio";
|
|
367
|
-
const resolvedProgressOptions = options.progressRequestOptions ?? options.requestOptions;
|
|
368
|
-
const resolvedDownloadOptions = options.downloadRequestOptions ?? options.requestOptions;
|
|
369
|
-
let result = null;
|
|
370
|
-
try {
|
|
371
|
-
result = await this.audioIsolationIsolate({
|
|
372
|
-
filePath: options.filePath,
|
|
373
|
-
contentType: options.contentType,
|
|
374
|
-
contentLength: options.contentLength,
|
|
375
|
-
fileFormat: options.fileFormat,
|
|
376
|
-
model: options.model,
|
|
377
|
-
sampling: options.sampling,
|
|
378
|
-
projectParams: options.projectParams,
|
|
379
|
-
generationParams: options.generationParams,
|
|
380
|
-
idempotencyKey: options.idempotencyKey,
|
|
381
|
-
requestOptions: options.requestOptions
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
catch (error) {
|
|
385
|
-
metadata.stage = "isolate";
|
|
386
|
-
setRestoreError(metadata, error);
|
|
387
|
-
if (options.raiseOnError) {
|
|
388
|
-
attachRestoreMetadata(error, metadata);
|
|
389
|
-
throw error;
|
|
390
|
-
}
|
|
391
|
-
return [null, metadata];
|
|
392
|
-
}
|
|
393
|
-
metadata.project = result.project;
|
|
394
|
-
metadata.generation = result.generation;
|
|
395
|
-
metadata.apiProjectId = result.project.apiProjectId;
|
|
396
|
-
metadata.generationId = result.generation.generationId;
|
|
397
|
-
metadata.stage = "generation";
|
|
398
|
-
let progress = null;
|
|
399
|
-
try {
|
|
400
|
-
progress = await this.waitForGeneration({
|
|
401
|
-
generationId: result.generation.generationId,
|
|
402
|
-
apiProjectId: result.project.apiProjectId,
|
|
403
|
-
pollInterval: options.pollInterval,
|
|
404
|
-
timeout: options.timeout,
|
|
405
|
-
timeoutInSeconds: options.timeoutInSeconds,
|
|
406
|
-
onProgress: options.onProgress,
|
|
407
|
-
showProgress: options.showProgress,
|
|
408
|
-
requestOptions: resolvedProgressOptions
|
|
409
|
-
});
|
|
410
|
-
}
|
|
411
|
-
catch (error) {
|
|
412
|
-
metadata.stage = "progress";
|
|
413
|
-
try {
|
|
414
|
-
progress = await this.getGenerationProgress({
|
|
415
|
-
generationId: result.generation.generationId,
|
|
416
|
-
apiProjectId: result.project.apiProjectId,
|
|
417
|
-
requestOptions: resolvedProgressOptions
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
catch {
|
|
421
|
-
progress = null;
|
|
422
|
-
}
|
|
423
|
-
metadata.progress = progress;
|
|
424
|
-
metadata.status = progress?.status ?? null;
|
|
425
|
-
setRestoreError(metadata, error);
|
|
426
|
-
if (progress) {
|
|
427
|
-
metadata.error = progress.error ?? String(error);
|
|
428
|
-
metadata.errorDetails = progress.errorDetails ?? null;
|
|
429
|
-
}
|
|
430
|
-
if (options.raiseOnError) {
|
|
431
|
-
attachRestoreMetadata(error, metadata);
|
|
432
|
-
throw error;
|
|
433
|
-
}
|
|
434
|
-
return [null, metadata];
|
|
435
|
-
}
|
|
436
|
-
metadata.progress = progress;
|
|
437
|
-
metadata.status = progress.status;
|
|
438
|
-
metadata.error = progress.error ?? null;
|
|
439
|
-
metadata.errorDetails = progress.errorDetails ?? null;
|
|
440
|
-
metadata.stage = "download_info";
|
|
441
|
-
let download;
|
|
442
|
-
try {
|
|
443
|
-
download = await this.getGenerationDownload({
|
|
444
|
-
generationId: result.generation.generationId,
|
|
445
|
-
apiProjectId: result.project.apiProjectId,
|
|
446
|
-
downloadType: options.downloadType ?? "audio",
|
|
447
|
-
requestOptions: resolvedDownloadOptions
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
catch (error) {
|
|
451
|
-
setRestoreError(metadata, error);
|
|
452
|
-
if (options.raiseOnError) {
|
|
453
|
-
attachRestoreMetadata(error, metadata);
|
|
454
|
-
throw error;
|
|
455
|
-
}
|
|
456
|
-
return [null, metadata];
|
|
457
|
-
}
|
|
458
|
-
metadata.download = download;
|
|
459
|
-
metadata.downloadType = download.downloadType;
|
|
460
|
-
metadata.downloadUrl = download.downloadUrl;
|
|
461
|
-
metadata.fileName = download.fileName;
|
|
462
|
-
metadata.mimeType = download.mimeType;
|
|
463
|
-
metadata.stage = "download";
|
|
464
|
-
let content;
|
|
465
|
-
try {
|
|
466
|
-
content = await this._downloadBinary(download.downloadUrl, resolvedDownloadOptions);
|
|
467
|
-
}
|
|
468
|
-
catch (error) {
|
|
469
|
-
setRestoreError(metadata, error);
|
|
470
|
-
if (options.raiseOnError) {
|
|
471
|
-
attachRestoreMetadata(error, metadata);
|
|
472
|
-
throw error;
|
|
473
|
-
}
|
|
474
|
-
return [null, metadata];
|
|
475
|
-
}
|
|
476
|
-
metadata.stage = "complete";
|
|
477
|
-
metadata.ok = true;
|
|
478
|
-
return [content, metadata];
|
|
479
|
-
}
|
|
480
|
-
async restore(options) {
|
|
481
|
-
return this.restoreAudio(options);
|
|
482
|
-
}
|
|
483
|
-
async audioIsolationIsolate(options) {
|
|
484
|
-
const project = await this.createProject({
|
|
485
|
-
filePath: options.filePath,
|
|
486
|
-
contentType: options.contentType,
|
|
487
|
-
contentLength: options.contentLength,
|
|
488
|
-
params: options.projectParams,
|
|
489
|
-
fileFormat: options.fileFormat,
|
|
490
|
-
requestOptions: options.requestOptions
|
|
491
|
-
});
|
|
492
|
-
const generation = await this.createGeneration({
|
|
493
|
-
apiProjectId: project.apiProjectId,
|
|
494
|
-
model: options.model,
|
|
495
|
-
sampling: options.sampling,
|
|
496
|
-
params: options.generationParams,
|
|
497
|
-
idempotencyKey: options.idempotencyKey,
|
|
498
|
-
requestOptions: options.requestOptions
|
|
72
|
+
timeout,
|
|
73
|
+
pollInterval,
|
|
74
|
+
onProgress
|
|
499
75
|
});
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const response = await this._requestBinary("GET", downloadUrl, () => undefined, requestOptions, {}, true);
|
|
505
|
-
return response;
|
|
506
|
-
}
|
|
507
|
-
async _requestJson(method, path, payload, requestOptions) {
|
|
508
|
-
const { url, headers, timeoutMs, maxRetries, retryBackoff, retryStatusCodes, fetchFn, abortSignal } = await this._buildRequest(method, path, requestOptions, {
|
|
509
|
-
"Content-Type": "application/json"
|
|
76
|
+
const download = await this.generations.download(created.id, generationId, {
|
|
77
|
+
...requestOptions,
|
|
78
|
+
file: downloadFile,
|
|
79
|
+
path: outputPath
|
|
510
80
|
});
|
|
511
|
-
const requestBody = JSON.stringify(payload);
|
|
512
|
-
const makeRequest = () => fetchWithTimeout(fetchFn, url, {
|
|
513
|
-
method,
|
|
514
|
-
headers,
|
|
515
|
-
body: requestBody
|
|
516
|
-
}, timeoutMs, abortSignal);
|
|
517
|
-
const response = await (0, retry_1.requestWithRetries)(makeRequest, { maxRetries, retryBackoff, retryStatusCodes });
|
|
518
|
-
return parseJsonResponse(response);
|
|
519
|
-
}
|
|
520
|
-
async _requestBinary(method, urlOrPath, bodyFactory, requestOptions, extraHeaders, isAbsoluteUrl = false) {
|
|
521
|
-
const { url, headers, timeoutMs, maxRetries, retryBackoff, retryStatusCodes, fetchFn, abortSignal } = await this._buildRequest(method, urlOrPath, requestOptions, extraHeaders, isAbsoluteUrl);
|
|
522
|
-
const makeRequest = async () => {
|
|
523
|
-
const body = await bodyFactory();
|
|
524
|
-
const requestInit = {
|
|
525
|
-
method,
|
|
526
|
-
headers,
|
|
527
|
-
body: body,
|
|
528
|
-
signal: abortSignal
|
|
529
|
-
};
|
|
530
|
-
if (body && isNodeReadable(body)) {
|
|
531
|
-
requestInit.duplex = "half";
|
|
532
|
-
}
|
|
533
|
-
try {
|
|
534
|
-
return await fetchWithTimeout(fetchFn, url, requestInit, timeoutMs, abortSignal);
|
|
535
|
-
}
|
|
536
|
-
finally {
|
|
537
|
-
destroyNodeReadable(body);
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
const response = await (0, retry_1.requestWithRetries)(makeRequest, { maxRetries, retryBackoff, retryStatusCodes });
|
|
541
|
-
if (method === "GET") {
|
|
542
|
-
return parseBinaryResponse(response);
|
|
543
|
-
}
|
|
544
|
-
await parseJsonResponse(response);
|
|
545
|
-
}
|
|
546
|
-
async _buildRequest(method, path, requestOptions, extraHeaders, isAbsoluteUrl = false) {
|
|
547
|
-
const { baseUrl, apiPrefix } = await resolveBaseUrl(this._options.baseUrl);
|
|
548
|
-
const apiKey = requestOptions?.apiKey ?? (await supplier_1.Supplier.get(this._options.apiKey));
|
|
549
|
-
if (!apiKey && !isAbsoluteUrl) {
|
|
550
|
-
throw new errors_1.DiffioApiError("apiKey is required");
|
|
551
|
-
}
|
|
552
|
-
const baseHeaders = isAbsoluteUrl ? undefined : this._options.headers;
|
|
553
|
-
const authHeaders = !isAbsoluteUrl && apiKey ? (0, headers_1.mergeOnlyDefinedHeaders)({ Authorization: `Bearer ${apiKey}` }) : undefined;
|
|
554
|
-
const mergedHeaders = (0, headers_1.mergeHeaders)(baseHeaders, authHeaders, requestOptions?.headers, extraHeaders);
|
|
555
|
-
const headers = await (0, headers_1.resolveHeaders)(mergedHeaders);
|
|
556
|
-
const timeoutSeconds = requestOptions?.timeoutInSeconds ??
|
|
557
|
-
requestOptions?.timeout ??
|
|
558
|
-
this._options.timeoutInSeconds ??
|
|
559
|
-
this._options.timeout ??
|
|
560
|
-
DEFAULT_TIMEOUT_SECONDS;
|
|
561
|
-
const timeoutMs = timeoutSeconds != null ? timeoutSeconds * 1000 : undefined;
|
|
562
|
-
const maxRetries = requestOptions?.maxRetries ?? this._options.maxRetries ?? 0;
|
|
563
|
-
const retryBackoff = requestOptions?.retryBackoff ?? this._options.retryBackoff ?? DEFAULT_RETRY_BACKOFF;
|
|
564
|
-
const retryStatusCodes = requestOptions?.retryStatusCodes ?? this._options.retryStatusCodes ?? DEFAULT_RETRY_STATUS_CODES;
|
|
565
|
-
const fetchFn = this._options.fetch ?? globalThis.fetch;
|
|
566
|
-
if (!fetchFn) {
|
|
567
|
-
throw new errors_1.DiffioApiError("fetch is not available in this runtime");
|
|
568
|
-
}
|
|
569
|
-
const requestPath = path.replace(/^\/+/, "");
|
|
570
|
-
const url = isAbsoluteUrl
|
|
571
|
-
? path
|
|
572
|
-
: (0, url_1.join)(baseUrl, apiPrefix ? `${apiPrefix}/${requestPath}` : requestPath);
|
|
573
81
|
return {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
fetchFn,
|
|
581
|
-
abortSignal: requestOptions?.abortSignal
|
|
82
|
+
project,
|
|
83
|
+
generation,
|
|
84
|
+
output_path: download.path,
|
|
85
|
+
data: download.data,
|
|
86
|
+
size_bytes: download.size_bytes,
|
|
87
|
+
content_type: download.content_type
|
|
582
88
|
};
|
|
583
89
|
}
|
|
584
90
|
}
|
|
585
91
|
exports.DiffioClient = DiffioClient;
|
|
586
|
-
function isAbortError(error) {
|
|
587
|
-
return typeof error === "object" && error != null && error.name === "AbortError";
|
|
588
|
-
}
|
|
589
|
-
function createAbortSignal(timeoutMs, externalSignal) {
|
|
590
|
-
if (!timeoutMs && !externalSignal) {
|
|
591
|
-
return { cleanup: () => undefined, didTimeout: () => false };
|
|
592
|
-
}
|
|
593
|
-
const controller = new AbortController();
|
|
594
|
-
let timedOut = false;
|
|
595
|
-
let timeoutId = null;
|
|
596
|
-
const abortListener = () => controller.abort();
|
|
597
|
-
if (externalSignal) {
|
|
598
|
-
if (externalSignal.aborted) {
|
|
599
|
-
controller.abort();
|
|
600
|
-
}
|
|
601
|
-
else {
|
|
602
|
-
externalSignal.addEventListener("abort", abortListener, { once: true });
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
if (timeoutMs != null) {
|
|
606
|
-
timeoutId = setTimeout(() => {
|
|
607
|
-
timedOut = true;
|
|
608
|
-
controller.abort();
|
|
609
|
-
}, timeoutMs);
|
|
610
|
-
}
|
|
611
|
-
const cleanup = () => {
|
|
612
|
-
if (timeoutId) {
|
|
613
|
-
clearTimeout(timeoutId);
|
|
614
|
-
}
|
|
615
|
-
if (externalSignal) {
|
|
616
|
-
externalSignal.removeEventListener("abort", abortListener);
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
return { signal: controller.signal, cleanup, didTimeout: () => timedOut };
|
|
620
|
-
}
|
|
621
|
-
async function fetchWithTimeout(fetchFn, url, init, timeoutMs, externalSignal) {
|
|
622
|
-
const { signal, cleanup, didTimeout } = createAbortSignal(timeoutMs, externalSignal);
|
|
623
|
-
try {
|
|
624
|
-
return await fetchFn(url, { ...init, signal });
|
|
625
|
-
}
|
|
626
|
-
catch (error) {
|
|
627
|
-
if (isAbortError(error) && didTimeout()) {
|
|
628
|
-
throw new errors_1.DiffioTimeoutError("Request timed out");
|
|
629
|
-
}
|
|
630
|
-
throw error;
|
|
631
|
-
}
|
|
632
|
-
finally {
|
|
633
|
-
cleanup();
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
function parseJsonResponse(response) {
|
|
637
|
-
if (response.ok) {
|
|
638
|
-
const contentType = response.headers.get("Content-Type") || "";
|
|
639
|
-
if (contentType.includes("application/json")) {
|
|
640
|
-
return response.json();
|
|
641
|
-
}
|
|
642
|
-
if (response.status === 204) {
|
|
643
|
-
return Promise.resolve({});
|
|
644
|
-
}
|
|
645
|
-
return response.text().then((text) => {
|
|
646
|
-
if (!text) {
|
|
647
|
-
return {};
|
|
648
|
-
}
|
|
649
|
-
try {
|
|
650
|
-
return JSON.parse(text);
|
|
651
|
-
}
|
|
652
|
-
catch {
|
|
653
|
-
return {};
|
|
654
|
-
}
|
|
655
|
-
});
|
|
656
|
-
}
|
|
657
|
-
return parseErrorResponse(response).then((errorBody) => {
|
|
658
|
-
const message = getErrorMessage(errorBody, response.status);
|
|
659
|
-
throw new errors_1.DiffioApiError(message, { statusCode: response.status, responseBody: errorBody });
|
|
660
|
-
});
|
|
661
|
-
}
|
|
662
|
-
async function parseBinaryResponse(response) {
|
|
663
|
-
if (response.ok) {
|
|
664
|
-
const buffer = await response.arrayBuffer();
|
|
665
|
-
return new Uint8Array(buffer);
|
|
666
|
-
}
|
|
667
|
-
const errorBody = await parseErrorResponse(response);
|
|
668
|
-
const message = getErrorMessage(errorBody, response.status);
|
|
669
|
-
throw new errors_1.DiffioApiError(message, { statusCode: response.status, responseBody: errorBody });
|
|
670
|
-
}
|
|
671
|
-
async function parseErrorResponse(response) {
|
|
672
|
-
const contentType = response.headers.get("Content-Type") || "";
|
|
673
|
-
if (contentType.includes("application/json")) {
|
|
674
|
-
try {
|
|
675
|
-
return await response.json();
|
|
676
|
-
}
|
|
677
|
-
catch {
|
|
678
|
-
return null;
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
const text = await response.text();
|
|
682
|
-
return text || null;
|
|
683
|
-
}
|
|
684
|
-
function getErrorMessage(body, status) {
|
|
685
|
-
if (body && typeof body === "object" && "error" in body) {
|
|
686
|
-
const error = body.error;
|
|
687
|
-
if (error && typeof error === "object" && typeof error.message === "string") {
|
|
688
|
-
return error.message;
|
|
689
|
-
}
|
|
690
|
-
if (error) {
|
|
691
|
-
return String(error);
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
return `Request failed with status ${status}`;
|
|
695
|
-
}
|
|
696
|
-
async function resolveBaseUrl(baseUrlSupplier) {
|
|
697
|
-
const envBase = typeof process !== "undefined" ? process.env.DIFFIO_API_BASE_URL : undefined;
|
|
698
|
-
const resolvedBase = (await supplier_1.Supplier.get(baseUrlSupplier)) ?? envBase ?? DEFAULT_BASE_URL;
|
|
699
|
-
const trimmed = resolvedBase.replace(/\/+$/, "");
|
|
700
|
-
const apiPrefix = trimmed.endsWith(`/${API_PREFIX}`) ? "" : API_PREFIX;
|
|
701
|
-
return { baseUrl: trimmed, apiPrefix };
|
|
702
|
-
}
|
|
703
|
-
function guessContentType(filePath) {
|
|
704
|
-
const guessed = (0, mime_types_1.lookup)(filePath);
|
|
705
|
-
if (typeof guessed === "string") {
|
|
706
|
-
return guessed;
|
|
707
|
-
}
|
|
708
|
-
return undefined;
|
|
709
|
-
}
|
|
710
|
-
function isNodeReadable(value) {
|
|
711
|
-
return Boolean(value) && typeof value === "object" && typeof value.pipe === "function";
|
|
712
|
-
}
|
|
713
|
-
function destroyNodeReadable(value) {
|
|
714
|
-
const destroy = isNodeReadable(value)
|
|
715
|
-
? value.destroy
|
|
716
|
-
: undefined;
|
|
717
|
-
if (destroy) {
|
|
718
|
-
destroy.call(value);
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
async function openFileForReading(filePath) {
|
|
722
|
-
const fs = await Promise.resolve().then(() => __importStar(require("node:fs/promises")));
|
|
723
|
-
return fs.open(filePath, "r");
|
|
724
|
-
}
|
|
725
|
-
/** Reads bytes [startByte, endByte) of an open file into one buffer, looping over short reads. */
|
|
726
|
-
async function readFileBytes(fileHandle, startByte, endByte) {
|
|
727
|
-
const length = endByte - startByte;
|
|
728
|
-
const buffer = Buffer.alloc(length);
|
|
729
|
-
let offset = 0;
|
|
730
|
-
while (offset < length) {
|
|
731
|
-
const { bytesRead } = await fileHandle.read(buffer, offset, length - offset, startByte + offset);
|
|
732
|
-
if (bytesRead === 0) {
|
|
733
|
-
throw new errors_1.DiffioUploadError("upload/invalid-response", "The file became shorter while it was uploading.");
|
|
734
|
-
}
|
|
735
|
-
offset += bytesRead;
|
|
736
|
-
}
|
|
737
|
-
return buffer;
|
|
738
|
-
}
|
|
739
|
-
function getFileSize(filePath) {
|
|
740
|
-
const fs = require("node:fs");
|
|
741
|
-
return fs.statSync(filePath).size;
|
|
742
|
-
}
|
|
743
|
-
function getBaseName(filePath) {
|
|
744
|
-
const path = require("node:path");
|
|
745
|
-
return path.basename(filePath);
|
|
746
|
-
}
|
|
747
|
-
function initRestoreMetadata() {
|
|
748
|
-
return {
|
|
749
|
-
ok: false,
|
|
750
|
-
stage: "start",
|
|
751
|
-
apiProjectId: null,
|
|
752
|
-
generationId: null,
|
|
753
|
-
project: null,
|
|
754
|
-
generation: null,
|
|
755
|
-
progress: null,
|
|
756
|
-
download: null,
|
|
757
|
-
downloadType: null,
|
|
758
|
-
downloadUrl: null,
|
|
759
|
-
fileName: null,
|
|
760
|
-
mimeType: null,
|
|
761
|
-
status: null,
|
|
762
|
-
error: null,
|
|
763
|
-
errorDetails: null,
|
|
764
|
-
exceptionType: null,
|
|
765
|
-
exceptionMessage: null
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
function setRestoreError(metadata, error) {
|
|
769
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
770
|
-
metadata.error = message;
|
|
771
|
-
metadata.exceptionType = error instanceof Error ? error.name : typeof error;
|
|
772
|
-
metadata.exceptionMessage = message;
|
|
773
|
-
if (error instanceof errors_1.DiffioApiError) {
|
|
774
|
-
metadata.statusCode = error.statusCode;
|
|
775
|
-
metadata.responseBody = error.responseBody;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
function attachRestoreMetadata(error, metadata) {
|
|
779
|
-
if (error && typeof error === "object") {
|
|
780
|
-
try {
|
|
781
|
-
error.restoreInfo = metadata;
|
|
782
|
-
}
|
|
783
|
-
catch {
|
|
784
|
-
return;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
async function reportProgress(progress, onProgress, showProgress) {
|
|
789
|
-
if (onProgress) {
|
|
790
|
-
await onProgress(progress);
|
|
791
|
-
}
|
|
792
|
-
if (showProgress) {
|
|
793
|
-
// eslint-disable-next-line no-console
|
|
794
|
-
console.log(formatProgress(progress));
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
function formatProgress(progress) {
|
|
798
|
-
const parts = [];
|
|
799
|
-
if (progress.preProcessing) {
|
|
800
|
-
parts.push(`pre=${progress.preProcessing.status}:${progress.preProcessing.progress}%`);
|
|
801
|
-
}
|
|
802
|
-
if (progress.inference) {
|
|
803
|
-
parts.push(`inf=${progress.inference.status}:${progress.inference.progress}%`);
|
|
804
|
-
}
|
|
805
|
-
if (progress.restoredVideo) {
|
|
806
|
-
parts.push(`vid=${progress.restoredVideo.status}:${progress.restoredVideo.progress}%`);
|
|
807
|
-
}
|
|
808
|
-
const joined = parts.join(", ");
|
|
809
|
-
if (joined) {
|
|
810
|
-
return `${progress.status} (${joined})`;
|
|
811
|
-
}
|
|
812
|
-
return progress.status;
|
|
813
|
-
}
|
|
814
|
-
async function sleepSeconds(seconds) {
|
|
815
|
-
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
816
|
-
}
|