Skip to content

Commit

Permalink
feat(compiler): expose transformSync method (#1174)
Browse files Browse the repository at this point in the history
* feat(compiler): add transform sync

* chore: remove deasync from jest

* chore: add tests for new API

* fix: fix typo in the test name
  • Loading branch information
pmdartus authored Apr 16, 2019
1 parent 7c5f264 commit ebeb23a
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 102 deletions.
3 changes: 2 additions & 1 deletion packages/@lwc/compiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
export { compile } from './compiler/compiler';
export { transform } from './transformers/transformer';
export { transform, transformSync } from './transformers/transformer';

export const version = '__VERSION__';
7 changes: 3 additions & 4 deletions packages/@lwc/compiler/src/rollup-plugins/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { Plugin } from 'rollup';

import { getTransformer, FileTransformerResult } from '../transformers/transformer';
import { transformFile } from '../transformers/transformer';

import { NormalizedCompilerOptions } from '../compiler/options';
import { MetadataCollector } from '../bundler/meta-collector';
Expand All @@ -20,9 +20,8 @@ export default function({
}): Plugin {
return {
name: 'lwc-file-transform',
async transform(src: string, id: string): Promise<FileTransformerResult> {
const transform = getTransformer(id);
return await transform(src, id, options, metadataCollector);
transform(src: string, id: string) {
return transformFile(src, id, options, metadataCollector);
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,37 @@
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import { transform } from '../../transformers/transformer';
import { transform, transformSync } from '../../transformers/transformer';

const transformEntry: any = transform;
function testValidateOptions(methodName, method) {
describe('validate options', () => {
it(`${methodName} should validate presence of src`, () => {
expect(() => method()).toThrow(/Expect a string for source. Received undefined/);
});

it('should validate presence of src', () => {
expect(() => transformEntry()).toThrow(/Expect a string for source. Received undefined/);
it(`${methodName} should validate presence of filename`, () => {
expect(() => method(`console.log('Hello')`)).toThrow(
/Expect a string for id. Received undefined/
);
});
});
}

testValidateOptions('transform', transform);
testValidateOptions('transformSync', transformSync);

describe('transform', () => {
it('returns a promise resolving to an object with code', () => {
expect(transform(`console.log('Hello')`, 'foo.js', {})).resolves.toMatchObject({
code: expect.any(String),
});
});
});

it('should validate presence of id', () => {
expect(() => transformEntry(`console.log('Hello')`)).toThrow(
/Expect a string for id. Received undefined/
);
describe('transformSync', () => {
it('returns to an object with code', () => {
expect(transformSync(`console.log('Hello')`, 'foo.js', {})).toMatchObject({
code: expect.any(String),
});
});
});
2 changes: 1 addition & 1 deletion packages/@lwc/compiler/src/transformers/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { BABEL_CONFIG_BASE, BABEL_PLUGINS_BASE } from '../babel-plugins';
import { NormalizedCompilerOptions } from '../compiler/options';
import { FileTransformerResult } from './transformer';

export default function(
export default function scriptTransform(
code: string,
filename: string,
options: NormalizedCompilerOptions
Expand Down
2 changes: 1 addition & 1 deletion packages/@lwc/compiler/src/transformers/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { normalizeToCompilerError, TransformerErrors } from '@lwc/errors';
import { NormalizedCompilerOptions } from '../compiler/options';
import { FileTransformerResult } from './transformer';

export default function transformStyle(
export default function styleTransform(
src: string,
filename: string,
config: NormalizedCompilerOptions
Expand Down
7 changes: 2 additions & 5 deletions packages/@lwc/compiler/src/transformers/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
import compile from '@lwc/template-compiler';
import { TemplateModuleDependency } from '@lwc/template-compiler';

import { FileTransformer } from './transformer';
import { MetadataCollector } from '../bundler/meta-collector';
import { NormalizedCompilerOptions } from '../compiler/options';

Expand All @@ -31,7 +30,7 @@ export interface TemplateMetadata {
* The transform also add a style import for the default stylesheet associated with
* the template regardless if there is an actual style or not.
*/
const transform: FileTransformer = function(
export default function templateTransform(
src: string,
filename: string,
options: NormalizedCompilerOptions,
Expand Down Expand Up @@ -67,7 +66,7 @@ const transform: FileTransformer = function(
map: { mappings: '' },
metadata,
};
};
}

function serialize(
code: string,
Expand All @@ -94,5 +93,3 @@ function serialize(

return buffer;
}

export default transform;
82 changes: 54 additions & 28 deletions packages/@lwc/compiler/src/transformers/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,60 +11,86 @@ import { NormalizedCompilerOptions, CompilerOptions, normalizeOptions } from '..

import styleTransform from './style';
import templateTransformer, { TemplateMetadata } from './template';
import javascriptTransformer from './javascript';
import scriptTransformer from './javascript';

import { isString } from '../utils';
import { MetadataCollector } from '../bundler/meta-collector';
import { SourceMap } from '../compiler/compiler';

// TODO: Improve on metadata type by providing consistent interface. Currently
// javascript transformer output differs from css and html in that later return a promise
export interface FileTransformerResult {
code: string;
metadata?: TemplateMetadata;
map: SourceMap | null;
}

export type FileTransformer = (
source: string,
/**
* Transforms the passed code. Returning a Promise of an object with the generated code, source map
* and gathered metadata.
*
* @deprecated Use transformSync instead.
*/
export function transform(
src: string,
filename: string,
options: NormalizedCompilerOptions,
metadataCollector?: MetadataCollector
) => FileTransformerResult | Promise<FileTransformerResult>;
options: CompilerOptions
): Promise<FileTransformerResult> {
validateArguments(src, filename);
return new Promise((resolve, reject) => {
try {
const res = transformSync(src, filename, options);
resolve(res);
} catch (error) {
reject(error);
}
});
}

export function transform(src: string, id: string, options: CompilerOptions) {
invariant(isString(src), TransformerErrors.INVALID_SOURCE, [src]);
invariant(isString(id), TransformerErrors.INVALID_ID, [id]);
/**
* Transform the passed source code. Returning an object with the generated code, source map and
* gathered metadata.
*/
export function transformSync(
src: string,
filename: string,
options: CompilerOptions
): FileTransformerResult {
validateArguments(src, filename);
return transformFile(src, filename, normalizeOptions(options));
}

return transformFile(src, id, normalizeOptions(options));
function validateArguments(src: string, filename: string) {
invariant(isString(src), TransformerErrors.INVALID_SOURCE, [src]);
invariant(isString(filename), TransformerErrors.INVALID_ID, [filename]);
}

export function getTransformer(fileName: string): FileTransformer {
switch (path.extname(fileName)) {
export function transformFile(
src: string,
filename: string,
options: NormalizedCompilerOptions,
metadataCollector?: MetadataCollector
): FileTransformerResult {
let transformer;

switch (path.extname(filename)) {
case '.html':
return templateTransformer;
transformer = templateTransformer;
break;

case '.css':
return styleTransform;
transformer = styleTransform;
break;

case '.ts':
case '.js':
return javascriptTransformer;
transformer = scriptTransformer;
break;

default:
throw generateCompilerError(TransformerErrors.NO_AVAILABLE_TRANSFORMER, {
messageArgs: [fileName],
origin: { filename: fileName },
messageArgs: [filename],
origin: { filename },
});
}
}

export async function transformFile(
src: string,
id: string,
options: NormalizedCompilerOptions,
metadataCollector?: MetadataCollector
): Promise<FileTransformerResult> {
const transformer = getTransformer(id);
return await transformer(src, id, options, metadataCollector);
return transformer(src, filename, options, metadataCollector);
}
3 changes: 1 addition & 2 deletions packages/@lwc/jest-transformer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
"@babel/plugin-transform-modules-commonjs": "7.1.0",
"@babel/template": "~7.1.2",
"@lwc/errors": "0.37.2",
"babel-preset-jest": "^24.0.0",
"deasync": "0.1.14"
"babel-preset-jest": "^24.0.0"
},
"peerDependencies": {
"@lwc/compiler": "0.37.x",
Expand Down
14 changes: 7 additions & 7 deletions packages/@lwc/jest-transformer/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
const crypto = require('crypto');
const path = require('path');
const crypto = require('crypto');

const babelCore = require('@babel/core');
const babelCommonJs = require('@babel/plugin-transform-modules-commonjs');
const jestPreset = require('babel-preset-jest');
const lwcCompiler = require('@lwc/compiler');
const jestPreset = require('babel-preset-jest');
const babelCommonJs = require('@babel/plugin-transform-modules-commonjs');

const engineVersion = require('@lwc/engine/package.json').version;
const compilerVersion = require('@lwc/compiler/package.json').version;
const { waitForPromise } = require('./utils');

const apexScopedImport = require('./transforms/apex-scoped-import');
const apexContinuationScopedImport = require('./transforms/apex-continuation-scoped-import');
const i18nScopedImport = require('./transforms/i18n-scoped-import');
Expand Down Expand Up @@ -41,16 +43,14 @@ const BABEL_CONFIG = {
module.exports = {
process(src, filePath) {
// Set default module name and namespace value for the namespace because it can't be properly guessed from the path
const transform = lwcCompiler.transform(src, filePath, {
const { code, map } = lwcCompiler.transformSync(src, filePath, {
moduleName: 'test',
moduleNamespace: 'x',
outputConfig: {
sourcemap: true,
},
});

const { code, map } = waitForPromise(transform);

// if is not .js, we add the .compiled extension in the sourcemap
const filename = path.extname(filePath) === '.js' ? filePath : filePath + '.compiled';
// **Note: .html and .css don't return valid sourcemaps cause they are used for rollup
Expand Down
27 changes: 0 additions & 27 deletions packages/@lwc/jest-transformer/src/utils.js

This file was deleted.

18 changes: 0 additions & 18 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2261,11 +2261,6 @@ binary-extensions@^1.0.0:
resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.12.0.tgz#c2d780f53d45bba8317a8902d4ceeaf3a6385b14"
integrity sha512-DYWGk01lDcxeS/K9IHPGWfT8PsJmbXRtRd2Sx72Tnb8pcYZQFF1oSDb8hJtS1vhp212q1Rzi5dUf9+nq0o9UIg==

bindings@~1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.2.1.tgz#14ad6113812d2d37d72e67b4cacb4bb726505f11"
integrity sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=

bl@^1.0.0:
version "1.2.2"
resolved "https://registry.yarnpkg.com/bl/-/bl-1.2.2.tgz#a160911717103c07410cef63ef51b397c025af9c"
Expand Down Expand Up @@ -3586,14 +3581,6 @@ dateformat@^3.0.0:
resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae"
integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==

[email protected]:
version "0.1.14"
resolved "https://registry.yarnpkg.com/deasync/-/deasync-0.1.14.tgz#232ea2252b443948cad033d792eb3b24b0a3d828"
integrity sha512-wN8sIuEqIwyQh72AG7oY6YQODCxIp1eXzEZlZznBuwDF8Q03Tdy9QNp1BNZXeadXoklNrw+Ip1fch+KXo/+ASw==
dependencies:
bindings "~1.2.1"
node-addon-api "^1.6.0"

[email protected], debug@^2.1.2, debug@^2.2.0, debug@^2.3.3, debug@~2.6.4:
version "2.6.9"
resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
Expand Down Expand Up @@ -7886,11 +7873,6 @@ nice-try@^1.0.4:
resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"
integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==

node-addon-api@^1.6.0:
version "1.6.2"
resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-1.6.2.tgz#d8aad9781a5cfc4132cc2fecdbdd982534265217"
integrity sha512-479Bjw9nTE5DdBSZZWprFryHGjUaQC31y1wHo19We/k0BZlrmhqQitWoUL0cD8+scljCbIUL+E58oRDEakdGGA==

node-fetch-npm@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/node-fetch-npm/-/node-fetch-npm-2.0.2.tgz#7258c9046182dca345b4208eda918daf33697ff7"
Expand Down

0 comments on commit ebeb23a

Please sign in to comment.