All files / dist index.js

91.05% Statements 173/190
84.31% Branches 86/102
93.75% Functions 15/16
98.21% Lines 165/168
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421    1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   4x                   1x 86x 99x   1x   1x       85x 85x 85x   85x 85x 85x 85x 85x 85x 85x 85x     85x 85x 85x   85x   85x 85x 71x         1x             93x   93x 93x   93x                   93x   215x 93x                         93x   93x 107x   64x 64x         64x 63x 63x 63x     64x 28x         43x   17x     14x 14x 14x       3x         26x   26x                   93x 93x 40x     93x     93x 20x     93x 88x                   102x 102x   102x 102x   6x 6x 6x 6x 6x     102x   17x 35x         17x 85x   85x 85x   51x 51x         34x   34x 34x 34x                 85x                       61x 61x 61x 61x   1x   61x     34x 34x       27x 1x 1x   26x   27x         1x 1x 1x   1x   1x   1x         1x                     43x   43x 1x   42x 39x     39x 39x 4x   35x     40x 35x   35x   35x   30x 5x   5x   5x       5x         13x               720x 720x 720x 6x 6x         714x 12x 12x 702x 393x 11x 382x 7x                   22x 22x       1x             12x 24x 12x             11x             7x           18x 18x 18x 18x   18x       42x 42x 1x   45x 41x       61x     1x      
'use strict';
 
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
 
var _babelTypes = require('babel-types');
 
var t = _interopRequireWildcard(_babelTypes);
 
var _templates = require('./helpers/templates');
 
var th = _interopRequireWildcard(_templates);
 
var _ast = require('./helpers/ast');
 
var ast = _interopRequireWildcard(_ast);
 
var _classes = require('./helpers/classes');
 
var classes = _interopRequireWildcard(_classes);
 
var _jsdoc = require('./helpers/jsdoc');
 
var _wrapper = require('./helpers/wrapper');
 
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
 
/*
References:
Babel Plugin Handbook: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md
AST Spec: https://github.com/babel/babylon/blob/master/ast/spec.md
Babel Types (t.*) https://github.com/babel/babel/tree/master/packages/babel-types
AST Explorer: https://astexplorer.net/
*/
 
const CONSTRUCTOR = 'constructor';
const tempModuleName = name => `__${ name }`;
const cleanImportSource = src => src.replace(/(\/)|(-)/g, '_').replace(/\./g, '');
 
