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
|
@@ -1,62 +1,62 @@
|
|
|
1
1
|
import { DiffioUploadError } from "../errors";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
partSizeBytes: number;
|
|
9
|
-
maxBytes: number;
|
|
10
|
-
expiresAt: string;
|
|
2
|
+
import type { ProjectUpload } from "../api/types";
|
|
3
|
+
/** Bytes to upload: a size and a reader for [start, end). */
|
|
4
|
+
export interface UploadSource {
|
|
5
|
+
sizeBytes: number;
|
|
6
|
+
read(start: number, end: number): Promise<Uint8Array>;
|
|
7
|
+
close?(): Promise<void>;
|
|
11
8
|
}
|
|
12
|
-
/** One planned multipart part: bytes [startByte, endByte) of the file. */
|
|
13
9
|
export interface EdgeUploadPartPlan {
|
|
14
10
|
partNumber: number;
|
|
15
11
|
startByte: number;
|
|
16
12
|
endByte: number;
|
|
17
13
|
}
|
|
18
|
-
/** A finished part as the edge acknowledges it, replayed on completion. */
|
|
19
14
|
export interface EdgeUploadPartReceipt {
|
|
20
15
|
partNumber: number;
|
|
21
16
|
etag: string;
|
|
22
17
|
}
|
|
23
|
-
/** The
|
|
18
|
+
/** The media host's answer to `complete`. */
|
|
24
19
|
export interface EdgeUploadCompletion {
|
|
25
|
-
objectKey: string;
|
|
26
20
|
sizeBytes: number;
|
|
27
21
|
etag: string;
|
|
28
22
|
}
|
|
29
|
-
/** One HTTP request to the edge; the body is a fixed-length buffer because parts need a Content-Length. */
|
|
30
|
-
export interface EdgeUploadHttpRequest {
|
|
31
|
-
method: "POST" | "PUT";
|
|
32
|
-
url: string;
|
|
33
|
-
bearerToken: string;
|
|
34
|
-
body: Uint8Array | string;
|
|
35
|
-
contentType: string;
|
|
36
|
-
}
|
|
37
|
-
/** The edge's answer to one request. Transport failures are thrown instead. */
|
|
38
|
-
export interface EdgeUploadHttpResponse {
|
|
39
|
-
status: number;
|
|
40
|
-
bodyText: string;
|
|
41
|
-
}
|
|
42
|
-
/** Inputs for one upload of a project's original media through the edge. */
|
|
43
23
|
export interface EdgeUploadOptions {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
sendEdgeRequest: (request: EdgeUploadHttpRequest) => Promise<EdgeUploadHttpResponse>;
|
|
24
|
+
upload: ProjectUpload;
|
|
25
|
+
source: UploadSource;
|
|
26
|
+
fetch: typeof fetch;
|
|
27
|
+
/** Parts in flight at once (default 3). */
|
|
49
28
|
partConcurrency?: number;
|
|
29
|
+
/** Attempts per request, first included (default 4). */
|
|
50
30
|
maxAttempts?: number;
|
|
31
|
+
/** Seconds before one media host request gives up (default 300; a 32 MiB part needs about 1 Mbit/s). */
|
|
32
|
+
timeout?: number;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
/** Called after each part lands. */
|
|
35
|
+
onProgress?: (progress: {
|
|
36
|
+
bytes_sent: number;
|
|
37
|
+
bytes_total: number;
|
|
38
|
+
parts_done: number;
|
|
39
|
+
parts_total: number;
|
|
40
|
+
}) => void;
|
|
51
41
|
sleep?: (delayMs: number) => Promise<void>;
|
|
52
42
|
}
|
|
53
43
|
/** Splits a file into fixed-size parts numbered from 1; an empty file is one empty part. */
|
|
54
44
|
export declare function planEdgeUploadParts(sizeBytes: number, partSizeBytes: number): EdgeUploadPartPlan[];
|
|
55
|
-
/** Backoff before
|
|
45
|
+
/** Backoff before attempt `attempt` (2 = first retry): 1 s, 2 s, 4 s, capped at 8 s. */
|
|
56
46
|
export declare function resolveEdgeUploadRetryDelayMs(attempt: number): number;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
47
|
+
type Vars = Record<string, string | number>;
|
|
48
|
+
/** Replaces `{name}` placeholders in a string; a string that is only one placeholder keeps the value's type. */
|
|
49
|
+
export declare function fillTemplateString(template: string, vars: Vars): string | number;
|
|
50
|
+
/**
|
|
51
|
+
* Fills a descriptor body template. An array whose items name per-part placeholders (`{part_number}`,
|
|
52
|
+
* `{etag}`) is expanded once per part, so `"parts": [{"partNumber": "{part_number}", "etag": "{etag}"}]`
|
|
53
|
+
* becomes the full sorted part list with numeric part numbers.
|
|
54
|
+
*/
|
|
55
|
+
export declare function fillTemplate(template: unknown, vars: Vars, parts?: EdgeUploadPartReceipt[]): unknown;
|
|
56
|
+
/** The standard descriptors, for an `upload` object without `requests` (older answers). */
|
|
57
|
+
export declare function defaultUploadRequests(upload: Pick<ProjectUpload, "edge_base_url" | "upload_token">): ProjectUpload["requests"];
|
|
58
|
+
/** Turns a non-2xx media host answer (`{"error": {"code", "message"}}`) into a typed upload error. */
|
|
59
|
+
export declare function classifyEdgeUploadResponse(status: number, bodyText: string): DiffioUploadError;
|
|
60
|
+
/** Uploads the bytes through the descriptors and returns the media host's completion receipt. */
|
|
61
|
+
export declare function uploadToMediaHost(options: EdgeUploadOptions): Promise<EdgeUploadCompletion>;
|
|
62
|
+
export {};
|
package/dist/core/edgeUpload.js
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// four attempts each, complete with the sorted receipts, and abort on a fatal failure.
|
|
2
|
+
// Sends a project's media bytes to Diffio's media host by following the `upload.requests` descriptors that
|
|
3
|
+
// `POST /v2/projects` (and `POST /v2/projects/{id}/upload`) return: `start` once, `part` once per part
|
|
4
|
+
// (numbered from 1, every part but the last exactly `part_size_bytes`), then `complete` listing every part.
|
|
5
|
+
// Parts go up to three at a time with up to four attempts each; a fatal failure sends `abort`.
|
|
7
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
7
|
exports.planEdgeUploadParts = planEdgeUploadParts;
|
|
9
8
|
exports.resolveEdgeUploadRetryDelayMs = resolveEdgeUploadRetryDelayMs;
|
|
10
|
-
exports.
|
|
9
|
+
exports.fillTemplateString = fillTemplateString;
|
|
10
|
+
exports.fillTemplate = fillTemplate;
|
|
11
|
+
exports.defaultUploadRequests = defaultUploadRequests;
|
|
11
12
|
exports.classifyEdgeUploadResponse = classifyEdgeUploadResponse;
|
|
12
|
-
exports.
|
|
13
|
+
exports.uploadToMediaHost = uploadToMediaHost;
|
|
13
14
|
const errors_1 = require("../errors");
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
15
|
+
const transport_1 = require("./transport");
|
|
16
|
+
const retry_1 = require("./retry");
|
|
17
|
+
const DEFAULT_PART_CONCURRENCY = 3;
|
|
18
|
+
const DEFAULT_MAX_ATTEMPTS = 4;
|
|
19
|
+
const DEFAULT_TIMEOUT_SECONDS = 300;
|
|
20
|
+
const PER_PART_PLACEHOLDERS = ["part_number", "etag", "part_length"];
|
|
21
|
+
const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
18
22
|
/** Splits a file into fixed-size parts numbered from 1; an empty file is one empty part. */
|
|
19
23
|
function planEdgeUploadParts(sizeBytes, partSizeBytes) {
|
|
20
24
|
if (!Number.isSafeInteger(sizeBytes) || sizeBytes < 0)
|
|
@@ -30,154 +34,194 @@ function planEdgeUploadParts(sizeBytes, partSizeBytes) {
|
|
|
30
34
|
}
|
|
31
35
|
return parts;
|
|
32
36
|
}
|
|
33
|
-
/** Backoff before
|
|
37
|
+
/** Backoff before attempt `attempt` (2 = first retry): 1 s, 2 s, 4 s, capped at 8 s. */
|
|
34
38
|
function resolveEdgeUploadRetryDelayMs(attempt) {
|
|
35
39
|
return Math.min(8000, 1000 * 2 ** Math.max(0, attempt - 2));
|
|
36
40
|
}
|
|
37
|
-
/**
|
|
38
|
-
function
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
41
|
+
/** Replaces `{name}` placeholders in a string; a string that is only one placeholder keeps the value's type. */
|
|
42
|
+
function fillTemplateString(template, vars) {
|
|
43
|
+
const whole = /^\{(\w+)\}$/.exec(template);
|
|
44
|
+
if (whole && whole[1] in vars)
|
|
45
|
+
return vars[whole[1]];
|
|
46
|
+
return template.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match));
|
|
47
|
+
}
|
|
48
|
+
const mentionsPerPartPlaceholder = (value) => {
|
|
49
|
+
const text = JSON.stringify(value) ?? "";
|
|
50
|
+
return PER_PART_PLACEHOLDERS.some((name) => text.includes(`{${name}}`));
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Fills a descriptor body template. An array whose items name per-part placeholders (`{part_number}`,
|
|
54
|
+
* `{etag}`) is expanded once per part, so `"parts": [{"partNumber": "{part_number}", "etag": "{etag}"}]`
|
|
55
|
+
* becomes the full sorted part list with numeric part numbers.
|
|
56
|
+
*/
|
|
57
|
+
function fillTemplate(template, vars, parts = []) {
|
|
58
|
+
if (typeof template === "string")
|
|
59
|
+
return fillTemplateString(template, vars);
|
|
60
|
+
if (Array.isArray(template)) {
|
|
61
|
+
if (template.length > 0 && template.every(mentionsPerPartPlaceholder)) {
|
|
62
|
+
return parts.flatMap((part) => template.map((item) => fillTemplate(item, { ...vars, part_number: part.partNumber, etag: part.etag }, parts)));
|
|
63
|
+
}
|
|
64
|
+
return template.map((item) => fillTemplate(item, vars, parts));
|
|
49
65
|
}
|
|
66
|
+
if (isRecord(template)) {
|
|
67
|
+
return Object.fromEntries(Object.entries(template).map(([key, value]) => [key, fillTemplate(value, vars, parts)]));
|
|
68
|
+
}
|
|
69
|
+
return template;
|
|
70
|
+
}
|
|
71
|
+
/** The standard descriptors, for an `upload` object without `requests` (older answers). */
|
|
72
|
+
function defaultUploadRequests(upload) {
|
|
73
|
+
const edge = `${upload.edge_base_url.replace(/\/+$/, "")}/v1/uploads`;
|
|
74
|
+
const auth = { Authorization: `Bearer ${upload.upload_token}` };
|
|
75
|
+
const json = { ...auth, "Content-Type": "application/json" };
|
|
50
76
|
return {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
77
|
+
start: { method: "POST", url: `${edge}/start`, headers: auth, body: null, returns: ["uploadId"], description: "" },
|
|
78
|
+
part: {
|
|
79
|
+
method: "PUT",
|
|
80
|
+
url: `${edge}/parts/{part_number}?uploadId={upload_id}`,
|
|
81
|
+
headers: { ...auth, "Content-Length": "{part_length}" },
|
|
82
|
+
body: null,
|
|
83
|
+
returns: ["partNumber", "etag"],
|
|
84
|
+
description: ""
|
|
85
|
+
},
|
|
86
|
+
complete: {
|
|
87
|
+
method: "POST",
|
|
88
|
+
url: `${edge}/complete`,
|
|
89
|
+
headers: json,
|
|
90
|
+
body: { uploadId: "{upload_id}", parts: [{ partNumber: "{part_number}", etag: "{etag}" }] },
|
|
91
|
+
returns: ["sizeBytes", "etag"],
|
|
92
|
+
description: ""
|
|
93
|
+
},
|
|
94
|
+
abort: { method: "POST", url: `${edge}/abort`, headers: json, body: { uploadId: "{upload_id}" }, returns: [], description: "" }
|
|
58
95
|
};
|
|
59
96
|
}
|
|
60
|
-
const
|
|
97
|
+
const parseJson = (text) => {
|
|
61
98
|
try {
|
|
62
|
-
const parsed = JSON.parse(
|
|
63
|
-
return
|
|
99
|
+
const parsed = JSON.parse(text);
|
|
100
|
+
return isRecord(parsed) ? parsed : {};
|
|
64
101
|
}
|
|
65
102
|
catch {
|
|
66
103
|
return {};
|
|
67
104
|
}
|
|
68
105
|
};
|
|
69
|
-
/**
|
|
70
|
-
function classifyEdgeUploadResponse(
|
|
71
|
-
const body =
|
|
72
|
-
const error =
|
|
106
|
+
/** Turns a non-2xx media host answer (`{"error": {"code", "message"}}`) into a typed upload error. */
|
|
107
|
+
function classifyEdgeUploadResponse(status, bodyText) {
|
|
108
|
+
const body = parseJson(bodyText);
|
|
109
|
+
const error = isRecord(body.error) ? body.error : {};
|
|
73
110
|
const message = typeof error.message === "string" && error.message
|
|
74
111
|
? error.message
|
|
75
|
-
: `
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if (response.status === 413)
|
|
82
|
-
code = "upload/too-large";
|
|
83
|
-
else if (response.status === 401 || response.status === 403)
|
|
84
|
-
code = "upload/unauthorized";
|
|
85
|
-
else if (response.status === 408 || response.status === 429 || response.status >= 500) {
|
|
86
|
-
code = "upload/server";
|
|
87
|
-
retryable = true;
|
|
88
|
-
}
|
|
89
|
-
return new errors_1.DiffioUploadError(code, message, { ...base, retryable });
|
|
112
|
+
: `The media host refused the upload with HTTP ${status}`;
|
|
113
|
+
const code = typeof error.code === "string" && error.code
|
|
114
|
+
? error.code
|
|
115
|
+
: status === 413 ? "payload_too_large" : status === 401 || status === 403 ? "invalid_token" : "upload_failed";
|
|
116
|
+
const retryable = status === 408 || status === 429 || status >= 500;
|
|
117
|
+
return new errors_1.DiffioUploadError({ code, message, status, retryable, body: Object.keys(body).length ? body : bodyText });
|
|
90
118
|
}
|
|
91
|
-
|
|
92
|
-
/** Turns a thrown transport failure into an upload error; caller aborts are final, other failures retryable. */
|
|
93
|
-
function toEdgeUploadError(error) {
|
|
119
|
+
function toUploadError(error, signal) {
|
|
94
120
|
if (error instanceof errors_1.DiffioUploadError)
|
|
95
121
|
return error;
|
|
96
|
-
|
|
97
|
-
|
|
122
|
+
const name = isRecord(error) || error instanceof Error ? error.name : undefined;
|
|
123
|
+
if (signal?.aborted || name === "AbortError") {
|
|
124
|
+
return new errors_1.DiffioUploadError({ code: "canceled", message: "The upload was canceled." });
|
|
98
125
|
}
|
|
99
126
|
const message = error instanceof Error ? error.message : String(error);
|
|
100
|
-
return new errors_1.DiffioUploadError("
|
|
127
|
+
return new errors_1.DiffioUploadError({ code: "network", message: message || "Network error during upload", retryable: true });
|
|
101
128
|
}
|
|
102
|
-
/** Uploads
|
|
103
|
-
async function
|
|
104
|
-
const {
|
|
105
|
-
const
|
|
106
|
-
const concurrency = Math.max(1, options.partConcurrency ??
|
|
107
|
-
const maxAttempts = Math.max(1, options.maxAttempts ??
|
|
108
|
-
|
|
109
|
-
|
|
129
|
+
/** Uploads the bytes through the descriptors and returns the media host's completion receipt. */
|
|
130
|
+
async function uploadToMediaHost(options) {
|
|
131
|
+
const { upload, source, signal } = options;
|
|
132
|
+
const wait = options.sleep ?? ((ms) => (0, retry_1.sleep)(ms, signal));
|
|
133
|
+
const concurrency = Math.max(1, options.partConcurrency ?? DEFAULT_PART_CONCURRENCY);
|
|
134
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
|
|
135
|
+
const timeoutMs = (options.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;
|
|
136
|
+
const requests = upload.requests?.start && upload.requests?.part && upload.requests?.complete
|
|
137
|
+
? upload.requests
|
|
138
|
+
: defaultUploadRequests(upload);
|
|
139
|
+
if (upload.max_bytes && source.sizeBytes > upload.max_bytes) {
|
|
140
|
+
throw new errors_1.DiffioUploadError({
|
|
141
|
+
code: "too_large",
|
|
142
|
+
message: `This file is ${source.sizeBytes} bytes; the upload limit is ${upload.max_bytes} bytes.`
|
|
143
|
+
});
|
|
110
144
|
}
|
|
111
|
-
const
|
|
145
|
+
const send = async (descriptor, vars, body, parts) => {
|
|
146
|
+
const headers = {};
|
|
147
|
+
for (const [name, value] of Object.entries(descriptor.headers ?? {})) {
|
|
148
|
+
// fetch sets Content-Length from the body; browsers refuse to let scripts set it.
|
|
149
|
+
if (name.toLowerCase() === "content-length")
|
|
150
|
+
continue;
|
|
151
|
+
headers[name] = String(fillTemplateString(String(value), vars));
|
|
152
|
+
}
|
|
153
|
+
let requestBody;
|
|
154
|
+
if (body)
|
|
155
|
+
requestBody = body;
|
|
156
|
+
else if (descriptor.body != null)
|
|
157
|
+
requestBody = JSON.stringify(fillTemplate(descriptor.body, vars, parts));
|
|
112
158
|
let response;
|
|
113
159
|
try {
|
|
114
|
-
response = await
|
|
160
|
+
response = await (0, transport_1.fetchWithTimeout)(options.fetch, String(fillTemplateString(descriptor.url, vars)), { method: descriptor.method, headers, body: requestBody }, timeoutMs, signal);
|
|
115
161
|
}
|
|
116
162
|
catch (error) {
|
|
117
|
-
throw
|
|
163
|
+
throw toUploadError(error, signal);
|
|
118
164
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
165
|
+
const text = await response.text().catch(() => "");
|
|
166
|
+
if (!response.ok)
|
|
167
|
+
throw classifyEdgeUploadResponse(response.status, text);
|
|
168
|
+
return parseJson(text);
|
|
122
169
|
};
|
|
123
|
-
// Set by the first part that fails for good; the other lanes then stop instead of retrying.
|
|
124
170
|
let fatalError = null;
|
|
125
|
-
|
|
126
|
-
// multipart upload, and the edge answers a repeated complete from the stored object.
|
|
127
|
-
const sendWithRetries = async (describe, readResult) => {
|
|
171
|
+
const withRetries = async (run) => {
|
|
128
172
|
for (let attempt = 1;; attempt += 1) {
|
|
129
173
|
try {
|
|
130
|
-
return
|
|
174
|
+
return await run();
|
|
131
175
|
}
|
|
132
176
|
catch (error) {
|
|
133
|
-
const uploadError =
|
|
177
|
+
const uploadError = toUploadError(error, signal);
|
|
134
178
|
if (fatalError || !uploadError.retryable || attempt >= maxAttempts)
|
|
135
179
|
throw fatalError ?? uploadError;
|
|
136
|
-
await
|
|
180
|
+
await wait(resolveEdgeUploadRetryDelayMs(attempt + 1));
|
|
137
181
|
}
|
|
138
182
|
}
|
|
139
183
|
};
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
body
|
|
144
|
-
contentType: "application/json"
|
|
145
|
-
});
|
|
146
|
-
const started = await sendWithRetries(() => jsonRequest("/v1/uploads/start", {}), (body) => {
|
|
184
|
+
// Every step is safe to repeat: a repeated start opens a fresh multipart upload, parts overwrite, and the
|
|
185
|
+
// media host answers a repeated complete from the stored object.
|
|
186
|
+
const started = await withRetries(async () => {
|
|
187
|
+
const body = await send(requests.start, {}, undefined);
|
|
147
188
|
if (typeof body.uploadId !== "string" || !body.uploadId) {
|
|
148
|
-
throw new errors_1.DiffioUploadError("
|
|
189
|
+
throw new errors_1.DiffioUploadError({ code: "invalid_response", message: "The media host did not return an uploadId." });
|
|
149
190
|
}
|
|
150
|
-
|
|
151
|
-
body.partSizeBytes > 0
|
|
152
|
-
? body.partSizeBytes
|
|
153
|
-
: session.partSizeBytes;
|
|
154
|
-
return { uploadId: body.uploadId, partSizeBytes };
|
|
191
|
+
return body;
|
|
155
192
|
});
|
|
156
|
-
const
|
|
157
|
-
const
|
|
158
|
-
|
|
193
|
+
const uploadId = started.uploadId;
|
|
194
|
+
const partSize = typeof started.partSizeBytes === "number" && Number.isSafeInteger(started.partSizeBytes) &&
|
|
195
|
+
started.partSizeBytes > 0
|
|
196
|
+
? started.partSizeBytes
|
|
197
|
+
: upload.part_size_bytes;
|
|
198
|
+
const plan = planEdgeUploadParts(source.sizeBytes, partSize);
|
|
199
|
+
const pending = [...plan];
|
|
159
200
|
const receipts = [];
|
|
201
|
+
let bytesSent = 0;
|
|
160
202
|
const uploadPart = async (part) => {
|
|
161
203
|
let bytes = null;
|
|
162
|
-
const
|
|
204
|
+
const etag = await withRetries(async () => {
|
|
163
205
|
if (fatalError)
|
|
164
206
|
throw fatalError;
|
|
165
|
-
bytes = bytes ?? await
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
url: `${session.edgeBaseUrl}/v1/uploads/parts/${part.partNumber}?uploadId=${encodeURIComponent(uploadId)}`,
|
|
169
|
-
body: bytes,
|
|
170
|
-
contentType: "application/octet-stream"
|
|
171
|
-
};
|
|
172
|
-
}, (body) => {
|
|
207
|
+
bytes = bytes ?? await source.read(part.startByte, part.endByte);
|
|
208
|
+
const vars = { part_number: part.partNumber, upload_id: uploadId, part_length: bytes.byteLength };
|
|
209
|
+
const body = await send(requests.part, vars, bytes);
|
|
173
210
|
if (typeof body.etag !== "string" || !body.etag) {
|
|
174
|
-
throw new errors_1.DiffioUploadError("
|
|
211
|
+
throw new errors_1.DiffioUploadError({ code: "invalid_response", message: `Part ${part.partNumber} returned no etag.` });
|
|
175
212
|
}
|
|
176
|
-
return
|
|
213
|
+
return body.etag;
|
|
214
|
+
});
|
|
215
|
+
receipts.push({ partNumber: part.partNumber, etag });
|
|
216
|
+
bytesSent += part.endByte - part.startByte;
|
|
217
|
+
options.onProgress?.({
|
|
218
|
+
bytes_sent: bytesSent,
|
|
219
|
+
bytes_total: source.sizeBytes,
|
|
220
|
+
parts_done: receipts.length,
|
|
221
|
+
parts_total: plan.length
|
|
177
222
|
});
|
|
178
|
-
receipts.push(receipt);
|
|
179
223
|
};
|
|
180
|
-
const
|
|
224
|
+
const lane = async () => {
|
|
181
225
|
while (pending.length > 0 && !fatalError) {
|
|
182
226
|
const part = pending.shift();
|
|
183
227
|
if (!part)
|
|
@@ -186,28 +230,29 @@ async function uploadProjectMediaToEdge(options) {
|
|
|
186
230
|
await uploadPart(part);
|
|
187
231
|
}
|
|
188
232
|
catch (error) {
|
|
189
|
-
fatalError = fatalError ??
|
|
233
|
+
fatalError = fatalError ?? toUploadError(error, signal);
|
|
190
234
|
throw fatalError;
|
|
191
235
|
}
|
|
192
236
|
}
|
|
193
237
|
};
|
|
194
|
-
const
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
238
|
+
const results = await Promise.allSettled(Array.from({ length: Math.min(concurrency, plan.length) }, lane));
|
|
239
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
240
|
+
if (failed) {
|
|
241
|
+
const uploadError = fatalError ?? toUploadError(failed.reason, signal);
|
|
242
|
+
if (requests.abort) {
|
|
243
|
+
// Release the stored parts; a failure here never hides the transfer error.
|
|
244
|
+
await send(requests.abort, { upload_id: uploadId }, undefined).catch(() => undefined);
|
|
245
|
+
}
|
|
201
246
|
throw uploadError;
|
|
202
247
|
}
|
|
203
248
|
receipts.sort((left, right) => left.partNumber - right.partNumber);
|
|
204
|
-
const completion = await
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
249
|
+
const completion = await withRetries(() => send(requests.complete, { upload_id: uploadId }, undefined, receipts));
|
|
250
|
+
const sizeBytes = typeof completion.sizeBytes === "number" ? completion.sizeBytes : source.sizeBytes;
|
|
251
|
+
if (sizeBytes !== source.sizeBytes) {
|
|
252
|
+
throw new errors_1.DiffioUploadError({
|
|
253
|
+
code: "invalid_response",
|
|
254
|
+
message: `The media host stored ${sizeBytes} bytes but the file has ${source.sizeBytes} bytes.`
|
|
255
|
+
});
|
|
211
256
|
}
|
|
212
|
-
return completion;
|
|
257
|
+
return { sizeBytes, etag: typeof completion.etag === "string" ? completion.etag : "" };
|
|
213
258
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { UploadSource } from "./edgeUpload";
|
|
2
|
+
export type FileInput = string | Blob | Uint8Array | ArrayBuffer | ArrayBufferView;
|
|
3
|
+
export interface ResolvedFile {
|
|
4
|
+
source: UploadSource;
|
|
5
|
+
/** Base name from the path or File, when there is one. */
|
|
6
|
+
file_name: string | null;
|
|
7
|
+
/** Type from the Blob, when it has one. */
|
|
8
|
+
content_type: string | null;
|
|
9
|
+
}
|
|
10
|
+
/** Opens a file input for reading parts. */
|
|
11
|
+
export declare function resolveFileInput(file: FileInput): Promise<ResolvedFile>;
|
|
12
|
+
/** Guesses a media type from a file name's extension; null when unknown. */
|
|
13
|
+
export declare function guessContentType(fileName: string): string | null;
|
|
14
|
+
/** Writes a fetch response body to a file in Node, streaming it; returns the bytes written. */
|
|
15
|
+
export declare function writeResponseToFile(response: Response, filePath: string): Promise<number>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Turns what callers pass as "a file" into an UploadSource, and writes downloads to disk in Node.
|
|
3
|
+
// Accepted: a file path (Node only), a Blob or File (browsers and Node 18+), a Uint8Array / Buffer,
|
|
4
|
+
// an ArrayBuffer, or an ArrayBufferView.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.resolveFileInput = resolveFileInput;
|
|
7
|
+
exports.guessContentType = guessContentType;
|
|
8
|
+
exports.writeResponseToFile = writeResponseToFile;
|
|
9
|
+
const errors_1 = require("../errors");
|
|
10
|
+
const node_1 = require("./node");
|
|
11
|
+
function nodeModule(id) {
|
|
12
|
+
const loaded = (0, node_1.nodeRequire)(id);
|
|
13
|
+
if (!loaded)
|
|
14
|
+
throw new errors_1.DiffioError("File paths work only in Node; pass a Blob, File or bytes instead.");
|
|
15
|
+
return loaded;
|
|
16
|
+
}
|
|
17
|
+
const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob ||
|
|
18
|
+
(Boolean(value) && typeof value === "object" && typeof value.arrayBuffer === "function" &&
|
|
19
|
+
typeof value.slice === "function" && typeof value.size === "number");
|
|
20
|
+
/** Opens a file input for reading parts. */
|
|
21
|
+
async function resolveFileInput(file) {
|
|
22
|
+
if (typeof file === "string") {
|
|
23
|
+
if (!file)
|
|
24
|
+
throw new errors_1.DiffioError("file is required");
|
|
25
|
+
const fs = nodeModule("node:fs/promises");
|
|
26
|
+
const path = nodeModule("node:path");
|
|
27
|
+
const handle = await fs.open(file, "r");
|
|
28
|
+
const { size } = await handle.stat();
|
|
29
|
+
return {
|
|
30
|
+
file_name: path.basename(file),
|
|
31
|
+
content_type: null,
|
|
32
|
+
source: {
|
|
33
|
+
sizeBytes: size,
|
|
34
|
+
async read(start, end) {
|
|
35
|
+
const length = end - start;
|
|
36
|
+
const buffer = new Uint8Array(length);
|
|
37
|
+
let offset = 0;
|
|
38
|
+
while (offset < length) {
|
|
39
|
+
const { bytesRead } = await handle.read(buffer, offset, length - offset, start + offset);
|
|
40
|
+
if (bytesRead === 0)
|
|
41
|
+
throw new errors_1.DiffioError("The file became shorter while it was uploading.");
|
|
42
|
+
offset += bytesRead;
|
|
43
|
+
}
|
|
44
|
+
return buffer;
|
|
45
|
+
},
|
|
46
|
+
close: () => handle.close()
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (isBlob(file)) {
|
|
51
|
+
const name = file.name;
|
|
52
|
+
return {
|
|
53
|
+
file_name: typeof name === "string" && name ? name : null,
|
|
54
|
+
content_type: file.type || null,
|
|
55
|
+
source: {
|
|
56
|
+
sizeBytes: file.size,
|
|
57
|
+
read: async (start, end) => new Uint8Array(await file.slice(start, end).arrayBuffer())
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
let bytes;
|
|
62
|
+
if (file instanceof Uint8Array)
|
|
63
|
+
bytes = file;
|
|
64
|
+
else if (file instanceof ArrayBuffer)
|
|
65
|
+
bytes = new Uint8Array(file);
|
|
66
|
+
else if (ArrayBuffer.isView(file))
|
|
67
|
+
bytes = new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
|
|
68
|
+
else
|
|
69
|
+
throw new errors_1.DiffioError("file must be a path, Blob, File, Uint8Array, Buffer or ArrayBuffer");
|
|
70
|
+
return {
|
|
71
|
+
file_name: null,
|
|
72
|
+
content_type: null,
|
|
73
|
+
source: { sizeBytes: bytes.byteLength, read: async (start, end) => bytes.subarray(start, end) }
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Media types for the extensions the API accepts (api_projects.py); others are left to the API. */
|
|
77
|
+
const MEDIA_TYPES = {
|
|
78
|
+
"3g2": "video/3gpp2", "3gp": "video/3gpp", "3gpp": "video/3gpp", aac: "audio/aac", aif: "audio/aiff",
|
|
79
|
+
aiff: "audio/aiff", amr: "audio/amr", au: "audio/basic", avi: "video/x-msvideo", caf: "audio/x-caf",
|
|
80
|
+
flac: "audio/flac", m4a: "audio/mp4", m4b: "audio/mp4", m4v: "video/mp4", mka: "audio/x-matroska",
|
|
81
|
+
mkv: "video/x-matroska", mov: "video/quicktime", mp2: "audio/mpeg", mp3: "audio/mpeg", mp4: "video/mp4",
|
|
82
|
+
mpeg: "video/mpeg", mpg: "video/mpeg", oga: "audio/ogg", ogg: "audio/ogg", ogv: "video/ogg", opus: "audio/opus",
|
|
83
|
+
wav: "audio/wav", weba: "audio/webm", webm: "video/webm", wma: "audio/x-ms-wma", wmv: "video/x-ms-wmv"
|
|
84
|
+
};
|
|
85
|
+
/** Guesses a media type from a file name's extension; null when unknown. */
|
|
86
|
+
function guessContentType(fileName) {
|
|
87
|
+
const match = /\.([A-Za-z0-9]+)$/.exec(fileName.trim());
|
|
88
|
+
return match ? MEDIA_TYPES[match[1].toLowerCase()] ?? null : null;
|
|
89
|
+
}
|
|
90
|
+
/** Writes a fetch response body to a file in Node, streaming it; returns the bytes written. */
|
|
91
|
+
async function writeResponseToFile(response, filePath) {
|
|
92
|
+
const fs = nodeModule("node:fs");
|
|
93
|
+
const path = nodeModule("node:path");
|
|
94
|
+
const dir = path.dirname(filePath);
|
|
95
|
+
if (dir)
|
|
96
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
97
|
+
const partial = `${filePath}.part`;
|
|
98
|
+
const stream = fs.createWriteStream(partial);
|
|
99
|
+
let written = 0;
|
|
100
|
+
try {
|
|
101
|
+
if (response.body) {
|
|
102
|
+
const reader = response.body.getReader();
|
|
103
|
+
for (;;) {
|
|
104
|
+
const { done, value } = await reader.read();
|
|
105
|
+
if (done)
|
|
106
|
+
break;
|
|
107
|
+
written += value.byteLength;
|
|
108
|
+
if (!stream.write(value))
|
|
109
|
+
await new Promise((resolve) => stream.once("drain", () => resolve()));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
await new Promise((resolve, reject) => stream.end((error) => (error ? reject(error) : resolve())));
|
|
113
|
+
await fs.promises.rename(partial, filePath);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
stream.destroy();
|
|
117
|
+
await fs.promises.rm(partial, { force: true }).catch(() => undefined);
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
return written;
|
|
121
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** True in Node (not in browsers, even with a `process` shim). */
|
|
2
|
+
export declare const isNode: () => boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Loads a Node built-in. The id is a variable so browser bundlers do not try to bundle Node modules; the
|
|
5
|
+
* SDK only calls this on Node code paths (file paths, node:crypto).
|
|
6
|
+
*/
|
|
7
|
+
export declare function nodeRequire<T>(id: string): T | undefined;
|