|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0 and the Server Side Public License, v 1; you may not use this file except |
| 5 | + * in compliance with, at your election, the Elastic License 2.0 or the Server |
| 6 | + * Side Public License, v 1. |
| 7 | + */ |
| 8 | + |
| 9 | +const t = require('@babel/types'); |
| 10 | +const { default: generate } = require('@babel/generator'); |
| 11 | + |
| 12 | +/** @typedef {import('./export_set').ExportSet} ExportSet */ |
| 13 | + |
| 14 | +/** |
| 15 | + * Generate code for replacing a `export * from './path'`, ie. |
| 16 | + * |
| 17 | + * export type { foo } from './path' |
| 18 | + * export { bar } from './path' |
| 19 | +
|
| 20 | + * @param {ExportSet} exportSet |
| 21 | + * @param {string} source |
| 22 | + */ |
| 23 | +const getExportCode = (exportSet, source) => { |
| 24 | + const exportedTypes = exportSet.types.size |
| 25 | + ? t.exportNamedDeclaration( |
| 26 | + undefined, |
| 27 | + Array.from(exportSet.types).map((n) => t.exportSpecifier(t.identifier(n), t.identifier(n))), |
| 28 | + t.stringLiteral(source) |
| 29 | + ) |
| 30 | + : undefined; |
| 31 | + |
| 32 | + if (exportedTypes) { |
| 33 | + exportedTypes.exportKind = 'type'; |
| 34 | + } |
| 35 | + |
| 36 | + const exportedValues = exportSet.values.size |
| 37 | + ? t.exportNamedDeclaration( |
| 38 | + undefined, |
| 39 | + Array.from(exportSet.values).map((n) => |
| 40 | + t.exportSpecifier(t.identifier(n), t.identifier(n)) |
| 41 | + ), |
| 42 | + t.stringLiteral(source) |
| 43 | + ) |
| 44 | + : undefined; |
| 45 | + |
| 46 | + return generate(t.program([exportedTypes, exportedValues].filter(Boolean))).code; |
| 47 | +}; |
| 48 | + |
| 49 | +/** |
| 50 | + * Generate code for replacing a `export * as name from './path'`, ie. |
| 51 | + * |
| 52 | + * import { foo, bar } from './path' |
| 53 | + * export const name = { foo, bar } |
| 54 | + * |
| 55 | + * @param {string} nsName |
| 56 | + * @param {string[]} exportNames |
| 57 | + * @param {string} source |
| 58 | + */ |
| 59 | +const getExportNamedNamespaceCode = (nsName, exportNames, source) => { |
| 60 | + return generate( |
| 61 | + t.program([ |
| 62 | + t.importDeclaration( |
| 63 | + exportNames.map((n) => t.importSpecifier(t.identifier(n), t.identifier(n))), |
| 64 | + t.stringLiteral(source) |
| 65 | + ), |
| 66 | + t.exportNamedDeclaration( |
| 67 | + t.variableDeclaration('const', [ |
| 68 | + t.variableDeclarator( |
| 69 | + t.identifier(nsName), |
| 70 | + t.objectExpression( |
| 71 | + exportNames.map((n) => |
| 72 | + t.objectProperty(t.identifier(n), t.identifier(n), false, true) |
| 73 | + ) |
| 74 | + ) |
| 75 | + ), |
| 76 | + ]) |
| 77 | + ), |
| 78 | + ]) |
| 79 | + ).code; |
| 80 | +}; |
| 81 | + |
| 82 | +module.exports = { getExportCode, getExportNamedNamespaceCode }; |
0 commit comments