magic-hour 0.36.0 → 0.37.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.
Files changed (66) hide show
  1. package/README.md +202 -10
  2. package/dist/helpers/download.d.ts +5 -0
  3. package/dist/helpers/download.js +88 -0
  4. package/dist/helpers/generate-type.d.ts +51 -0
  5. package/dist/helpers/generate-type.js +2 -0
  6. package/dist/helpers/sleep.d.ts +4 -0
  7. package/dist/helpers/sleep.js +9 -0
  8. package/dist/logger.d.ts +48 -0
  9. package/dist/logger.js +97 -0
  10. package/dist/resources/v1/ai-clothes-changer/resource-client.d.ts +50 -0
  11. package/dist/resources/v1/ai-clothes-changer/resource-client.js +75 -0
  12. package/dist/resources/v1/ai-face-editor/resource-client.d.ts +55 -0
  13. package/dist/resources/v1/ai-face-editor/resource-client.js +85 -0
  14. package/dist/resources/v1/ai-gif-generator/resource-client.d.ts +29 -0
  15. package/dist/resources/v1/ai-gif-generator/resource-client.js +60 -0
  16. package/dist/resources/v1/ai-headshot-generator/resource-client.d.ts +38 -0
  17. package/dist/resources/v1/ai-headshot-generator/resource-client.js +68 -0
  18. package/dist/resources/v1/ai-image-editor/resource-client.d.ts +39 -0
  19. package/dist/resources/v1/ai-image-editor/resource-client.js +69 -0
  20. package/dist/resources/v1/ai-image-generator/resource-client.d.ts +31 -0
  21. package/dist/resources/v1/ai-image-generator/resource-client.js +62 -0
  22. package/dist/resources/v1/ai-image-upscaler/resource-client.d.ts +40 -0
  23. package/dist/resources/v1/ai-image-upscaler/resource-client.js +70 -0
  24. package/dist/resources/v1/ai-meme-generator/resource-client.d.ts +33 -0
  25. package/dist/resources/v1/ai-meme-generator/resource-client.js +64 -0
  26. package/dist/resources/v1/ai-photo-editor/resource-client.d.ts +49 -0
  27. package/dist/resources/v1/ai-photo-editor/resource-client.js +79 -0
  28. package/dist/resources/v1/ai-qr-code-generator/resource-client.d.ts +30 -0
  29. package/dist/resources/v1/ai-qr-code-generator/resource-client.js +61 -0
  30. package/dist/resources/v1/ai-talking-photo/resource-client.d.ts +51 -0
  31. package/dist/resources/v1/ai-talking-photo/resource-client.js +76 -0
  32. package/dist/resources/v1/animation/resource-client.d.ts +61 -0
  33. package/dist/resources/v1/animation/resource-client.js +98 -0
  34. package/dist/resources/v1/auto-subtitle-generator/resource-client.d.ts +41 -0
  35. package/dist/resources/v1/auto-subtitle-generator/resource-client.js +71 -0
  36. package/dist/resources/v1/face-detection/resource-client.d.ts +30 -0
  37. package/dist/resources/v1/face-detection/resource-client.js +75 -0
  38. package/dist/resources/v1/face-swap/resource-client.d.ts +77 -0
  39. package/dist/resources/v1/face-swap/resource-client.js +125 -0
  40. package/dist/resources/v1/face-swap-photo/resource-client.d.ts +73 -0
  41. package/dist/resources/v1/face-swap-photo/resource-client.js +117 -0
  42. package/dist/resources/v1/files/resource-client.d.ts +40 -0
  43. package/dist/resources/v1/files/resource-client.js +236 -0
  44. package/dist/resources/v1/files/resource-client.test.d.ts +1 -0
  45. package/dist/resources/v1/files/resource-client.test.js +422 -0
  46. package/dist/resources/v1/image-background-remover/resource-client.d.ts +49 -0
  47. package/dist/resources/v1/image-background-remover/resource-client.js +82 -0
  48. package/dist/resources/v1/image-projects/resource-client.d.ts +22 -0
  49. package/dist/resources/v1/image-projects/resource-client.js +68 -0
  50. package/dist/resources/v1/image-projects/resource-client.test.d.ts +1 -0
  51. package/dist/resources/v1/image-projects/resource-client.test.js +538 -0
  52. package/dist/resources/v1/image-to-video/resource-client.d.ts +40 -0
  53. package/dist/resources/v1/image-to-video/resource-client.js +70 -0
  54. package/dist/resources/v1/lip-sync/resource-client.d.ts +53 -0
  55. package/dist/resources/v1/lip-sync/resource-client.js +84 -0
  56. package/dist/resources/v1/photo-colorizer/resource-client.d.ts +38 -0
  57. package/dist/resources/v1/photo-colorizer/resource-client.js +68 -0
  58. package/dist/resources/v1/text-to-video/resource-client.d.ts +32 -0
  59. package/dist/resources/v1/text-to-video/resource-client.js +63 -0
  60. package/dist/resources/v1/video-projects/resource-client.d.ts +22 -0
  61. package/dist/resources/v1/video-projects/resource-client.js +68 -0
  62. package/dist/resources/v1/video-projects/resource-client.test.d.ts +1 -0
  63. package/dist/resources/v1/video-projects/resource-client.test.js +713 -0
  64. package/dist/resources/v1/video-to-video/resource-client.d.ts +48 -0
  65. package/dist/resources/v1/video-to-video/resource-client.js +84 -0
  66. package/package.json +15 -11