module.exports = () => {
 
  const ProgramVisitor = {
    // Use a ProgramVisitor to efficiently avoid processing the same file twice if babel calls twice.
    // The UI5ModuleVisitor will only be used if it hasn't let ran.
    Program(path, { opts }) {
      Iif (this.ran) return;
      this.ran = true;
      let { node } = path;
 
      this.defaultExport = null;
      this.defaultExportNode = null;
      this.exportGlobal = false;
      this.imports = [];
      this.namedExports = [];
      this.requires = [];
      this.injectDynamicImportHelper = false;
      this.programNode = node;
 
      // Opts handling
      this.namespacePrefix = opts.namespacePrefix;
      this.noImportInteropPrefixes = opts.noImportInteropPrefixes || ['sap/'];
      this.noImportInteropPrefixesRegexp = new RegExp(this.noImportInteropPrefixes.map(p => `(^${ p }.*)`).join('|'));
 
      path.traverse(UI5ModuleVisitor, this);
 
      const needsWrap = !!(this.defaultExport || this.imports.length || this.namedExports.length || this.injectDynamicImportHelper);
      if (needsWrap) {
        (0, _wrapper.wrap)(this, node, opts);
      }
    }
  };
 
  const UI5ModuleVisitor = {
 
    /*!
     * Removes the ES6 import and adds the details to the import array in our state.
     */
    ImportDeclaration(path) {
      // { opts = {} }
      const { node } = path;
 
      const { specifiers, source } = node;
      const src = source.value.replace(/\\/g, '/');
 
      const shouldInterop = !this.noImportInteropPrefixesRegexp.test(src);
 
      // NOTE: DO NOT REMOVE. This code is for future enhancements, not old logic.
      // const testLibs = opts.libs || ['^sap/']
      // const isLibRE = testLibs.length && new RegExp(`(${testLibs.join('|')})`)
      // const isLib = isLibRE.test(src)
      // const testSrc = (opts.libs || ['^sap/']).concat(opts.files || [])
      // const isUi5SrcRE = testSrc.length && new RegExp(`(${testSrc.join('|')})`)
      // const isUi5Src = isUi5SrcRE.test(src)
 
      const name = cleanImportSource(src); // default to the src for import without named var
 
      const existingImport = this.imports.find(imp => imp.src === src);
      const imp = existingImport || {
        src, // url
        name,
        // isLib, // for future use separating UI5 imports from npm/webpack imports
        // isUi5Src, // not used yet
        tmpName: shouldInterop ? tempModuleName(name) : name,
        destructors: [],
        default: false,
        interop: false,
        path: path,
        locked: false
      };
 
      const destructors = [];
 
      for (const specifier of specifiers) {
        if (t.isImportDefaultSpecifier(specifier)) {
          // import X from 'X'
          imp.default = true;
          imp.interop = shouldInterop;
 
          // Shorten the imported-as name since it should be unique for default imports.
          // The default import should always come first,
          // so this new name will be used for destructuring the other too.
          if (!imp.locked) {
            imp.name = specifier.local.name;
            imp.tmpName = shouldInterop ? tempModuleName(imp.name) : imp.name;
            imp.locked = true;
          }
 
          if (shouldInterop) {
            destructors.push(th.buildDefaultImportDestructor({
              MODULE: t.identifier(imp.tmpName),
              LOCAL: specifier.local
            }));
          }
        } else if (t.isImportNamespaceSpecifier(specifier)) {
          // console.log(specifier)
          if (specifiers.length === 1 && !imp.locked) {
            // import * as X from 'X'
            // If the namespace specifier is the only import, we can avoid the temp name and the destructor
            imp.name = specifier.local.name;
            imp.tmpName = specifier.local.name;
            imp.locked = true;
          } else {
            // import X, * as X2 from 'X'
            // Else it's probably combined with a default export. keep the tmpName and destruct it
            destructors.push(th.buildConstDeclaration({
              NAME: specifier.local,
              VALUE: t.identifier(imp.tmpName)
            }));
          }
        } else Eif (t.isImportSpecifier(specifier)) {
          // import { A } from 'X'
          destructors.push(th.buildNamedImportDestructor({
            MODULE: t.identifier(imp.tmpName),
            LOCAL: specifier.local,
            IMPORTED: t.stringLiteral(specifier.imported.name)
          }));
        } else {
          throw path.buildCodeFrameError(`Unknown ImportDeclaration specifier type ${ specifier.type }`);
        }
      }
 
      path.replaceWithMultiple(destructors);
      if (destructors.length) {
        imp.locked = true;
      }
 
      imp.destructors = imp.destructors.concat(destructors);
 
      // TODO now that we're saving destructors on the imp, dynamically determine firstImport if needed.
      if (!this.firstImport && imp.destructors[0]) {
        this.firstImport = imp.destructors[0];
      }
 
      if (!existingImport) {
        this.imports.push(imp);
      }
    },
 
    /**
     * Push all exports to an array.
     * The reason we don't export in place is to handle the situation
     * where a let or var can be defined, and the latest one should be exported.
     */
    ExportNamedDeclaration(path) {
      const { node } = path;
      const { specifiers, declaration, source } = node;
 
      let fromSource = '';
      if (source) {
        // export { one, two } from 'x'
        const src = source.value;
        const name = cleanImportSource(src);
        const tmpName = tempModuleName(name);
        this.imports.push({ src, name, tmpName });
        fromSource = tmpName + '.';
      }
 
      if (specifiers && specifiers.length) {
        // export { one, two }
        for (const specifier of path.node.specifiers) {
          this.namedExports.push({
            key: specifier.exported,
            value: t.identifier(`${ fromSource }${ specifier.local.name }`)
          });
        }
        path.remove();
      } else Eif (declaration) {
        // export const c = 1 | export function f() {}
        const name = ast.getIdName(declaration);
        if (name) {
          // export function f() {}
          const id = t.identifier(declaration.id.name);
          this.namedExports.push({
            key: id,
            value: id,
            declaration
          });
        } else Eif (declaration.declarations) {
          // export const c = 1
          for (const subDeclaration of declaration.declarations) {
            const id = t.identifier(subDeclaration.id.name);
            this.namedExports.push({
              value: id,
              key: id,
              declaration: subDeclaration
            });
          }
        } else {
          throw path.buildCodeFrameError('Unknown ExportNamedDeclaration shape.');
        }
        path.replaceWith(declaration);
      } else {
        throw path.buildCodeFrameError('Unknown ExportNamedDeclaration shape.');
      }
    },
 
    /*!
     * Replaces the ES6 export with sap.ui.define by using the state.imports array built up when
     * visiting ImportDeclaration.
     * Only a single 'export default' is supported.
     */
    ExportDefaultDeclaration(path) {
      const { node } = path;
      const { declaration } = node;
      const declarationName = ast.getIdName(declaration);
      if (hasGlobalExportFlag(node)) {
        // check for jsdoc @export
        this.exportGlobal = true;
      }
      if (declarationName) {
        // ClassDeclaration or FunctionDeclaration with name.
        // Leave the declaration in-line and preserve the identifier for the return statement.
        path.replaceWith(declaration);
        this.defaultExport = t.identifier(declarationName);
      } else {
        // Identifier, ObjectExpression or anonymous FunctionDeclaration
        // Safe to move to the end and return directly
        if (t.isFunctionDeclaration(declaration)) {
          const { params, body, generator, async: isAsync } = declaration;
          this.defaultExport = t.functionExpression(null, params, body, generator, isAsync);
        } else {
          this.defaultExport = declaration;
        }
        path.remove();
      }
    },
 
    ExportAllDeclaration(path) {
      const src = path.node.source.value;
      const name = src.replace(/\//g, '_').replace(/\./g, '');
      const tmpName = tempModuleName(name);
 
      this.imports.push({ src, name, tmpName });
 
      this.exportAllHelper = true;
 
      this.namedExports.push({
        all: true,
        value: t.identifier(tmpName)
      });
 
      path.remove();
    },
 
    /**
     * ClassDeclaration visitor.
     * Use both enter() and exit() to track when the visitor is inside a UI5 class,
     * in order to convert the super calls.
     * No changes for non-UI5 classes.
     */
    Class: {
      enter(path, { opts = {} }) {
        const { node, parent, parentPath } = path;
 
        if (opts.neverConvertClass) {
          return;
        }
        if (doesClassExtendFromImport(node, [...this.imports, ...this.requires])) {
          const { name } = node.id;
          // If the super class is one of the imports, we'll assume it's a UI5 managed class,
          // and therefore needs to be transformed to .extend() syntax.
          const classInfo = classes.getClassInfo(path, node, path.parent, opts);
          if (classInfo.nonUI5 || opts.onlyConvertNamedClass && !classInfo.name) {
            return;
          }
          this.superClassName = classInfo.superClassName;
 
          // Find the Block scoped parent (Program or Function body) and search for assigned properties within that.
          const blockParent = path.findParent(path => path.isBlock()).node;
          const staticProps = ast.groupPropertiesByName(ast.getOtherPropertiesOfIdentifier(blockParent, name));
          // TODO flag metadata and renderer for removal if applicable
          const ui5ExtendClass = classes.convertClassToUI5Extend(path, node, classInfo, staticProps, opts);
 
          if (path.isClassDeclaration()) {
            // class X {}
            path.replaceWithMultiple(ui5ExtendClass);
          } else Eif (path.isClassExpression()) {
            // return class X {}
            Eif (t.isReturnStatement(parent)) {
              // Add the return statement back before calling replace
              ui5ExtendClass.push(th.buildReturn({
                ID: t.identifier(classInfo.localName)
              }));
            }
            parentPath.replaceWithMultiple(ui5ExtendClass);
          }
        }
      },
      exit() {
        this.superClassName = null;
      }
    },
 
    /*!
     * Visits function calls.
     */
    CallExpression(path) {
      const { node } = path;
      const { callee } = node;
      if (ast.isImport(callee)) {
        this.injectDynamicImportHelper = true;
        path.replaceWith(_extends({}, node, {
          callee: t.identifier('__ui5_require_async')
        }));
      }
      // If the file already has sap.ui.define, get the names of variables it creates to use for the class logic.
      else if (ast.isCallExpressionCalling(node, 'sap.ui.define')) {
          this.requires = getRequiredParamsOfSAPUIDefine(path, node);
          return;
        } else if (this.superClassName) {
          if (t.isSuper(callee)) {
            replaceConstructorSuperCall(path, node, this.superClassName);
          } else if (t.isSuper(callee.object)) {
            replaceObjectSuperCall(path, node, this.superClassName);
          }
        }
    },
 
    /**
     * Convert object method constructor() to constructor: function constructor(),
     * since a UI5 class is not a real class.
     */
    ObjectMethod(path) {
      const { node } = path;
      if (node.key.name === CONSTRUCTOR) {
        // The keyword 'constructor' should not be used as a shorthand
        // method name in an object. It might(?) work on some objects,
        // but it doesn't work with X.extend(...) inheritance.
        path.replaceWith(t.objectProperty(t.identifier(CONSTRUCTOR), t.functionExpression(t.identifier(CONSTRUCTOR), node.params, node.body)));
      }
    }
 
  };
 
  function getRequiredParamsOfSAPUIDefine(path, node) {
    const defineArgs = node.arguments;
    const callbackNode = defineArgs.find(argNode => t.isFunction(argNode));
    return callbackNode.params; // Identifier
  }
 
  /**
   * Replace super() call
   */
  function replaceConstructorSuperCall(path, node, superClassName) {
    replaceSuperNamedCall(path, node, superClassName, CONSTRUCTOR);
  }
 
  /**
   * Replace super.method() call
   */
  function replaceObjectSuperCall(path, node, superClassName) {
    replaceSuperNamedCall(path, node, superClassName, node.callee.property.name);
  }
 
  function replaceSuperNamedCall(path, node, superClassName, methodName) {
    // .call() is better for simple args (or not args) but doesn't work right for spread args
    // if it gets further transpiled by babel spread args transform (will be .call.apply(...).
    const thisEx = t.thisExpression();
    const hasSpread = node.arguments.some(t.isSpreadElement);
    const caller = hasSpread ? 'apply' : 'call';
    const callArgs = hasSpread ? [thisEx, t.arrayExpression(node.arguments)] : [thisEx, ...node.arguments];
    // console.log(callArgs)
    path.replaceWith(t.callExpression(t.identifier(`${ superClassName }.prototype.${ methodName }.${ caller }`), callArgs));
  }
 
  function doesClassExtendFromImport(node, imports) {
    const superClass = node.superClass;
    if (!superClass) {
      return false;
    }
    const isImported = imports.some(imported => imported.name === superClass.name);
    return isImported;
  }
 
  function hasGlobalExportFlag(node) {
    return (0, _jsdoc.hasJsdocGlobalExportFlag)(node);
  }
 
  return {
    visitor: ProgramVisitor
  };
};