Преглед изворни кода

@uppy/transloadit: refactor to ESM (#3725)

Antoine du Hamel пре 2 година
родитељ
комит
3f5a03f504

+ 1 - 0
.eslintrc.js

@@ -225,6 +225,7 @@ module.exports = {
         'packages/@uppy/thumbnail-generator/src/**/*.js',
         'packages/@uppy/tus/src/**/*.js',
         'packages/@uppy/unsplash/src/**/*.js',
+        'packages/@uppy/transloadit/src/**/*.js',
         'packages/@uppy/url/src/**/*.js',
         'packages/@uppy/vue/src/**/*.js',
         'packages/@uppy/webcam/src/**/*.js',

+ 2 - 0
packages/@uppy/transloadit/package.json

@@ -5,6 +5,7 @@
   "license": "MIT",
   "main": "lib/index.js",
   "types": "types/index.d.ts",
+  "type": "module",
   "keywords": [
     "file uploader",
     "transloadit",
@@ -38,6 +39,7 @@
     "@uppy/core": "workspace:^"
   },
   "devDependencies": {
+    "@jest/globals": "^27.4.2",
     "whatwg-fetch": "^3.6.2"
   }
 }

+ 10 - 10
packages/@uppy/transloadit/src/Assembly.js

@@ -1,19 +1,19 @@
-const Emitter = require('component-emitter')
-const has = require('@uppy/utils/lib/hasProperty')
-const NetworkError = require('@uppy/utils/lib/NetworkError')
-const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError')
-const parseUrl = require('./parseUrl')
+import Emitter from 'component-emitter'
+import has from '@uppy/utils/lib/hasProperty'
+import NetworkError from '@uppy/utils/lib/NetworkError'
+import fetchWithNetworkError from '@uppy/utils/lib/fetchWithNetworkError'
+import parseUrl from './parseUrl.js'
 
-// Lazy load socket.io to avoid a console error
+// We used to lazy load socket.io to avoid a console error
 // in IE 10 when the Transloadit plugin is not used.
 // (The console.error call comes from `buffer`. I
 // think we actually don't use that part of socket.io
 // at all…)
+// TODO: remove this hack in the next release.
 let socketIo
 function requireSocketIo () {
-  // eslint-disable-next-line global-require
-  socketIo ??= require('socket.io-client')
-  return socketIo
+  // eslint-disable-next-line no-return-assign, no-restricted-globals, global-require
+  return socketIo ??= require('socket.io-client')
 }
 
 const ASSEMBLY_UPLOADING = 'ASSEMBLY_UPLOADING'
@@ -282,4 +282,4 @@ class TransloaditAssembly extends Emitter {
   }
 }
 
-module.exports = TransloaditAssembly
+export default TransloaditAssembly

+ 3 - 2
packages/@uppy/transloadit/src/Assembly.test.js