@@ -1,7 +1,131 @@
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
45
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
46
+ var m = o[Symbol.asyncIterator], i;
47
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
48
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
49
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
50
+ };
2
51
  Object.defineProperty(exports, "__esModule", { value: true });
3
52
  exports.FilesClient = void 0;
53
+ const fs = __importStar(require("fs"));
54
+ const path = __importStar(require("path"));
55
+ const stream_1 = require("stream");
4
56
  const core_1 = require("../../../core");
57
+ /**
58
+ * Determine file type and extension from file path or name.
59
+ */
60
+ function getFileTypeAndExtension(fileName) {
61
+ const ext = path.extname(fileName).toLowerCase().slice(1); // Remove the leading dot
62
+ // Video extensions
63
+ const videoExts = ["mp4", "m4v", "mov", "webm"];
64
+ // Audio extensions
65
+ const audioExts = ["mp3", "mpeg", "wav", "aac", "aiff", "flac"];
66
+ // Image extensions
67
+ const imageExts = [
68
+ "png",
69
+ "jpg",
70
+ "jpeg",
71
+ "webp",
72
+ "avif",
73
+ "jp2",
74
+ "tiff",
75
+ "bmp",
76
+ ];
77
+ let fileType;
78
+ if (videoExts.includes(ext)) {
79
+ fileType = "video";
80
+ }
81
+ else if (audioExts.includes(ext)) {
82
+ fileType = "audio";
83
+ }
84
+ else if (imageExts.includes(ext)) {
85
+ fileType = "image";
86
+ }
87
+ else {
88
+ throw new Error(`Unsupported file extension: ${ext}. ` +
89
+ "Supported types: video (mp4, m4v, mov, webm), " +
90
+ "audio (mp3, mpeg, wav, aac, aiff, flac), " +
91
+ "image (png, jpg, jpeg, webp, avif, jp2, tiff, bmp)");
92
+ }
93
+ return { fileType, extension: ext };
94
+ }
95
+ /**
96
+ * Process different file input types and return standardized information.
97
+ */
98
+ function processFileInput(file) {
99
+ if (typeof file === "string") {
100
+ // File path
101
+ if (!fs.existsSync(file)) {
102
+ throw new Error(`File not found: ${file}`);
103
+ }
104
+ const { fileType, extension } = getFileTypeAndExtension(file);
105
+ return { filePath: file, fileType, extension };
106
+ }
107
+ else if (Buffer.isBuffer(file)) {
108
+ throw new Error("Buffer input requires a file name for extension detection. " +
109
+ "Please use a file path, File object, or stream with a name property.");
110
+ }
111
+ else if (file instanceof stream_1.Readable) {
112
+ // Stream with path property
113
+ const filePath = file.path;
114
+ if (typeof filePath !== "string") {
115
+ throw new Error("Stream must have a 'path' property for extension detection.");
116
+ }
117
+ const { fileType, extension } = getFileTypeAndExtension(filePath);
118
+ return { fileData: file, fileType, extension };
119
+ }
120
+ else if (typeof File !== "undefined" && file instanceof File) {
121
+ // File object (browser)
122
+ const { fileType, extension } = getFileTypeAndExtension(file.name);
123
+ return { fileData: file, fileType, extension };
124
+ }
125
+ else {
126
+ throw new Error("Unsupported file input type");
127
+ }
128
+ }
5
129
  class FilesClient extends core_1.CoreResourceClient {
6
130
  constructor(coreClient, opts) {
7
131
  super(coreClient, opts);
@@ -13,5 +137,117 @@ class FilesClient extends core_1.CoreResourceClient {
13
137
  var _a;
14
138
  return ((_a = this._uploadUrlsLazy) !== null && _a !== void 0 ? _a : (this._uploadUrlsLazy = new (require("./upload-urls").UploadUrlsClient)(this._client, this._opts)));
15
139
  }
140
+ /**
141
+ * Upload a file to Magic Hour's storage.
142
+ *
143
+ * This method uploads a file to Magic Hour's secure cloud storage and returns
144
+ * a file path that can be used as input for other Magic Hour API endpoints.
145
+ * The file type is automatically detected from the file extension.
146
+ *
147
+ * @param file - The file to upload. Can be:
148
+ * - **string**: Path to a local file (e.g., "/path/to/image.jpg")
149
+ * - **Buffer**: File content as buffer (requires extension detection via other means)
150
+ * - **Readable**: Node.js readable stream (must have a 'path' property)
151
+ * - **File**: File object (browser environment)
152
+ *
153
+ * @returns The uploaded file's path in Magic Hour's storage system.
154
+ * This path can be used as input for other API endpoints.
155
+ *
156
+ * @throws {Error} If the specified local file doesn't exist.
157
+ * @throws {Error} If the file type is not supported.
158
+ * @throws {Error} If the upload request fails (network/server errors).
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * import { Client } from "../../../index.js";
163
+ *
164
+ * const client = new Client({ token: process.env.MAGIC_HOUR_API_TOKEN });
165
+ *
166
+ * // Upload from file path
167
+ * const filePath = await client.v1.files.uploadFile("/path/to/your/image.jpg");
168
+ * console.log(`Uploaded file: ${filePath}`);
169
+ *
170
+ * // Use the uploaded file in other API calls
171
+ * const result = await client.v1.aiImageUpscaler.create({
172
+ * assets: { imageFilePath: filePath },
173
+ * style: { upscaleFactor: 2 }
174
+ * });
175
+ * ```
176
+ */
177
+ uploadFile(file) {
178
+ return __awaiter(this, void 0, void 0, function* () {
179
+ var _a, e_1, _b, _c;
180
+ const { filePath, fileData, fileType, extension } = processFileInput(file);
181
+ // Create upload URL
182
+ const response = yield this.uploadUrls.create({
183
+ items: [
184
+ {
185
+ extension,
186
+ type: fileType,
187
+ },
188
+ ],
189
+ });
190
+ if (!response.items || response.items.length === 0) {
191
+ throw new Error("No upload URL was returned from the server");
192
+ }
193
+ const uploadInfo = response.items[0];
194
+ if (!uploadInfo) {
195
+ throw new Error("Upload info is missing from server response");
196
+ }
197
+ // Prepare file content
198
+ let content;
199
+ if (filePath) {
200
+ content = fs.readFileSync(filePath);
201
+ }
202
+ else if (fileData) {
203
+ if (Buffer.isBuffer(fileData)) {
204
+ content = fileData;
205
+ }
206
+ else if (fileData instanceof stream_1.Readable) {
207
+ // For streams, read all data into buffer
208
+ const chunks = [];
209
+ try {
210
+ for (var _d = true, fileData_1 = __asyncValues(fileData), fileData_1_1; fileData_1_1 = yield fileData_1.next(), _a = fileData_1_1.done, !_a; _d = true) {
211
+ _c = fileData_1_1.value;
212
+ _d = false;
213
+ const chunk = _c;
214
+ chunks.push(chunk);
215
+ }
216
+ }
217
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
218
+ finally {
219
+ try {
220
+ if (!_d && !_a && (_b = fileData_1.return)) yield _b.call(fileData_1);
221
+ }
222
+ finally { if (e_1) throw e_1.error; }
223
+ }
224
+ content = Buffer.concat(chunks);
225
+ }
226
+ else if (typeof File !== "undefined" && fileData instanceof File) {
227
+ // File object - convert to buffer
228
+ const arrayBuffer = yield fileData.arrayBuffer();
229
+ content = Buffer.from(arrayBuffer);
230
+ }
231
+ else {
232
+ throw new Error("Unsupported file data type");
233
+ }
234
+ }
235
+ else {
236
+ throw new Error("No file data available");
237
+ }
238
+ // Upload the file
239
+ const fetcherFn = core_1.RUNTIME.type === "node" || typeof fetch !== "function"
240
+ ? require("node-fetch").default
241
+ : fetch;
242
+ const uploadResponse = yield fetcherFn(uploadInfo.uploadUrl, {
243
+ method: "PUT",
244
+ body: content,
245
+ });
246
+ if (!uploadResponse.ok) {
247
+ throw new Error(`Upload failed with status ${uploadResponse.status}: ${uploadResponse.statusText}`);
248
+ }
249
+ return uploadInfo.filePath;
250
+ });
251
+ }
16
252
  }
17
253
  exports.FilesClient = FilesClient;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,422 @@
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ const magic_hour_1 = __importDefault(require("../../../index.js"));
49
+ const fs = __importStar(require("fs"));
50
+ const path = __importStar(require("path"));
51
+ const stream_1 = require("stream");
52
+ const msw_1 = require("msw");
53
+ const node_1 = require("msw/node");
54
+ // Mock fs module
55
+ jest.mock("fs", () => ({
56
+ existsSync: jest.fn(),
57
+ readFileSync: jest.fn(),
58
+ }));
59
+ const mockFs = fs;
60
+ // Create MSW server for mocking API requests
61
+ const server = (0, node_1.setupServer)(
62
+ // Mock upload URLs creation - handle both possible URLs
63
+ msw_1.http.post("https://api.magichour.ai/v1/files/upload-urls", () => {
64
+ return msw_1.HttpResponse.json({
65
+ items: [
66
+ {
67
+ upload_url: "https://storage.example.com/upload?token=abc123",
68
+ file_path: "api-assets/12345/image.jpg",
69
+ expires_at: "2024-12-31T23:59:59Z",
70
+ },
71
+ ],
72
+ });
73
+ }),
74
+ // Mock file upload to storage
75
+ msw_1.http.put("https://storage.example.com/upload", () => {
76
+ return msw_1.HttpResponse.json({ status: 200 });
77
+ }),
78
+ // Handle any other upload URLs that might be generated
79
+ msw_1.http.put("https://example.com/upload", () => {
80
+ return msw_1.HttpResponse.json({ status: 200 });
81
+ }));
82
+ // Mock RUNTIME to ensure we use node-fetch
83
+ jest.mock("magic-hour/core", () => {
84
+ const actual = jest.requireActual("magic-hour/core");
85
+ return Object.assign(Object.assign({}, actual), { RUNTIME: { type: "node" } });
86
+ });
87
+ // Start and stop MSW server
88
+ beforeAll(() => server.listen());
89
+ afterAll(() => server.close());
90
+ afterEach(() => server.resetHandlers());
91
+ describe("FilesClient.uploadFile", () => {
92
+ let client;
93
+ beforeEach(() => {
94
+ client = new magic_hour_1.default({
95
+ token: "API_TOKEN",
96
+ });
97
+ // Reset all mocks
98
+ jest.clearAllMocks();
99
+ // Setup default fs mocks
100
+ mockFs.existsSync.mockReturnValue(true);
101
+ mockFs.readFileSync.mockReturnValue(Buffer.from("mock file content"));
102
+ });
103
+ describe("File type detection", () => {
104
+ // MSW handles the uploadUrls.create call automatically
105
+ test("should detect video file types correctly", () => __awaiter(void 0, void 0, void 0, function* () {
106
+ const videoExtensions = ["mp4", "m4v", "mov", "webm"];
107
+ for (const ext of videoExtensions) {
108
+ const filePath = `/path/to/video.${ext}`;
109
+ // Spy on the uploadUrls.create method to verify it gets called with correct params
110
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
111
+ const result = yield client.v1.files.uploadFile(filePath);
112
+ expect(createSpy).toHaveBeenCalledWith({
113
+ items: [{ extension: ext, type: "video" }],
114
+ });
115
+ expect(result).toBe("api-assets/12345/image.jpg"); // MSW returns this mock value
116
+ createSpy.mockRestore();
117
+ }
118
+ }));
119
+ test("should detect audio file types correctly", () => __awaiter(void 0, void 0, void 0, function* () {
120
+ const audioExtensions = ["mp3", "mpeg", "wav", "aac", "aiff", "flac"];
121
+ for (const ext of audioExtensions) {
122
+ const filePath = `/path/to/audio.${ext}`;
123
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
124
+ const result = yield client.v1.files.uploadFile(filePath);
125
+ expect(createSpy).toHaveBeenCalledWith({
126
+ items: [{ extension: ext, type: "audio" }],
127
+ });
128
+ expect(result).toBe("api-assets/12345/image.jpg");
129
+ createSpy.mockRestore();
130
+ }
131
+ }));
132
+ test("should detect image file types correctly", () => __awaiter(void 0, void 0, void 0, function* () {
133
+ const imageExtensions = [
134
+ "png",
135
+ "jpg",
136
+ "jpeg",
137
+ "webp",
138
+ "avif",
139
+ "jp2",
140
+ "tiff",
141
+ "bmp",
142
+ ];
143
+ for (const ext of imageExtensions) {
144
+ const filePath = `/path/to/image.${ext}`;
145
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
146
+ const result = yield client.v1.files.uploadFile(filePath);
147
+ expect(createSpy).toHaveBeenCalledWith({
148
+ items: [{ extension: ext, type: "image" }],
149
+ });
150
+ expect(result).toBe("api-assets/12345/image.jpg");
151
+ createSpy.mockRestore();
152
+ }
153
+ }));
154
+ test("should handle case-insensitive file extensions", () => __awaiter(void 0, void 0, void 0, function* () {
155
+ const testCases = [
156
+ {
157
+ input: "/path/to/VIDEO.MP4",
158
+ expectedExt: "mp4",
159
+ expectedType: "video",
160
+ },
161
+ {
162
+ input: "/path/to/IMAGE.JPG",
163
+ expectedExt: "jpg",
164
+ expectedType: "image",
165
+ },
166
+ {
167
+ input: "/path/to/AUDIO.WAV",
168
+ expectedExt: "wav",
169
+ expectedType: "audio",
170
+ },
171
+ ];
172
+ for (const { input, expectedExt, expectedType } of testCases) {
173
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
174
+ const result = yield client.v1.files.uploadFile(input);
175
+ expect(createSpy).toHaveBeenCalledWith({
176
+ items: [{ extension: expectedExt, type: expectedType }],
177
+ });
178
+ expect(result).toBe("api-assets/12345/image.jpg");
179
+ createSpy.mockRestore();
180
+ }
181
+ }));
182
+ test("should throw error for unsupported file extensions", () => __awaiter(void 0, void 0, void 0, function* () {
183
+ const unsupportedFiles = [
184
+ "/path/to/file.txt",
185
+ "/path/to/document.pdf",
186
+ "/path/to/archive.zip",
187
+ "/path/to/data.json",
188
+ ];
189
+ for (const filePath of unsupportedFiles) {
190
+ const ext = path.extname(filePath).slice(1).toLowerCase();
191
+ yield expect(client.v1.files.uploadFile(filePath)).rejects.toThrow(`Unsupported file extension: ${ext}`);
192
+ }
193
+ }));
194
+ });
195
+ describe("File input validation", () => {
196
+ const mockUploadResponse = {
197
+ items: [
198
+ {
199
+ uploadUrl: "https://example.com/upload",
200
+ filePath: "uploaded-file.jpg",
201
+ expiresAt: "2024-01-01T00:00:00Z",
202
+ },
203
+ ],
204
+ };
205
+ beforeEach(() => {
206
+ jest
207
+ .spyOn(client.v1.files.uploadUrls, "create")
208
+ .mockResolvedValue(mockUploadResponse);
209
+ });
210
+ test("should validate file exists for string input", () => __awaiter(void 0, void 0, void 0, function* () {
211
+ const filePath = "/path/to/image.jpg";
212
+ mockFs.existsSync.mockReturnValue(true);
213
+ yield client.v1.files.uploadFile(filePath);
214
+ expect(mockFs.existsSync).toHaveBeenCalledWith(filePath);
215
+ }));
216
+ test("should throw error for non-existent file path", () => __awaiter(void 0, void 0, void 0, function* () {
217
+ const filePath = "/nonexistent/file.jpg";
218
+ mockFs.existsSync.mockReturnValue(false);
219
+ yield expect(client.v1.files.uploadFile(filePath)).rejects.toThrow(`File not found: ${filePath}`);
220
+ }));
221
+ test("should reject Buffer input without filename", () => __awaiter(void 0, void 0, void 0, function* () {
222
+ const buffer = Buffer.from("image content");
223
+ yield expect(client.v1.files.uploadFile(buffer)).rejects.toThrow("Buffer input requires a file name for extension detection");
224
+ }));
225
+ test("should validate Readable stream has path property", () => __awaiter(void 0, void 0, void 0, function* () {
226
+ const mockStream = new stream_1.Readable({
227
+ read() {
228
+ this.push(Buffer.from("stream content"));
229
+ this.push(null);
230
+ },
231
+ });
232
+ // Stream without path property should fail
233
+ yield expect(client.v1.files.uploadFile(mockStream)).rejects.toThrow("Stream must have a 'path' property for extension detection");
234
+ }));
235
+ test("should accept Readable stream with path property", () => __awaiter(void 0, void 0, void 0, function* () {
236
+ const mockStream = new stream_1.Readable({
237
+ read() {
238
+ this.push(Buffer.from("stream content"));
239
+ this.push(null);
240
+ },
241
+ });
242
+ mockStream.path = "/path/to/video.mp4";
243
+ const result = yield client.v1.files.uploadFile(mockStream);
244
+ expect(result).toBe("uploaded-file.jpg");
245
+ expect(client.v1.files.uploadUrls.create).toHaveBeenCalledWith({
246
+ items: [{ extension: "mp4", type: "video" }],
247
+ });
248
+ }));
249
+ test.skip("should handle File object in browser-like environment", () => __awaiter(void 0, void 0, void 0, function* () {
250
+ // Skipping this test as File object mocking is complex in Node.js environment
251
+ // This functionality would work in actual browser environments
252
+ }));
253
+ });
254
+ describe("File content processing", () => {
255
+ // MSW handles the uploadUrls.create call automatically
256
+ test("should read file content from file path", () => __awaiter(void 0, void 0, void 0, function* () {
257
+ const filePath = "/path/to/image.jpg";
258
+ const fileContent = Buffer.from("image content");
259
+ mockFs.readFileSync.mockReturnValue(fileContent);
260
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
261
+ const result = yield client.v1.files.uploadFile(filePath);
262
+ expect(mockFs.readFileSync).toHaveBeenCalledWith(filePath);
263
+ expect(createSpy).toHaveBeenCalledWith({
264
+ items: [{ extension: "jpg", type: "image" }],
265
+ });
266
+ expect(result).toBe("api-assets/12345/image.jpg");
267
+ createSpy.mockRestore();
268
+ }));
269
+ test("should process Readable stream content", () => __awaiter(void 0, void 0, void 0, function* () {
270
+ const streamContent = Buffer.from("stream video content");
271
+ const mockStream = new stream_1.Readable({
272
+ read() {
273
+ this.push(streamContent);
274
+ this.push(null);
275
+ },
276
+ });
277
+ mockStream.path = "/path/to/video.mp4";
278
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
279
+ const result = yield client.v1.files.uploadFile(mockStream);
280
+ expect(createSpy).toHaveBeenCalledWith({
281
+ items: [{ extension: "mp4", type: "video" }],
282
+ });
283
+ expect(result).toBe("api-assets/12345/image.jpg");
284
+ createSpy.mockRestore();
285
+ }));
286
+ test("should handle large stream content", () => __awaiter(void 0, void 0, void 0, function* () {
287
+ const largeContent = Buffer.from("a".repeat(1024 * 1024)); // 1MB of content
288
+ const mockStream = new stream_1.Readable({
289
+ read() {
290
+ this.push(largeContent);
291
+ this.push(null);
292
+ },
293
+ });
294
+ mockStream.path = "/path/to/large-video.mp4";
295
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
296
+ const result = yield client.v1.files.uploadFile(mockStream);
297
+ expect(createSpy).toHaveBeenCalledWith({
298
+ items: [{ extension: "mp4", type: "video" }],
299
+ });
300
+ expect(result).toBe("api-assets/12345/image.jpg");
301
+ createSpy.mockRestore();
302
+ }));
303
+ test.skip("should handle File object arrayBuffer conversion", () => __awaiter(void 0, void 0, void 0, function* () {
304
+ // Skipping this test as File object mocking is complex in Node.js environment
305
+ // This functionality would work in actual browser environments
306
+ }));
307
+ });
308
+ describe("Upload process and error handling", () => {
309
+ test("should successfully complete upload process", () => __awaiter(void 0, void 0, void 0, function* () {
310
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
311
+ const result = yield client.v1.files.uploadFile("/path/to/image.jpg");
312
+ expect(result).toBe("api-assets/12345/image.jpg");
313
+ expect(createSpy).toHaveBeenCalledWith({
314
+ items: [{ extension: "jpg", type: "image" }],
315
+ });
316
+ createSpy.mockRestore();
317
+ }));
318
+ test("should handle empty upload URL response", () => __awaiter(void 0, void 0, void 0, function* () {
319
+ const mockResponse = { items: [] };
320
+ jest
321
+ .spyOn(client.v1.files.uploadUrls, "create")
322
+ .mockResolvedValue(mockResponse);
323
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("No upload URL was returned from the server");
324
+ }));
325
+ test("should handle null upload info", () => __awaiter(void 0, void 0, void 0, function* () {
326
+ const mockResponse = { items: [null] };
327
+ jest
328
+ .spyOn(client.v1.files.uploadUrls, "create")
329
+ .mockResolvedValue(mockResponse);
330
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("Upload info is missing from server response");
331
+ }));
332
+ test("should handle upload HTTP failure", () => __awaiter(void 0, void 0, void 0, function* () {
333
+ // Change server behavior for this test
334
+ server.use(msw_1.http.put("https://storage.example.com/upload", () => {
335
+ return msw_1.HttpResponse.json({ error: "Internal Server Error" }, { status: 500 });
336
+ }));
337
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("Upload failed with status 500");
338
+ }));
339
+ test("should handle network errors during upload", () => __awaiter(void 0, void 0, void 0, function* () {
340
+ // Change server behavior for this test to simulate network error
341
+ server.use(msw_1.http.put("https://storage.example.com/upload", () => {
342
+ return msw_1.HttpResponse.error();
343
+ }));
344
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("Network error");
345
+ }));
346
+ test("should handle upload URLs creation failure", () => __awaiter(void 0, void 0, void 0, function* () {
347
+ jest
348
+ .spyOn(client.v1.files.uploadUrls, "create")
349
+ .mockRejectedValue(new Error("API authentication failed"));
350
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("API authentication failed");
351
+ }));
352
+ test("should handle file system read errors", () => __awaiter(void 0, void 0, void 0, function* () {
353
+ mockFs.readFileSync.mockImplementation(() => {
354
+ throw new Error("Permission denied");
355
+ });
356
+ yield expect(client.v1.files.uploadFile("/path/to/image.jpg")).rejects.toThrow("Permission denied");
357
+ }));
358
+ });
359
+ describe("Integration and edge cases", () => {
360
+ test("should handle files with special characters in names", () => __awaiter(void 0, void 0, void 0, function* () {
361
+ const specialFiles = [
362
+ "/path/to/image with spaces.jpg",
363
+ "/path/to/image-with-dashes.png",
364
+ "/path/to/image_with_underscores.webp",
365
+ "/path/to/image.with.dots.mp4",
366
+ "/path/to/123numeric.mp3",
367
+ ];
368
+ const mockResponse = {
369
+ items: [
370
+ {
371
+ uploadUrl: "https://example.com/upload",
372
+ filePath: "uploaded-file.jpg",
373
+ expiresAt: "2024-01-01T00:00:00Z",
374
+ },
375
+ ],
376
+ };
377
+ jest
378
+ .spyOn(client.v1.files.uploadUrls, "create")
379
+ .mockResolvedValue(mockResponse);
380
+ for (const filePath of specialFiles) {
381
+ const ext = path.extname(filePath).slice(1).toLowerCase();
382
+ const expectedType = getFileTypeFromExtension(ext);
383
+ yield client.v1.files.uploadFile(filePath);
384
+ expect(client.v1.files.uploadUrls.create).toHaveBeenCalledWith({
385
+ items: [{ extension: ext, type: expectedType }],
386
+ });
387
+ }
388
+ }));
389
+ test("should handle empty file content", () => __awaiter(void 0, void 0, void 0, function* () {
390
+ mockFs.readFileSync.mockReturnValue(Buffer.from(""));
391
+ const createSpy = jest.spyOn(client.v1.files.uploadUrls, "create");
392
+ const result = yield client.v1.files.uploadFile("/path/to/empty.jpg");
393
+ expect(result).toBe("api-assets/12345/image.jpg");
394
+ expect(createSpy).toHaveBeenCalledWith({
395
+ items: [{ extension: "jpg", type: "image" }],
396
+ });
397
+ createSpy.mockRestore();
398
+ }));
399
+ });
400
+ });
401
+ // Helper function for tests
402
+ function getFileTypeFromExtension(ext) {
403
+ const videoExts = ["mp4", "m4v", "mov", "webm"];
404
+ const audioExts = ["mp3", "mpeg", "wav", "aac", "aiff", "flac"];
405
+ const imageExts = [
406
+ "png",
407
+ "jpg",
408
+ "jpeg",
409
+ "webp",
410
+ "avif",
411
+ "jp2",
412
+ "tiff",
413
+ "bmp",
414
+ ];
415
+ if (videoExts.includes(ext))
416
+ return "video";
417
+ if (audioExts.includes(ext))
418
+ return "audio";
419
+ if (imageExts.includes(ext))
420
+ return "image";
421
+ throw new Error(`Unsupported extension: ${ext}`);
422
+ }