@bytescale/sdk 1.5.0 → 3.0.0-alpha.10

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 CHANGED
@@ -1,67 +1,254 @@
1
- # Bytescale JavaScript SDK
2
-
3
- The Bytescale JavaScript SDK allows you to quickly integrate your application with [Bytescale](https://www.bytescale.com).
4
-
5
- Effortlessly upload, optimize, transform, and host your digital media assets.
1
+ <h1 align="center">
2
+ <a href="https://www.bytescale.com/docs/sdks/javascript">
3
+ <img alt="Bytescale JavaScript SDK" width="557" height="67" src="https://raw.githubusercontent.com/bytescale/bytescale-javascript-sdk/main/.github/assets/bytescale-javascript-sdk.svg">
4
+ </a>
5
+ </h1>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@bytescale/sdk">
9
+ <img src="https://img.shields.io/badge/%40bytescale%2Fsdk-npm-4ba0f6" />
10
+ </a>
11
+
12
+ <a href="https://github.com/bytescale/bytescale-javascript-sdk/actions/workflows/ci.yml">
13
+ <img src="https://img.shields.io/badge/build-passing-4ba0f6" />
14
+ </a>
15
+
16
+ <a href="https://github.com/bytescale/bytescale-javascript-sdk/">
17
+ <img src="https://img.shields.io/badge/gzipped-9%20kb-4ba0f6" />
18
+ </a>
19
+
20
+ <a href="https://www.npmjs.com/package/@bytescale/sdk">
21
+ <img src="https://img.shields.io/npm/dt/upload-js?color=%234ba0f6" />
22
+ </a>
23
+ <br/>
24
+
25
+ <a href="https://www.npmjs.com/package/@bytescale/sdk">
26
+ <img src="https://img.shields.io/badge/TypeScript-included-4ba0f6" />
27
+ </a>
28
+
29
+ <a href="https://github.com/bytescale/bytescale-javascript-sdk/actions/workflows/ci.yml">
30
+ <img src="https://img.shields.io/npms-io/maintenance-score/upload-js?color=4ba0f6" />
31
+ </a>
32
+
33
+ <a target="_blank" href="https://twitter.com/intent/tweet?text=This%20was%20a%20great%20find...%0A%0Ahttps%3A%2F%2Fgithub.com%2Fbytescale%2Fbytescale-javascript-sdk">
34
+ <img alt="Twitter URL" src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fbytescale%2Fbytescale-javascript-sdk" />
35
+ </a>
36
+
37
+ </p>
38
+
39
+ <hr/>
40
+
41
+ <p align="center">
42
+ <b>Bytescale is the developer platform for images, video, and audio.</b>
43
+ <br />
44
+ <br />
45
+ Use the Bytescale JavaScript SDK to upload, transform, and serve files at scale.
46
+ <br />
47
+ <br />
48
+ <a href="https://www.bytescale.com/docs/sdks/javascript" rel="nofollow"><b>Full SDK Documentation</b></a> • <a href="https://www.bytescale.com/docs/upload-widget" rel="nofollow">Upload Widget</a> • <a href="https://www.bytescale.com/docs/media-processing-apis" rel="nofollow">Media Processing APIs</a> • <a href="https://www.bytescale.com/docs/storage/sources" rel="nofollow">Storage</a> • <a href="https://www.bytescale.com/docs/cdn" rel="nofollow">CDN</a>
49
+ </p>
50
+
51
+ <hr/>
6
52
 
7
53
  ## Installation
8
54
 
55
+ #### For Node.js:
56
+
9
57
  ```bash
10
- npm install @bytescale/sdk
58
+ npm install @bytescale/sdk node-fetch
11
59
  ```
12
60
 
13
- Additional step for Node.js:
61
+ #### For Browsers:
14
62
 
15
63
  ```bash
16
- npm install node-fetch
64
+ npm install @bytescale/sdk
17
65
  ```
18
66
 
19
- ## Full Documentation
67
+ Or:
20
68
 
21
- **[Bytescale JavaScript SDK Full Documentation »](https://www.bytescale.com/docs/sdks/javascript)**
69
+ ```html
70
+ <script src="https://js.bytescale.com/sdk/v3"></script>
71
+ ```
22
72
 
23
- ## Quick Guide
73
+ ## Uploading Files
24
74
 
25
- - [Upload a File](#upload-a-file)
26
- - [Download a File](#download-a-file)
27
- - [Process a File](#process-a-file)
28
- - [Get File Details](#get-file-details)
29
- - [List Folder](#list-folder)
30
- - **[See All Methods »](https://www.bytescale.com/docs/sdks/javascript)**
75
+ This library is isomorphic, which means you can upload files from Node.js, or the browser, or both.
31
76
 
32
- ### Upload a File
77
+ #### From Node.js:
33
78
 
34
79
  ```javascript
35
80
  import * as Bytescale from "@bytescale/sdk";
36
- import fetch from "node-fetch"; // Node.js only.
81
+ import fetch from "node-fetch";
37
82
 
38
83
  const uploadManager = new Bytescale.UploadManager({
39
- fetchApi: fetch, // 'fetch as any' for TypeScript
40
- apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx"
84
+ fetchApi: fetch, // or 'fetch as any' (please note: you must use 'node-fetch' as errors can occur with other implementations)
85
+ apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
41
86
  });
42
87
 
43
88
  uploadManager
44
89
  .upload({
45
- accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
90
+ // ---------
91
+ // Required:
92
+ // ---------
93
+
94
+ // Your account ID (e.g. "W142hJk")
95
+ accountId: "YOUR_ACCOUNT_ID",
96
+
46
97
  // Supported types for 'data' field:
47
98
  // - String
48
- // - Blob
49
- // - File (i.e. from a DOM file input element)
50
99
  // - Buffer
51
100
  // - ReadableStream (Node.js), e.g. fs.createReadStream("file.txt")
52
- data: "Example Data"
101
+ data: "Hello World",
102
+
103
+ // ---------
104
+ // Optional:
105
+ // ---------
106
+
107
+ // Required if 'data' is a stream.
108
+ // size: 5098, // e.g. fs.statSync("file.txt").size
109
+
110
+ // Required if 'data' is a stream, buffer, or string.
111
+ mime: "text/plain",
112
+
113
+ // Required if 'data' is a stream, buffer, or string.
114
+ originalFileName: "my_file.txt"
115
+
116
+ // Controls multipart upload concurrency. Ignored if 'data' is a stream.
117
+ // maxConcurrentUploadParts: 4,
118
+
119
+ // Up to 2KB of arbitrary JSON.
120
+ // metadata: {
121
+ // productId: 60891
122
+ // },
123
+
124
+ // Up to 25 tags per file.
125
+ // tags: [
126
+ // "example_tag"
127
+ // ],
128
+
129
+ // About file paths:
130
+ // - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
131
+ // - You can override the API key's file upload path by specifying a path below.
132
+ // - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables
133
+ // path: {
134
+ // folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
135
+ // fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
136
+ // },
137
+
138
+ // Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
139
+ // cancellationToken: {
140
+ // isCancelled: false
141
+ // }
53
142
  })
54
143
  .then(
55
- uploadedFile => console.log(uploadedFile),
56
- error => console.error(error)
144
+ ({ fileUrl, filePath }) => {
145
+ // --------------------------------------------
146
+ // File successfully uploaded!
147
+ // --------------------------------------------
148
+ // The 'filePath' uniquely identifies the file,
149
+ // and is what you should save to your DB.
150
+ // --------------------------------------------
151
+ console.log(`File uploaded to: ${fileUrl}`);
152
+ },
153
+ error => console.error(`Error: ${error.message}`, error)
57
154
  );
58
155
  ```
59
156
 
60
- ### Download a File
157
+ #### From the Browser:
158
+
159
+ ```html
160
+ <html>
161
+ <head>
162
+ <script src="https://js.bytescale.com/sdk/v3"></script>
163
+ <script>
164
+ // import * as Bytescale from "@bytescale/sdk"
165
+ const uploadManager = new Bytescale.UploadManager({
166
+ apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
167
+ });
168
+
169
+ const onFileSelected = async event => {
170
+ const file = event.target.files[0];
171
+
172
+ try {
173
+ const { fileUrl, filePath } = await uploadManager.upload({
174
+ // ---------
175
+ // Required:
176
+ // ---------
177
+
178
+ // Your account ID (e.g. "W142hJk")
179
+ accountId: "YOUR_ACCOUNT_ID",
180
+
181
+ // Supported types for 'data' field:
182
+ // - String
183
+ // - Blob
184
+ // - File (i.e. from a DOM file input element)
185
+ data: file
186
+
187
+ // ---------
188
+ // Optional:
189
+ // ---------
190
+
191
+ // Required if 'data' is a stream. (Not required for DOM file inputs, blobs, buffers, or strings.)
192
+ // size: 5098, // e.g. fs.statSync("file.txt").size
193
+
194
+ // Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
195
+ // mime: "application/octet-stream",
196
+
197
+ // Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
198
+ // originalFileName: "my_file.txt",
199
+
200
+ // Controls multipart upload concurrency. Ignored if 'data' is a stream.
201
+ // maxConcurrentUploadParts: 4,
202
+
203
+ // Up to 2KB of arbitrary JSON.
204
+ // metadata: {
205
+ // productId: 60891
206
+ // },
207
+
208
+ // Up to 25 tags per file.
209
+ // tags: [
210
+ // "example_tag"
211
+ // ],
212
+
213
+ // About file paths:
214
+ // - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
215
+ // - You can override the API key's file upload path by specifying a path below.
216
+ // - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables
217
+ // path: {
218
+ // folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
219
+ // fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
220
+ // },
221
+
222
+ // Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
223
+ // cancellationToken: {
224
+ // isCancelled: false
225
+ // }
226
+ });
227
+
228
+ // --------------------------------------------
229
+ // File successfully uploaded!
230
+ // --------------------------------------------
231
+ // The 'filePath' uniquely identifies the file,
232
+ // and is what you should save to your API.
233
+ // --------------------------------------------
234
+ alert(`File uploaded:\n${fileUrl}`);
235
+ } catch (e) {
236
+ alert(`Error:\n${e.message}`);
237
+ }
238
+ };
239
+ </script>
240
+ </head>
241
+ <body>
242
+ <input type="file" onchange="onFileSelected(event)" />
243
+ </body>
244
+ </html>
245
+ ```
246
+
247
+ ## Downloading Files
61
248
 
62
249
  ```javascript
63
250
  import * as Bytescale from "@bytescale/sdk";
64
- import fetch from "node-fetch"; // Node.js only.
251
+ import fetch from "node-fetch"; // Only required for Node.js
65
252
 
66
253
  const fileApi = new Bytescale.FileApi({
67
254
  fetchApi: fetch, // 'fetch as any' for TypeScript
@@ -80,13 +267,13 @@ fileApi
80
267
  );
81
268
  ```
82
269
 
83
- **Note:** you can also download files using: `https://upcdn.io/{accountId}/raw/{filePath}`
270
+ Use the [`UrlBuilder`](#urlbuilder) to get a URL to your file (if you need a URL instead of downloading the file).
84
271
 
85
- ### Process a File
272
+ ## Processing Files
86
273
 
87
274
  ```javascript
88
275
  import * as Bytescale from "@bytescale/sdk";
89
- import fetch from "node-fetch"; // Node.js only.
276
+ import fetch from "node-fetch"; // Only required for Node.js
90
277
 
91
278
  const fileApi = new Bytescale.FileApi({
92
279
  fetchApi: fetch, // 'fetch as any' for TypeScript
@@ -97,7 +284,13 @@ fileApi
97
284
  .processFile({
98
285
  accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
99
286
  filePath: "/uploads/2022/12/25/image.jpg",
100
- transformation: "thumbnail" // Create transformations here: https://www.bytescale.com/dashboard/transformations
287
+
288
+ // See: https://www.bytescale.com/docs/image-processing-api
289
+ transformation: "image",
290
+ transformationParams: {
291
+ w: 800,
292
+ h: 600
293
+ }
101
294
  })
102
295
  .then(response => response.stream()) // .text() | .json() | .blob() | .stream()
103
296
  .then(
@@ -115,13 +308,13 @@ fileApi
115
308
  );
116
309
  ```
117
310
 
118
- **Note:** you can also process files using: `https://upcdn.io/{accountId}/{transformation}/{filePath}`
311
+ Use the [`UrlBuilder`](#urlbuilder) to get a URL to your file (if you need a URL instead of downloading the file).
119
312
 
120
- ### Get File Details
313
+ ## Get File Details
121
314
 
122
315
  ```javascript
123
316
  import * as Bytescale from "@bytescale/sdk";
124
- import fetch from "node-fetch"; // Node.js only.
317
+ import fetch from "node-fetch"; // Only required for Node.js
125
318
 
126
319
  const fileApi = new Bytescale.FileApi({
127
320
  fetchApi: fetch, // 'fetch as any' for TypeScript
@@ -139,11 +332,11 @@ fileApi
139
332
  );
140
333
  ```
141
334
 
142
- ### List Folder
335
+ ## Listing Folders
143
336
 
144
337
  ```javascript
145
338
  import * as Bytescale from "@bytescale/sdk";
146
- import fetch from "node-fetch"; // Node.js only.
339
+ import fetch from "node-fetch"; // Only required for Node.js
147
340
 
148
341
  const folderApi = new Bytescale.FolderApi({
149
342
  fetchApi: fetch, // 'fetch as any' for TypeScript
@@ -163,6 +356,152 @@ folderApi
163
356
  );
164
357
  ```
165
358
 
359
+ ## Authorization
360
+
361
+ The Bytescale JavaScript SDK supports two types of authorization:
362
+
363
+ ### API Keys
364
+
365
+ The Bytescale JavaScript SDK automatically adds the `apiKey` from the constructor to the `Authorization` header for all requests made via the SDK.
366
+
367
+ With API key auth, the requester has access to the resources available to the API key:
368
+
369
+ - Secret API keys (`secret_***`) have access to all API endpoints.
370
+
371
+ - Public API keys (`public_***`) have access to file upload, file download, and file listing API endpoints. (File listing is disabled by default. This can be changed in the API key's settings.)
372
+
373
+ Each Public API Key and Secret API Key can have its read/write access limited to a subset of files/folders.
374
+
375
+ ### JWT Cookies
376
+
377
+ JWT cookies are optional.
378
+
379
+ With JWT cookies, the user can download private files directly via URL, as authorization is performed implicitly via a session cookie. This allows the browser to display private files in `<img>` and `<video>` elements.
380
+
381
+ With JWT cookies, the user can also perform API requests (e.g. file uploads) granted by the [JWT's payload](https://www.bytescale.com/docs/types/BytescaleJwt). This is because the Bytescale JavaScript SDK automatically injects the user's JWT into the `authorization-token` request header for all API requests, assuming the `AuthManager.beginAuthSession` method has been called.
382
+
383
+ _Note: when using JWT cookies to download files, the `?auth=true` query parameter must be added to the URL._
384
+
385
+ [Learn more about using JWT cookies »](https://www.bytescale.com/docs/authorization#jwt-cookie)
386
+
387
+ ## UrlBuilder
388
+
389
+ Use the `UrlBuilder` to make URLs for your uploaded files:
390
+
391
+ ```javascript
392
+ import { UrlBuilder } from "@bytescale/sdk";
393
+ ```
394
+
395
+ #### Raw Files
396
+
397
+ To get the URL for the uploaded image `/example.jpg` in its original form, use the following params:
398
+
399
+ ```javascript
400
+ // Returns: "https://upcdn.io/1234abc/raw/example.jpg"
401
+ new UrlBuilder().url({
402
+ accountId: "1234abc",
403
+ filePath: "/example.jpg"
404
+ });
405
+ ```
406
+
407
+ #### Images
408
+
409
+ To resize the uploaded image `/example.jpg` to 800x600, use the following params:
410
+
411
+ ```javascript
412
+ // Returns: "https://upcdn.io/1234abc/image/example.jpg?w=800&h=600"
413
+ new UrlBuilder().url({
414
+ accountId: "1234abc",
415
+ filePath: "/example.jpg",
416
+ options: {
417
+ transformation: "image",
418
+ transformationParams: {
419
+ w: 800,
420
+ h: 600
421
+ }
422
+ }
423
+ });
424
+ ```
425
+
426
+ [Image Processing API Docs »](https://www.bytescale.com/docs/image-processing-api)
427
+
428
+ #### Videos
429
+
430
+ To transcode the uploaded video `/example.mov` to MP4/H.264 in HD, use the following params:
431
+
432
+ ```javascript
433
+ // Returns: "https://upcdn.io/1234abc/video/example.mov?f=mp4-h264&h=1080"
434
+ new UrlBuilder().url({
435
+ accountId: "1234abc",
436
+ filePath: "/example.mov",
437
+ options: {
438
+ transformation: "video",
439
+ transformationParams: {
440
+ f: "mp4-h264",
441
+ h: 1080
442
+ }
443
+ }
444
+ });
445
+ ```
446
+
447
+ [Video Processing API Docs »](https://www.bytescale.com/docs/video-processing-api)
448
+
449
+ #### Audio
450
+
451
+ To transcode the uploaded audio `/example.wav` to AAC in 192kbps, use the following params:
452
+
453
+ ```javascript
454
+ // Returns: "https://upcdn.io/1234abc/audio/example.wav?f=aac&br=192"
455
+ new UrlBuilder().url({
456
+ accountId: "1234abc",
457
+ filePath: "/example.wav",
458
+ options: {
459
+ transformation: "audio",
460
+ transformationParams: {
461
+ f: "aac",
462
+ br: 192
463
+ }
464
+ }
465
+ });
466
+ ```
467
+
468
+ [Audio Processing API Docs »](https://www.bytescale.com/docs/audio-processing-api)
469
+
470
+ #### Archives
471
+
472
+ To extract the file `document.docx` from the uploaded ZIP file `/example.zip`, use the following params:
473
+
474
+ ```javascript
475
+ // Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx"
476
+ new UrlBuilder().url({
477
+ accountId: "1234abc",
478
+ filePath: "/example.zip",
479
+ options: {
480
+ transformation: "archive",
481
+ transformationParams: {
482
+ m: "extract"
483
+ },
484
+ artifact: "/document.docx"
485
+ }
486
+ });
487
+ ```
488
+
489
+ [Archive Processing API Docs »](https://www.bytescale.com/docs/archive-processing-api)
490
+
491
+ ## 👋 Create your Bytescale Account
492
+
493
+ Bytescale is the best way to serve images, videos, and audio for web apps.
494
+
495
+ **[Create a Bytescale account »](https://www.bytescale.com/get-started)**
496
+
497
+ ## 🙋 Can I use my own storage?
498
+
499
+ Bytescale supports AWS S3, Cloudflare R2, Google Storage, DigitalOcean Spaces, and Bytescale Storage.
500
+
501
+ **[Bytescale Storage Docs »](https://www.bytescale.com/docs/storage/sources)**
502
+
503
+ **[Bytescale JavaScript SDK Docs »](https://www.bytescale.com/docs/sdks/javascript)**
504
+
166
505
  ## License
167
506
 
168
507
  [MIT](LICENSE)