@@ -1,5 +1,6 @@
-const { RateLimitedQueue } = require('@uppy/utils/lib/RateLimitedQueue')
-const Assembly = require('./Assembly')
+import { describe, expect, it, jest } from '@jest/globals'
+import { RateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
+import Assembly from './Assembly.js'
 
 describe('Transloadit/Assembly', () => {
   describe('status diffing', () => {

+ 7 - 3
packages/@uppy/transloadit/src/AssemblyOptions.js

@@ -1,4 +1,4 @@
-const ErrorWithCause = require('@uppy/utils/lib/ErrorWithCause')
+import ErrorWithCause from '@uppy/utils/lib/ErrorWithCause'
 
 /**
  * Check that Assembly parameters are present and include all required fields.
@@ -113,5 +113,9 @@ class AssemblyOptions {
   }
 }
 
-module.exports = AssemblyOptions
-module.exports.validateParams = validateParams
+export default AssemblyOptions
+export { validateParams }
+
+// Backward compatibility: we want `validateParams` to keep being a static
+// method of `AssemblyOptions` to avoid a breaking change.
+AssemblyOptions.validateParams = validateParams // TODO: remove this line on the next major

+ 2 - 1
packages/@uppy/transloadit/src/AssemblyOptions.test.js

@@ -1,4 +1,5 @@
-const AssemblyOptions = require('./AssemblyOptions')
+import { describe, expect, it } from '@jest/globals'
+import AssemblyOptions from './AssemblyOptions.js'
 
 describe('Transloadit/AssemblyOptions', () => {
   it('Validates response from getAssemblyOptions()', async () => {

+ 2 - 2
packages/@uppy/transloadit/src/AssemblyWatcher.js

@@ -1,4 +1,4 @@
-const Emitter = require('component-emitter')
+import Emitter from 'component-emitter'
 
 /**
  * Track completion of multiple assemblies.
@@ -111,4 +111,4 @@ class TransloaditAssemblyWatcher extends Emitter {
   }
 }
 
-module.exports = TransloaditAssemblyWatcher
+export default TransloaditAssemblyWatcher

+ 2 - 2
packages/@uppy/transloadit/src/Client.js

@@ -1,11 +1,11 @@
-const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError')
+import fetchWithNetworkError from '@uppy/utils/lib/fetchWithNetworkError'
 
 const ASSEMBLIES_ENDPOINT = '/assemblies'
 
 /**
  * A Barebones HTTP API client for Transloadit.
  */
-module.exports = class Client {
+export default class Client {
   #headers = {}
 
   #fetchWithNetworkError

+ 27 - 18
packages/@uppy/transloadit/src/index.js

@@ -1,14 +1,15 @@
-const hasProperty = require('@uppy/utils/lib/hasProperty')
-const ErrorWithCause = require('@uppy/utils/lib/ErrorWithCause')
-const { RateLimitedQueue } = require('@uppy/utils/lib/RateLimitedQueue')
-const BasePlugin = require('@uppy/core/lib/BasePlugin')
-const Tus = require('@uppy/tus')
-const Assembly = require('./Assembly')
-const Client = require('./Client')
-const AssemblyOptions = require('./AssemblyOptions')
-const AssemblyWatcher = require('./AssemblyWatcher')
-
-const locale = require('./locale')
+import hasProperty from '@uppy/utils/lib/hasProperty'
+import ErrorWithCause from '@uppy/utils/lib/ErrorWithCause'
+import { RateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
+import BasePlugin from '@uppy/core/lib/BasePlugin'
+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 packageJson from '../package.json'
 
 function defaultGetAssemblyOptions (file, options) {
   return {
@@ -20,7 +21,7 @@ function defaultGetAssemblyOptions (file, options) {
 
 const sendErrorToConsole = originalErr => err => {
   const error = new ErrorWithCause('Failed to send error to the client', { cause: err })
-  // eslint-ignore-next-line no-console
+  // eslint-disable-next-line no-console
   console.error(error, originalErr)
 }
 
@@ -33,8 +34,8 @@ const TL_COMPANION = /https?:\/\/api2(?:-\w+)?\.transloadit\.com\/companion/
 /**
  * Upload files to Transloadit using Tus.
  */
-module.exports = class Transloadit extends BasePlugin {
-  static VERSION = require('../package.json').version // eslint-disable-line global-require
+export default class Transloadit extends BasePlugin {
+  static VERSION = packageJson.version
 
   #rateLimitedQueue
 
@@ -68,11 +69,11 @@ module.exports = class Transloadit extends BasePlugin {
 
     const hasCustomAssemblyOptions = this.opts.getAssemblyOptions !== defaultOptions.getAssemblyOptions
     if (this.opts.params) {
-      AssemblyOptions.validateParams(this.opts.params)
+      validateParams(this.opts.params)
     } else if (!hasCustomAssemblyOptions) {
       // Throw the same error that we'd throw if the `params` returned from a
       // `getAssemblyOptions()` function is null.
-      AssemblyOptions.validateParams(null)
+      validateParams(null)
     }
 
     this.client = new Client({
@@ -826,5 +827,13 @@ module.exports = class Transloadit extends BasePlugin {
   }
 }
 
-module.exports.COMPANION = COMPANION
-module.exports.COMPANION_PATTERN = ALLOWED_COMPANION_PATTERN
+export {
+  COMPANION,
+  ALLOWED_COMPANION_PATTERN,
+}
+
+// Backward compatibility: we want `COMPANION` and `ALLOWED_COMPANION_PATTERN`
+// to keep being accessible as static properties of `Transloadit` to avoid a
+// breaking change.
+Transloadit.COMPANION = COMPANION // TODO: remove this line on the next major
+Transloadit.ALLOWED_COMPANION_PATTERN = ALLOWED_COMPANION_PATTERN // TODO: remove this line on the next major

+ 4 - 3
packages/@uppy/transloadit/src/index.test.js

@@ -1,6 +1,7 @@
-const Core = require('@uppy/core')
-const Transloadit = require('.')
-require('whatwg-fetch')
+import { describe, expect, it } from '@jest/globals'
+import Core from '@uppy/core'
+import Transloadit from './index.js'
+import 'whatwg-fetch'
 
 describe('Transloadit', () => {
   it('Throws errors if options are missing', () => {

+ 1 - 1
packages/@uppy/transloadit/src/locale.js

@@ -1,4 +1,4 @@
-module.exports = {
+export default {
   strings: {
     // Shown while Assemblies are being created for an upload.
     creatingAssembly: 'Preparing upload...',

+ 1 - 1
packages/@uppy/transloadit/src/parseUrl.js

@@ -1,4 +1,4 @@
-module.exports = function parseUrl (url) {
+export default function parseUrl (url) {
   const scheme = /^\w+:\/\//.exec(url)
   let i = 0
   if (scheme) {

+ 2 - 1
packages/@uppy/transloadit/src/parseUrl.test.js

@@ -1,4 +1,5 @@
-const parseUrl = require('./parseUrl')
+import { describe, expect, it } from '@jest/globals'
+import parseUrl from './parseUrl.js'
 
 describe('Transloadit/parseUrl', () => {
   it('splits a url into origin and pathname', () => {

+ 24 - 0
private/dev/vite.config.js

@@ -147,6 +147,30 @@ const config = {
                       }
                     }
                   },
+
+                  // Very specific hack to avoid a breaking change when the file was refactored to ESM.
+                  // TODO: remove this hack in the next release.
+                  ...(id.endsWith('transloadit/src/Assembly.js') ? {
+                    FunctionDeclaration (path) {
+                      if (path.node.id.name === 'requireSocketIo') {
+                        const prevSibling = path.getPrevSibling()
+                        if (!t.isVariableDeclaration(prevSibling) || prevSibling.node.declarations[0].id.name !== 'socketIo') {
+                          // The require call has already been rewritten to an import statement.
+                          return
+                        }
+
+                        const { id:socketIoIdentifier } = prevSibling.node.declarations[0]
+
+                        prevSibling.replaceWith(t.importDeclaration(
+                          [t.importDefaultSpecifier(socketIoIdentifier)],
+                          t.stringLiteral('socket.io-client'),
+                        ))
+                        path.replaceWith(t.functionDeclaration(path.node.id, path.node.params, t.blockStatement([
+                          t.returnStatement(socketIoIdentifier),
+                        ])))
+                      }
+                    },
+                  } : null),
                 },
               },
             ],

+ 1 - 1
website/src/docs/transloadit.md

@@ -305,7 +305,7 @@ Limit the amount of uploads going on at the same time. Setting this to `0` means
 <!-- eslint-disable no-restricted-globals, no-multiple-empty-lines -->
 
 ```js
-module.exports = {
+export default {
   strings: {
     // Shown while Assemblies are being created for an upload.
     creatingAssembly: 'Preparing upload...',

+ 1 - 0
yarn.lock

@@ -10163,6 +10163,7 @@ __metadata:
   version: 0.0.0-use.local
   resolution: "@uppy/transloadit@workspace:packages/@uppy/transloadit"
   dependencies:
+    "@jest/globals": ^27.4.2
     "@uppy/companion-client": "workspace:^"
     "@uppy/provider-views": "workspace:^"
     "@uppy/tus": "workspace:^"