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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 1x 1x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 14x 50x 50x 50x 12x 12x 10x 2x 2x 48x 1x 48x 43x 5x 3x 3x 16x 1x 1x 1x 1x 15x 3x 3x 48x 9x 48x 1x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 50x 36x 36x 36x 36x 36x 11x 14x 12x 2x 2x 40x 40x 40x 48x 48x 48x 48x 4x 4x 4x 4x 4x 48x 10x 20x 10x 38x 38x 38x 25x 25x 13x 13x 13x 13x 38x 45x 45x 45x 45x 45x 1x 45x 27x 27x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 36x 36x 1x 35x 32x 32x 32x 5x 27x 32x 27x 27x 27x 22x 5x 5x 5x 5x 14x 337x 337x 337x 2x 2x 335x 12x 12x 323x 76x 8x 68x 4x 22x 22x 22x 1x 12x 24x 12x 8x 8x 4x 4x 4x 35x 35x 1x 38x 34x 48x 45x 45x 48x 45x 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; }; // import t from 'babel-types' require('source-map-support/register'); var _templates = require('./helpers/templates'); var th = _interopRequireWildcard(_templates); var _ast = require('./helpers/ast'); var _classes = require('./helpers/classes'); var _exports = require('./helpers/exports'); var _jsdoc = require('./helpers/jsdoc'); 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 tempModuleName = name => `__${ name }`; module.exports = ({ types: t }) => { 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: { exit(path, { opts }) { Iif (this.ran) return; this.ran = true; let { node } = path; let { body } = node; this.defaultExport = null; this.defaultExportNode = null; this.exportGlobal = false; this.imports = []; this.namedExports = []; this.requires = []; this.injectDynamicImportHelper = false; // Opts handling this.namespacePrefix = opts.namespacePrefix; const { noImportInteropPrefixes = ['sap/'] } = opts; this.noImportInteropPrefixesRegexp = new RegExp(noImportInteropPrefixes.map(p => `(^${ p }.*)`).join('|')); this.programNode = node; path.traverse(UI5ModuleVisitor, this); const needsWrap = this.defaultExport || this.imports.length || this.namedExports.length || this.injectDynamicImportHelper; if (!needsWrap) { return; } let allExportHelperAdded = false; opts.collapse = !opts.noExportCollapse; // opts.extend = !opts.noExportExtend // Before adding anything, see if the named exports can be collapsed into the default export. if (this.defaultExport && this.namedExports.length && opts.collapse) { let filteredExports = (0, _exports.collapseNamedExports)(node, this.defaultExportDeclaration, this.namedExports, opts); if (!filteredExports.length) { this.namedExports = []; } else Eif (!opts.allowUnsafeMixedExports) { throw new Error(`Unsafe mixing of default and named exports. The following named exports can't be collapsed or ignored: \n(${ (0, _ast.getPropNames)(filteredExports).join(', ') }).`); } } if (this.injectDynamicImportHelper) { body.unshift(th.buildDynamicImportHelper()); } if (!this.namedExports.length && this.defaultExport) { body.push(t.returnStatement(this.defaultExport)); } else if (this.namedExports.length) { body.unshift(...[th.buildDeclareExports(), th.buildExportsModuleDeclaration()]); for (let namedExport of this.namedExports) { if (namedExport.all) { Eif (!allExportHelperAdded) { body.push(th.buildAllExportHelper()); allExportHelperAdded = true; } body.push(th.buildAllExport({ LOCAL: namedExport.value })); } else { body.push(th.buildNamedExport(namedExport)); } } Iif (this.defaultExport) { body.push(th.buildNamedExport({ key: t.identifier('default'), value: this.defaultExport })); } body.push(t.returnStatement(t.identifier('exports'))); } if (this.imports.some(imp => imp.interop)) { body.unshift(th.buildDefaultImportInterop()); } node.body = [generateDefine(body, this.imports, this.exportGlobal || opts.exportAllGlobal)]; } } }; const UI5ModuleVisitor = { /*! * Removes the ES6 import and adds the details to the import array in our state. */ ImportDeclaration(path, { opts = {} }) { // this.wrap = true const { node } = path; const { specifiers, source } = node; const src = source.value.replace(/\\/g, '/'); const noInterop = this.noImportInteropPrefixesRegexp.test(src); 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 = src.replace(/\//g, '_').replace(/\./g, ''); // default to the src for import without named var let tmpName = noInterop ? name : tempModuleName(name); const imp = { src, name, isLib, isUi5Src, tmpName }; const destructors = []; for (const specifier of specifiers) { if (t.isImportDefaultSpecifier(specifier)) { imp.default = true; imp.interop = !noInterop; // Shorten the imported as name. The default import should always come first, // so this new name will be used for destructuring the other too. imp.name = specifier.local.name; tmpName = imp.tmpName = noInterop ? imp.name : tempModuleName(imp.name); if (!noInterop) { destructors.push(th.buildDefaultImportDestructor({ MODULE: t.identifier(imp.tmpName), LOCAL: specifier.local })); } } else if (t.isImportSpecifier(specifier)) { destructors.push(th.buildNamedImportDestructor({ MODULE: t.identifier(imp.tmpName), LOCAL: specifier.local, IMPORTED: t.stringLiteral(specifier.imported.name) })); } else Eif (t.isImportNamespaceSpecifier(specifier)) { destructors.push(th.buildConstDeclaration({ NAME: specifier.local, VALUE: t.identifier(imp.tmpName) })); } else { throw path.buildCodeFrameError(`Unknown ImportDeclaration specifier type ${ specifier.type }`); } } path.replaceWithMultiple(destructors); imp.path = path; 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) { // this.wrap = true const { node } = path; const { specifiers, declaration, source } = node; let fromSource = ''; if (source) { // export { one, two } from 'x' const src = source.value; const name = src.replace(/\//g, '_').replace(/\./g, ''); 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 = (0, _ast.getIdName)(declaration); if (name) { // export function f() {} const id = t.identifier(declaration.id.name); this.namedExports.push({ key: id, value: id }); } 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 }); } } 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 * visting ImportDeclaration. * Only a single 'export default' is supported. */ ExportDefaultDeclaration(path) { // this.wrap = true const { node } = path; const { declaration } = node; this.defaultExportDeclaration = declaration; const declarationName = (0, _ast.getIdName)(declaration); if (hasGlobalExportFlag(node)) { // check for @export jsdoc 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 Iif (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 = (0, _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 = (0, _ast.groupPropertiesByName)((0, _ast.getOtherPropertiesOfIdentifier)(blockParent, name)); // TODO flag metadata and renderer for removal if applicable const ui5ExtendClass = (0, _classes.convertClassToUI5Extend)(node, classInfo, staticProps); 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 (t.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 ((0, _classes.isSAPUIDefineCallExpression)(node)) { 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; const CONSTRUCTOR = 'constructor'; 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) { node.arguments.unshift(t.identifier('this')); path.replaceWith(t.callExpression(t.identifier(`${ superClassName }.prototype.constructor.call`), node.arguments)); } /** * Replace super.method() call */ function replaceObjectSuperCall(path, node, superClassName) { node.arguments.unshift(t.identifier('this')); const callIdentifier = t.identifier(`${ superClassName }.prototype.${ node.callee.property.name }.call`); path.replaceWith(t.callExpression(callIdentifier, node.arguments)); } function doesClassExtendFromImport(node, imports) { const superClass = node.superClass; if (!superClass) { return false; } const isImported = imports.some(imported => imported.name === superClass.name); return isImported; } function generateDefine(body, imports, exportGlobal) { const defineOpts = { SOURCES: imports.map(i => t.stringLiteral(i.src)), PARAMS: imports.map(i => t.identifier(i.tmpName)), BODY: body }; return exportGlobal ? th.buildDefineGlobal(defineOpts) : th.buildDefine(defineOpts); } function hasGlobalExportFlag(node) { return (0, _jsdoc.hasJsdocGlobalExportFlag)(node); } return { visitor: ProgramVisitor }; }; |