Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

@uppy/transloadit

Package Overview
Dependencies
Maintainers
5
Versions
137
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@uppy/transloadit - npm Package Compare versions

Comparing version 3.5.1 to 3.6.0

src/Assembly.ts

7

CHANGELOG.md
# @uppy/transloadit
## 3.6.0
Released: 2024-03-27
Included in: Uppy v3.24.0
- @uppy/transloadit: migrate to TS (Merlijn Vos / #4987)
## 3.5.0

@@ -4,0 +11,0 @@

27

lib/Assembly.js

@@ -8,2 +8,5 @@ function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }

import fetchWithNetworkError from '@uppy/utils/lib/fetchWithNetworkError';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore untyped
const ASSEMBLY_UPLOADING = 'ASSEMBLY_UPLOADING';

@@ -45,5 +48,2 @@ const ASSEMBLY_EXECUTING = 'ASSEMBLY_EXECUTING';

* to `next`.
*
* @param {object} prev The previous assembly status.
* @param {object} next The new assembly status.
*/

@@ -117,4 +117,2 @@ Object.defineProperty(this, _diffStatus, {

* emitted for status changes, new files, and new results.
*
* @param {object} next The new assembly status object.
*/

@@ -145,7 +143,2 @@ updateStatus(next) {

_classPrivateFieldLooseBase(this, _sse)[_sse].addEventListener('open', () => {
// if server side events works, we don't need websockets anymore (it's just a fallback)
if (this.socket) {
this.socket.disconnect();
this.socket = null;
}
clearInterval(this.pollInterval);

@@ -194,5 +187,3 @@ this.pollInterval = null;

} catch {
_classPrivateFieldLooseBase(this, _onError)[_onError]({
msg: e.data
});
_classPrivateFieldLooseBase(this, _onError)[_onError](new Error(e.data));
}

@@ -205,4 +196,4 @@ // Refetch for updated status code

}
function _onError2(status) {
this.emit('error', Object.assign(new Error(status.msg), status));
function _onError2(assemblyOrError) {
this.emit('error', Object.assign(new Error(assemblyOrError.message), assemblyOrError));
this.close();

@@ -234,2 +225,3 @@ }

const status = await response.json();
// Avoid updating if we closed during this request's lifetime.

@@ -272,4 +264,7 @@ if (this.closed) return;

// Find new uploaded files.
// Only emit if the upload is new (not in prev.uploads).
Object.keys(next.uploads).filter(upload => !has(prev.uploads, upload)).forEach(upload => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore either the types are wrong or the tests are wrong.
// types think next.uploads is an array, but the tests pass an object.
this.emit('upload', next.uploads[upload]);

@@ -276,0 +271,0 @@ });

import ErrorWithCause from '@uppy/utils/lib/ErrorWithCause';
/**

@@ -25,3 +24,2 @@ * Check that Assembly parameters are present and include all required fields.

}
/**

@@ -28,0 +26,0 @@ * Combine Assemblies with the same options into a single Assembly for all the

@@ -5,15 +5,6 @@ function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }

import Emitter from 'component-emitter';
/**
* Track completion of multiple assemblies.
*
* Emits 'assembly-complete' when an assembly completes.
* Emits 'assembly-error' when an assembly fails.
* Exposes a `.promise` property that resolves when all assemblies have
* completed (or failed).
*/
var _assemblyIDs = /*#__PURE__*/_classPrivateFieldLooseKey("assemblyIDs");
var _reject = /*#__PURE__*/_classPrivateFieldLooseKey("reject");
var _remaining = /*#__PURE__*/_classPrivateFieldLooseKey("remaining");
var _resolve = /*#__PURE__*/_classPrivateFieldLooseKey("resolve");
var _reject = /*#__PURE__*/_classPrivateFieldLooseKey("reject");
var _uppy = /*#__PURE__*/_classPrivateFieldLooseKey("uppy");

@@ -28,2 +19,10 @@ var _watching = /*#__PURE__*/_classPrivateFieldLooseKey("watching");

var _addListeners = /*#__PURE__*/_classPrivateFieldLooseKey("addListeners");
/**
* Track completion of multiple assemblies.
*
* Emits 'assembly-complete' when an assembly completes.
* Emits 'assembly-error' when an assembly fails.
* Exposes a `.promise` property that resolves when all assemblies have
* completed (or failed).
*/
class TransloaditAssemblyWatcher extends Emitter {

@@ -51,11 +50,11 @@ constructor(uppy, assemblyIDs) {

});
Object.defineProperty(this, _reject, {
Object.defineProperty(this, _remaining, {
writable: true,
value: void 0
});
Object.defineProperty(this, _remaining, {
Object.defineProperty(this, _resolve, {
writable: true,
value: void 0
});
Object.defineProperty(this, _resolve, {
Object.defineProperty(this, _reject, {
writable: true,

@@ -62,0 +61,0 @@ value: void 0

@@ -6,2 +6,9 @@ function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }

const ASSEMBLIES_ENDPOINT = '/assemblies';
export class AssemblyError extends Error {
constructor(message, details, assembly) {
super(message);
this.details = details;
this.assembly = assembly;
}
}

@@ -17,9 +24,2 @@ /**

constructor(_opts) {
if (_opts === void 0) {
_opts = {};
}
/**
* @param {[RequestInfo | URL, RequestInit]} args
* @returns {Promise<any>}
*/
Object.defineProperty(this, _fetchJSON, {

@@ -64,12 +64,3 @@ value: _fetchJSON2

}
/**
* Create a new assembly.
*
* @param {object} options
* @param {string|object} options.params
* @param {object} options.fields
* @param {string} options.signature
* @param {number} options.expectedFiles
*/
createAssembly(_ref) {
async createAssembly(_ref) {
let {

@@ -87,5 +78,5 @@ params,

Object.keys(fields).forEach(key => {
data.append(key, fields[key]);
data.append(key, String(fields[key]));
});
data.append('num_expected_upload_files', expectedFiles);
data.append('num_expected_upload_files', String(expectedFiles));
const url = new URL(ASSEMBLIES_ENDPOINT, `${this.opts.service}`).href;

@@ -104,7 +95,4 @@ return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {

* Reserve resources for a file in an Assembly. Then addFile can be used later.
*
* @param {object} assembly
* @param {UppyFile} file
*/
reserveFile(assembly, file) {
async reserveFile(assembly, file) {
const size = encodeURIComponent(file.size);

@@ -125,7 +113,4 @@ const url = `${assembly.assembly_ssl_url}/reserve_file?size=${size}`;

* Import a remote file to an Assembly.
*
* @param {object} assembly
* @param {UppyFile} file
*/
addFile(assembly, file) {
async addFile(assembly, file) {
if (!file.uploadURL) {

@@ -153,7 +138,4 @@ return Promise.reject(new Error('File does not have an `uploadURL`.'));

* Update the number of expected files in an already created assembly.
*
* @param {object} assembly
* @param {number} num_expected_upload_files
*/
updateNumberOfFilesInAssembly(assembly, num_expected_upload_files) {
async updateNumberOfFilesInAssembly(assembly, num_expected_upload_files) {
const url = new URL(assembly.assembly_ssl_url);

@@ -179,6 +161,4 @@ url.pathname = '/update_assemblies';

* Cancel a running Assembly.
*
* @param {object} assembly
*/
cancelAssembly(assembly) {
async cancelAssembly(assembly) {
const url = assembly.assembly_ssl_url;

@@ -196,6 +176,4 @@ return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {

* Get the current status for an assembly.
*
* @param {string} url The status endpoint of the assembly.
*/
getAssemblyStatus(url) {
async getAssemblyStatus(url) {
return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {

@@ -208,3 +186,3 @@ headers: _classPrivateFieldLooseBase(this, _headers)[_headers]

}
submitError(err, _temp) {
async submitError(err, _temp) {
let {

@@ -229,34 +207,29 @@ endpoint,

}
function _fetchJSON2() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
async function _fetchJSON2() {
const response = await _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError](...arguments);
if (response.status === 429) {
this.opts.rateLimitedQueue.rateLimit(2000);
return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](...arguments);
}
return _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError](...args).then(response => {
if (response.status === 429) {
this.opts.rateLimitedQueue.rateLimit(2000);
return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](...args);
}
if (!response.ok) {
const serverError = new Error(response.statusText);
serverError.statusCode = response.status;
if (!`${args[0]}`.endsWith(ASSEMBLIES_ENDPOINT)) return Promise.reject(serverError);
if (!response.ok) {
const serverError = new Error(response.statusText);
// @ts-expect-error statusCode is not a standard property
serverError.statusCode = response.status;
if (!`${arguments.length <= 0 ? undefined : arguments[0]}`.endsWith(ASSEMBLIES_ENDPOINT)) return Promise.reject(serverError);
// Failed assembly requests should return a more detailed error in JSON.
return response.json().then(assembly => {
if (!assembly.error) throw serverError;
const error = new Error(assembly.error);
error.details = assembly.message;
error.assembly = assembly;
if (assembly.assembly_id) {
error.details += ` Assembly ID: ${assembly.assembly_id}`;
}
throw error;
}, err => {
// eslint-disable-next-line no-param-reassign
err.cause = serverError;
throw err;
});
}
return response.json();
});
// Failed assembly requests should return a more detailed error in JSON.
return response.json().then(assembly => {
if (!assembly.error) throw serverError;
const error = new AssemblyError(assembly.error, assembly.message, assembly);
if (assembly.assembly_id) {
error.details += ` Assembly ID: ${assembly.assembly_id}`;
}
throw error;
}, err => {
// eslint-disable-next-line no-param-reassign
err.cause = serverError;
throw err;
});
}
return response.json();
}

@@ -9,9 +9,11 @@ function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }

import Tus from '@uppy/tus';
import Assembly from './Assembly.js';
import Client from './Client.js';
import AssemblyOptions, { validateParams } from './AssemblyOptions.js';
import AssemblyWatcher from './AssemblyWatcher.js';
import locale from './locale.js';
import Assembly from "./Assembly.js";
import Client from "./Client.js";
import AssemblyOptionsBuilder, { validateParams } from "./AssemblyOptions.js";
import AssemblyWatcher from "./AssemblyWatcher.js";
import locale from "./locale.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore We don't want TS to generate types for the package.json
const packageJson = {
"version": "3.5.1"
"version": "3.6.0"
};

@@ -30,6 +32,21 @@ const sendErrorToConsole = originalErr => err => {

const TL_COMPANION = /https?:\/\/api2(?:-\w+)?\.transloadit\.com\/companion/;
/**
* Upload files to Transloadit using Tus.
*/
const defaultOptions = {
service: 'https://api2.transloadit.com',
errorReporting: true,
waitForEncoding: false,
waitForMetadata: false,
alwaysRunAssembly: false,
importFromUploadURLs: false,
/** @deprecated use `assemblyOptions` instead */
signature: null,
/** @deprecated use `assemblyOptions` instead */
params: null,
/** @deprecated use `assemblyOptions` instead */
fields: null,
/** @deprecated use `assemblyOptions` instead */
getAssemblyOptions: null,
limit: 20,
retryDelays: [7000, 10000, 15000, 20000],
clientName: null
};
var _rateLimitedQueue = /*#__PURE__*/_classPrivateFieldLooseKey("rateLimitedQueue");

@@ -57,6 +74,12 @@ var _getClientVersion = /*#__PURE__*/_classPrivateFieldLooseKey("getClientVersion");

var _onTusError = /*#__PURE__*/_classPrivateFieldLooseKey("onTusError");
/**
* Upload files to Transloadit using Tus.
*/
export default class Transloadit extends BasePlugin {
constructor(uppy, opts) {
var _this, _this$opts, _this$opts$assemblyOp, _this$opts$getAssembl;
super(uppy, opts);
super(uppy, {
...defaultOptions,
...opts
});
_this = this;

@@ -72,4 +95,2 @@ Object.defineProperty(this, _connectAssembly, {

* and emit it.
*
* @param {object} status
*/

@@ -79,9 +100,2 @@ Object.defineProperty(this, _onAssemblyFinished, {

});
/**
* Callback when a new Assembly result comes in.
*
* @param {string} assemblyId
* @param {string} stepName
* @param {object} result
*/
Object.defineProperty(this, _onResult, {

@@ -117,5 +131,2 @@ value: _onResult2

* See: https://github.com/tus/tusd/wiki/Uploading-to-Transloadit-using-tus#uploading-using-tus
*
* @param {object} file
* @param {object} status
*/

@@ -179,4 +190,2 @@ Object.defineProperty(this, _attachAssemblyMetadata, {

* It will pass this back to the `_onRestored` function.
*
* @param {Function} setData
*/

@@ -278,3 +287,3 @@ Object.defineProperty(this, _getPersistentData, {

restoreAssemblies();
return updateAssemblies();
updateAssemblies();
});

@@ -288,3 +297,3 @@ this.restored.then(() => {

writable: true,
value: (fileIDs, uploadID) => {
value: async (fileIDs, uploadID) => {
const files = fileIDs.map(id => this.uppy.getFile(id));

@@ -301,6 +310,5 @@ const filesWithoutErrors = files.filter(file => {

});
// eslint-disable-next-line no-shadow
const createAssembly = async _ref => {
let {
// eslint-disable-next-line no-shadow
fileIDs,

@@ -339,4 +347,4 @@ options

});
const assemblyOptions = new AssemblyOptions(filesWithoutErrors, this.opts);
return assemblyOptions.build().then(assemblies => Promise.all(assemblies.map(createAssembly))).then(maybeCreatedAssemblies => {
const assemblyOptions = new AssemblyOptionsBuilder(filesWithoutErrors, this.opts);
await assemblyOptions.build().then(assemblies => Promise.all(assemblies.map(createAssembly))).then(maybeCreatedAssemblies => {
const createdAssemblies = maybeCreatedAssemblies.filter(Boolean);

@@ -431,2 +439,3 @@ const assemblyIDs = createdAssemblies.map(assembly => assembly.status.assembly_id);

var _this$activeAssemblie;
if (!assemblyID) return;
(_this$activeAssemblie = this.activeAssemblies[assemblyID]) == null || _this$activeAssemblie.close();

@@ -437,10 +446,11 @@ }

writable: true,
value: function (err, uploadID) {
if (err === void 0) {
err = null;
}
const state = _this.getPluginState();
const assemblyIDs = state.uploadsAssemblies[uploadID];
assemblyIDs == null || assemblyIDs.forEach(_classPrivateFieldLooseBase(_this, _closeAssemblyIfExists)[_closeAssemblyIfExists]);
_this.client.submitError(err)
value: err => {
// TODO: uploadID is not accessible here. The state in core has many upload IDs,
// so we don't know which one to get. This code never worked and no one complained.
// See if we run into problems with this.
// const state = this.getPluginState()
// const assemblyIDs = state.uploadsAssemblies[uploadID]
// assemblyIDs?.forEach(this.#closeAssemblyIfExists)
this.client.submitError(err)
// if we can't report the error that sucks

@@ -456,7 +466,6 @@ .catch(sendErrorToConsole(err));

if (err != null && (_err$message = err.message) != null && _err$message.startsWith('tus: ')) {
var _err$originalRequest;
const endpoint = (_err$originalRequest = err.originalRequest) == null || (_err$originalRequest = _err$originalRequest.getUnderlyingObject()) == null ? void 0 : _err$originalRequest.responseURL;
var _originalRequest;
const endpoint = (_originalRequest = err.originalRequest) == null || (_originalRequest = _originalRequest.getUnderlyingObject()) == null ? void 0 : _originalRequest.responseURL;
this.client.submitError(err, {
endpoint,
type: 'TUS_ERROR'
endpoint
})

@@ -470,27 +479,3 @@ // if we can't report the error that sucks

this.id = this.opts.id || 'Transloadit';
this.title = 'Transloadit';
this.defaultLocale = locale;
const defaultOptions = {
service: 'https://api2.transloadit.com',
errorReporting: true,
waitForEncoding: false,
waitForMetadata: false,
alwaysRunAssembly: false,
importFromUploadURLs: false,
/** @deprecated use `assemblyOptions` instead */
signature: null,
/** @deprecated use `assemblyOptions` instead */
params: null,
/** @deprecated use `assemblyOptions` instead */
fields: null,
/** @deprecated use `assemblyOptions` instead */
getAssemblyOptions: null,
limit: 20,
retryDelays: [7000, 10000, 15000, 20000],
clientName: null
};
this.opts = {
...defaultOptions,
...opts
};

@@ -533,4 +518,2 @@ // TODO: remove this fallback in the next major

this.uppy.on('cancel-all', _classPrivateFieldLooseBase(this, _onCancelAll)[_onCancelAll]);
// For error reporting.
this.uppy.on('upload-error', _classPrivateFieldLooseBase(this, _onTusError)[_onTusError]);

@@ -541,2 +524,4 @@ if (this.opts.importFromUploadURLs) {

} else {
// @ts-expect-error endpoint has to be required for @uppy/tus but for some reason
// we don't need it here.
this.uppy.use(Tus, {

@@ -616,6 +601,11 @@ // Disable tus-js-client fingerprinting, otherwise uploading the same file at different times

function _getClientVersion2() {
const list = [`uppy-core:${this.uppy.constructor.VERSION}`, `uppy-transloadit:${this.constructor.VERSION}`, `uppy-tus:${Tus.VERSION}`];
const list = [
// @ts-expect-error VERSION comes from babel, TS does not understand
`uppy-core:${this.uppy.constructor.VERSION}`,
// @ts-expect-error VERSION comes from babel, TS does not understand
`uppy-transloadit:${this.constructor.VERSION}`, `uppy-tus:${Tus.VERSION}`];
const addPluginVersion = (pluginName, versionName) => {
const plugin = this.uppy.getPlugin(pluginName);
if (plugin) {
// @ts-expect-error VERSION comes from babel, TS does not understand
list.push(`${versionName}:${plugin.constructor.VERSION}`);

@@ -764,6 +754,10 @@ }

assembly.close();
_classPrivateFieldLooseBase(this, _cancelAssembly)[_cancelAssembly](newAssembly).catch(() => {/* ignore potential errors */});
_classPrivateFieldLooseBase(this, _cancelAssembly)[_cancelAssembly](newAssembly).catch(() => {
/* ignore potential errors */
});
this.uppy.off('file-removed', fileRemovedHandler);
} else {
this.client.updateNumberOfFilesInAssembly(newAssembly, nbOfRemainingFiles).catch(() => {/* ignore potential errors */});
this.client.updateNumberOfFilesInAssembly(newAssembly, nbOfRemainingFiles).catch(() => {
/* ignore potential errors */
});
}

@@ -777,2 +771,3 @@ }

}).catch(err => {
// TODO: use AssemblyError?
const wrapped = new ErrorWithCause(`${this.i18n('creatingAssemblyFailed')}: ${err.message}`, {

@@ -782,5 +777,7 @@ cause: err

if ('details' in err) {
// @ts-expect-error details is not in the Error type
wrapped.details = err.details;
}
if ('assembly' in err) {
// @ts-expect-error assembly is not in the Error type
wrapped.assembly = err.assembly;

@@ -791,5 +788,6 @@ }

}
function _createAssemblyWatcher2(assemblyID, uploadID) {
function _createAssemblyWatcher2(idOrArrayOfIds, uploadID) {
// AssemblyWatcher tracks completion states of all Assemblies in this upload.
const watcher = new AssemblyWatcher(this.uppy, assemblyID);
const ids = Array.isArray(idOrArrayOfIds) ? idOrArrayOfIds : [idOrArrayOfIds];
const watcher = new AssemblyWatcher(this.uppy, ids);
watcher.on('assembly-complete', id => {

@@ -978,2 +976,3 @@ const files = this.getAssemblyFiles(id);

// No need to connect to the socket if the Assembly has completed by now.
// @ts-expect-error ok does not exist on Assembly?
if (assembly.ok === 'ASSEMBLY_COMPLETE') {

@@ -980,0 +979,0 @@ return assembly;

{
"name": "@uppy/transloadit",
"description": "The Transloadit plugin can be used to upload files to Transloadit for all kinds of processing, such as transcoding video, resizing images, zipping/unzipping, and more",
"version": "3.5.1",
"version": "3.6.0",
"license": "MIT",

@@ -31,10 +31,10 @@ "main": "lib/index.js",

"dependencies": {
"@uppy/companion-client": "^3.7.2",
"@uppy/provider-views": "^3.9.1",
"@uppy/tus": "^3.5.2",
"@uppy/utils": "^5.7.2",
"@uppy/companion-client": "^3.8.0",
"@uppy/provider-views": "^3.11.0",
"@uppy/tus": "^3.5.4",
"@uppy/utils": "^5.7.5",
"component-emitter": "^1.2.1"
},
"peerDependencies": {
"@uppy/core": "^3.9.1"
"@uppy/core": "^3.10.0"
},

@@ -41,0 +41,0 @@ "devDependencies": {

import { describe, expect, it, vi } from 'vitest'
import { RateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
import Assembly from './Assembly.js'
import Assembly from './Assembly.ts'
describe('Transloadit/Assembly', () => {
describe('status diffing', () => {
function attemptDiff (prev, next) {
function attemptDiff(prev, next) {
const assembly = new Assembly(prev, new RateLimitedQueue())

@@ -20,11 +20,14 @@ const events = []

it('ASSEMBLY_UPLOADING → ASSEMBLY_EXECUTING', () => {
const result = attemptDiff({
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
}, {
ok: 'ASSEMBLY_EXECUTING',
uploads: {},
results: {},
})
const result = attemptDiff(
{
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
},
{
ok: 'ASSEMBLY_EXECUTING',
uploads: {},
results: {},
},
)

@@ -35,11 +38,14 @@ expect(result[0]).toEqual(['executing'])

it('ASSEMBLY_EXECUTING → ASSEMBLY_COMPLETED', () => {
const result = attemptDiff({
ok: 'ASSEMBLY_EXECUTING',
uploads: {},
results: {},
}, {
ok: 'ASSEMBLY_COMPLETED',
uploads: {},
results: {},
})
const result = attemptDiff(
{
ok: 'ASSEMBLY_EXECUTING',
uploads: {},
results: {},
},
{
ok: 'ASSEMBLY_COMPLETED',
uploads: {},
results: {},
},
)

@@ -50,11 +56,14 @@ expect(result[0]).toEqual(['finished'])

it('ASSEMBLY_UPLOADING → ASSEMBLY_COMPLETED', () => {
const result = attemptDiff({
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
}, {
ok: 'ASSEMBLY_COMPLETED',
uploads: {},
results: {},
})
const result = attemptDiff(
{
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
},
{
ok: 'ASSEMBLY_COMPLETED',
uploads: {},
results: {},
},
)

@@ -67,13 +76,16 @@ expect(result[0]).toEqual(['executing'])

it('emits events for new files', () => {
const result = attemptDiff({
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
}, {
ok: 'ASSEMBLY_UPLOADING',
uploads: {
some_id: { id: 'some_id' },
const result = attemptDiff(
{
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
},
results: {},
})
{
ok: 'ASSEMBLY_UPLOADING',
uploads: {
some_id: { id: 'some_id' },
},
results: {},
},
)

@@ -84,13 +96,16 @@ expect(result[0]).toEqual(['upload', { id: 'some_id' }])

it('emits executing, then upload, on new files + status change', () => {
const result = attemptDiff({
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
}, {
ok: 'ASSEMBLY_EXECUTING',
uploads: {
some_id: { id: 'some_id' },
const result = attemptDiff(
{
ok: 'ASSEMBLY_UPLOADING',
uploads: {},
results: {},
},
results: {},
})
{
ok: 'ASSEMBLY_EXECUTING',
uploads: {
some_id: { id: 'some_id' },
},
results: {},
},
)

@@ -116,7 +131,3 @@ expect(result[0]).toEqual(['executing'])

results: {
step_one: [
{ id: 'thumb1' },
{ id: 'thumb2' },
{ id: 'thumb3' },
],
step_one: [{ id: 'thumb1' }, { id: 'thumb2' }, { id: 'thumb3' }],
},

@@ -136,5 +147,3 @@ }

],
step_two: [
{ id: 'transcript' },
],
step_two: [{ id: 'transcript' }],
},

@@ -172,5 +181,3 @@ }

],
step_two: [
{ id: 'transcript' },
],
step_two: [{ id: 'transcript' }],
},

@@ -177,0 +184,0 @@ }

import { describe, expect, it } from 'vitest'
import AssemblyOptions from './AssemblyOptions.js'
import AssemblyOptions from './AssemblyOptions.ts'
describe('Transloadit/AssemblyOptions', () => {
it('Validates response from assemblyOptions()', async () => {
const options = new AssemblyOptions([
{ name: 'testfile' },
], {
const options = new AssemblyOptions([{ name: 'testfile' }], {
assemblyOptions: (file) => {

@@ -26,17 +24,20 @@ expect(file.name).toBe('testfile')

const options = new AssemblyOptions([
{ name: 'a.png', data },
{ name: 'b.png', data },
{ name: 'c.png', data },
{ name: 'd.png', data },
], {
assemblyOptions: (file) => ({
params: {
auth: { key: 'fake key' },
steps: {
fake_step: { data: file.name },
const options = new AssemblyOptions(
[
{ name: 'a.png', data },
{ name: 'b.png', data },
{ name: 'c.png', data },
{ name: 'd.png', data },
],
{
assemblyOptions: (file) => ({
params: {
auth: { key: 'fake key' },
steps: {
fake_step: { data: file.name },
},
},
},
}),
})
}),
},
)

@@ -55,17 +56,20 @@ const assemblies = await options.build()

const options = new AssemblyOptions([
{ name: 'a.png', data, size: data.byteLength },
{ name: 'b.png', data, size: data.byteLength },
{ name: 'c.png', data, size: data.byteLength },
{ name: 'd.png', data: data2, size: data2.byteLength },
], {
assemblyOptions: (file) => ({
params: {
auth: { key: 'fake key' },
steps: {
fake_step: { data: file.size },
const options = new AssemblyOptions(
[
{ name: 'a.png', data, size: data.byteLength },
{ name: 'b.png', data, size: data.byteLength },
{ name: 'c.png', data, size: data.byteLength },
{ name: 'd.png', data: data2, size: data2.byteLength },
],
{
assemblyOptions: (file) => ({
params: {
auth: { key: 'fake key' },
steps: {
fake_step: { data: file.size },
},
},
},
}),
})
}),
},
)

@@ -82,3 +86,3 @@ const assemblies = await options.build()

const options = new AssemblyOptions([], {
assemblyOptions () {
assemblyOptions() {
throw new Error('should not create Assembly')

@@ -94,3 +98,3 @@ },

alwaysRunAssembly: true,
async assemblyOptions (file) {
async assemblyOptions(file) {
expect(file).toBe(null)

@@ -110,3 +114,3 @@ return {

it('Collects metadata if `fields` is an array', async () => {
function defaultGetAssemblyOptions (file, options) {
function defaultGetAssemblyOptions(file, options) {
return {

@@ -119,15 +123,21 @@ params: options.params,

const options = new AssemblyOptions([{
id: 1,
meta: { watermark: 'Some text' },
}, {
id: 2,
meta: { watermark: 'ⓒ Transloadit GmbH' },
}], {
fields: ['watermark'],
params: {
auth: { key: 'fake key' },
const options = new AssemblyOptions(
[
{
id: 1,
meta: { watermark: 'Some text' },
},
{
id: 2,
meta: { watermark: 'ⓒ Transloadit GmbH' },
},
],
{
fields: ['watermark'],
params: {
auth: { key: 'fake key' },
},
assemblyOptions: defaultGetAssemblyOptions,
},
assemblyOptions: defaultGetAssemblyOptions,
})
)

@@ -134,0 +144,0 @@ const assemblies = await options.build()

@@ -5,3 +5,3 @@ import { createServer } from 'node:http'

import Core from '@uppy/core'
import Transloadit from './index.js'
import Transloadit from './index.ts'
import 'whatwg-fetch'

@@ -34,3 +34,4 @@

uppy.use(Transloadit, {
params: '{"auth":{"key":"some auth key string"},"template_id":"some template id string"}',
params:
'{"auth":{"key":"some auth key string"},"template_id":"some template id string"}',
})

@@ -44,3 +45,3 @@ }).not.toThrowError(/The `params\.auth\.key` option is required/)

uppy.use(Transloadit, {
getAssemblyOptions () {
getAssemblyOptions() {
return Promise.reject(error)

@@ -56,10 +57,13 @@ },

return uppy.upload().then(() => {
throw new Error('Should not have succeeded')
}).catch((err) => {
const fileID = Object.keys(uppy.getState().files)[0]
return uppy
.upload()
.then(() => {
throw new Error('Should not have succeeded')
})
.catch((err) => {
const fileID = Object.keys(uppy.getState().files)[0]
expect(err).toBe(error)
expect(uppy.getFile(fileID).progress.uploadStarted).toBe(null)
})
expect(err).toBe(error)
expect(uppy.getFile(fileID).progress.uploadStarted).toBe(null)
})
})

@@ -76,3 +80,4 @@

uppy.getPlugin('Transloadit').client.createAssembly = () => Promise.reject(new Error('VIDEO_ENCODE_VALIDATION'))
uppy.getPlugin('Transloadit').client.createAssembly = () =>
Promise.reject(new Error('VIDEO_ENCODE_VALIDATION'))

@@ -85,10 +90,15 @@ uppy.addFile({

return uppy.upload().then(() => {
throw new Error('Should not have succeeded')
}, (err) => {
const fileID = Object.keys(uppy.getState().files)[0]
return uppy.upload().then(
() => {
throw new Error('Should not have succeeded')
},
(err) => {
const fileID = Object.keys(uppy.getState().files)[0]
expect(err.message).toBe('Transloadit: Could not create Assembly: VIDEO_ENCODE_VALIDATION')
expect(uppy.getFile(fileID).progress.uploadStarted).toBe(null)
})
expect(err.message).toBe(
'Transloadit: Could not create Assembly: VIDEO_ENCODE_VALIDATION',
)
expect(uppy.getFile(fileID).progress.uploadStarted).toBe(null)
},
)
})

@@ -119,3 +129,3 @@

server.closeAllConnections()
await new Promise(resolve => server.close(resolve))
await new Promise((resolve) => server.close(resolve))
})

@@ -147,4 +157,4 @@

server.closeAllConnections()
await new Promise(resolve => server.close(resolve))
await new Promise((resolve) => server.close(resolve))
})
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc