Skip to content

Commit

Permalink
Stop requiring setupBabel from within packager/ folder.
Browse files Browse the repository at this point in the history
Reviewed By: davidaurelio

Differential Revision: D5137246

fbshipit-source-id: 3072aaa6fd74a135980f1f0a7b078a82dd85f09d
  • Loading branch information
cpojer authored and facebook-github-bot committed May 30, 2017
1 parent cfe0032 commit 414da08
Show file tree
Hide file tree
Showing 19 changed files with 225 additions and 210 deletions.
1 change: 1 addition & 0 deletions local-cli/bundle/buildBundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ function buildBundle(
transformCache: TransformCaching.useTempDir(),
transformModulePath: transformModulePath,
watch: false,
workerPath: config.getWorkerPath && config.getWorkerPath(),
};

packagerInstance = new Server(options);
Expand Down
1 change: 1 addition & 0 deletions local-cli/server/runServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ function getPackagerServer(args, config) {
transformModulePath: transformModulePath,
verbose: args.verbose,
watch: !args.nonPersistent,
workerPath: config.getWorkerPath(),
});
}

Expand Down
6 changes: 6 additions & 0 deletions local-cli/util/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ export type ConfigT = {
getTransformModulePath: () => string,
getTransformOptions: GetTransformOptions,

/**
* Returns the path to the worker that is used for transformation.
*/
getWorkerPath: () => string,

/**
* An optional function that can modify the code and source map of bundle
* after the minifaction took place.
Expand Down Expand Up @@ -121,6 +126,7 @@ const defaultConfig: ConfigT = {
postProcessModules: modules => modules,
postProcessModulesForBuck: modules => modules,
transformVariants: () => ({default: {}}),
getWorkerPath: () => require.resolve('./worker.js'),
};

/**
Expand Down
13 changes: 13 additions & 0 deletions local-cli/util/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

'use strict';

require('../../setupBabel')();
module.exports = require('../../packager/src/JSTransformer/worker');
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"Libraries/Renderer",
"/node_modules/",
"/website/",
"local-cli/templates/"
"local-cli/templates/",
"packager/integration_tests/__tests__/basic_bundle-test.js"
],
"haste": {
"defaultPlatform": "ios",
Expand Down
1 change: 1 addition & 0 deletions packager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type Options = {
+transformCache: TransformCache,
+transformModulePath: string,
watch?: boolean,
workerPath: ?string,
};

type StrictOptions = {...Options, reporter: Reporter};
Expand Down
8 changes: 5 additions & 3 deletions packager/src/Bundler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import type AssetServer from '../AssetServer';
import type Module, {HasteImpl} from '../node-haste/Module';
import type ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse';
import type {MappingsMap} from '../lib/SourceMap';
import type {Options as JSTransformerOptions} from '../JSTransformer/worker/worker';
import type {Options as JSTransformerOptions} from '../JSTransformer/worker';
import type {Reporter} from '../lib/reporting';
import type {TransformCache} from '../lib/TransformCaching';
import type {GlobalTransformCache} from '../lib/GlobalTransformCache';
Expand Down Expand Up @@ -126,8 +126,8 @@ type Options = {|
+hasteImpl?: HasteImpl,
+platforms: Array<string>,
+polyfillModuleNames: Array<string>,
+postProcessModules?: PostProcessModules,
+postMinifyProcess: PostMinifyProcess,
+postProcessModules?: PostProcessModules,
+projectRoots: $ReadOnlyArray<string>,
+providesModuleNodeModules?: Array<string>,
+reporter: Reporter,
Expand All @@ -137,6 +137,7 @@ type Options = {|
+transformModulePath: string,
+transformTimeoutInterval: ?number,
+watch: boolean,
+workerPath: ?string,
|};

const {hasOwnProperty} = Object;
Expand Down Expand Up @@ -197,7 +198,8 @@ class Bundler {
{
stdoutChunk: chunk => opts.reporter.update({type: 'worker_stdout_chunk', chunk}),
stderrChunk: chunk => opts.reporter.update({type: 'worker_stderr_chunk', chunk}),
}
},
opts.workerPath,
);

const getTransformCacheKey = options => {
Expand Down
7 changes: 4 additions & 3 deletions packager/src/JSTransformer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ const path = require('path');
const util = require('util');
const workerFarm = require('../worker-farm');

import type {Data as TransformData, Options as WorkerOptions} from './worker/worker';
import type {Data as TransformData, Options as WorkerOptions} from './worker';
import type {LocalPath} from '../node-haste/lib/toLocalPath';
import type {MappingsMap} from '../lib/SourceMap';
import typeof {minify as Minify, transformAndExtractDependencies as TransformAndExtractDependencies} from './worker/worker';
import typeof {minify as Minify, transformAndExtractDependencies as TransformAndExtractDependencies} from './worker';

type CB<T> = (?Error, ?T) => mixed;
type Denodeify =
Expand Down Expand Up @@ -83,12 +83,13 @@ class Transformer {
transformModulePath: string,
maxWorkerCount: number,
reporters: Reporters,
workerPath: ?string,
) {
invariant(path.isAbsolute(transformModulePath), 'transform module path should be absolute');
this._transformModulePath = transformModulePath;

const farm = makeFarm(
require.resolve('./worker'),
workerPath || require.resolve('./worker'),
['minify', 'transformAndExtractDependencies'],
TRANSFORM_TIMEOUT_INTERVAL,
maxWorkerCount,
Expand Down
182 changes: 180 additions & 2 deletions packager/src/JSTransformer/worker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,187 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/

'use strict';

require('../../../../setupBabel')();
module.exports = require('./worker');
const babelRegisterOnly = require('../../../babelRegisterOnly');
const constantFolding = require('./constant-folding');
const extractDependencies = require('./extract-dependencies');
const inline = require('./inline');
const invariant = require('fbjs/lib/invariant');
const minify = require('./minify');

import type {LogEntry} from '../../Logger/Types';
import type {MappingsMap} from '../../lib/SourceMap';
import type {LocalPath} from '../../node-haste/lib/toLocalPath';
import type {Ast, Plugins as BabelPlugins} from 'babel-core';

export type TransformedCode = {
code: string,
dependencies: Array<string>,
dependencyOffsets: Array<number>,
map?: ?MappingsMap,
};

export type Transformer<ExtraOptions: {} = {}> = {
transform: ({|
filename: string,
localPath: string,
options: ExtraOptions & TransformOptions,
plugins?: BabelPlugins,
src: string,
|}) => {ast: ?Ast, code: string, map: ?MappingsMap},
getCacheKey: () => string,
};


export type TransformOptionsStrict = {|
+dev: boolean,
+generateSourceMaps: boolean,
+hot: boolean,
+inlineRequires: {+blacklist: {[string]: true}} | boolean,
+platform: ?string,
+projectRoot: string,
|};

export type TransformOptions = {
+dev?: boolean,
+generateSourceMaps?: boolean,
+hot?: boolean,
+inlineRequires?: {+blacklist: {[string]: true}} | boolean,
+platform: ?string,
+projectRoot: string,
};

export type Options = {|
+dev: boolean,
+minify: boolean,
+platform: ?string,
+transform: TransformOptionsStrict,
|};

export type Data = {
result: TransformedCode,
transformFileStartLogEntry: LogEntry,
transformFileEndLogEntry: LogEntry,
};

type Callback<T> = (
error: ?Error,
data: ?T,
) => mixed;

function transformCode(
transformer: Transformer<*>,
filename: string,
localPath: LocalPath,
sourceCode: string,
options: Options,
callback: Callback<Data>,
) {
invariant(
!options.minify || options.transform.generateSourceMaps,
'Minifying source code requires the `generateSourceMaps` option to be `true`',
);

const isJson = filename.endsWith('.json');
if (isJson) {
sourceCode = 'module.exports=' + sourceCode;
}

const transformFileStartLogEntry = {
action_name: 'Transforming file',
action_phase: 'start',
file_name: filename,
log_entry_label: 'Transforming file',
start_timestamp: process.hrtime(),
};

let transformed;
try {
transformed = transformer.transform({
filename,
localPath,
options: options.transform,
src: sourceCode,
});
} catch (error) {
callback(error);
return;
}

invariant(
transformed != null,
'Missing transform results despite having no error.',
);

var code, map;
if (options.minify) {
({code, map} =
constantFolding(filename, inline(filename, transformed, options)));
invariant(code != null, 'Missing code from constant-folding transform.');
} else {
({code, map} = transformed);
}

if (isJson) {
code = code.replace(/^\w+\.exports=/, '');
} else {
// Remove shebang
code = code.replace(/^#!.*/, '');
}

const depsResult = isJson
? {dependencies: [], dependencyOffsets: []}
: extractDependencies(code);

const timeDelta = process.hrtime(transformFileStartLogEntry.start_timestamp);
const duration_ms = Math.round((timeDelta[0] * 1e9 + timeDelta[1]) / 1e6);
const transformFileEndLogEntry = {
action_name: 'Transforming file',
action_phase: 'end',
file_name: filename,
duration_ms,
log_entry_label: 'Transforming file',
};

callback(null, {
result: {...depsResult, code, map},
transformFileStartLogEntry,
transformFileEndLogEntry,
});
}

exports.transformAndExtractDependencies = (
transform: string,
filename: string,
localPath: LocalPath,
sourceCode: string,
options: Options,
callback: Callback<Data>,
) => {
babelRegisterOnly([transform]);
/* $FlowFixMe: impossible to type a dynamic require */
const transformModule: Transformer<*> = require(transform);
transformCode(transformModule, filename, localPath, sourceCode, options, callback);
};

exports.minify = (
filename: string,
code: string,
sourceMap: MappingsMap,
callback: Callback<{code: string, map: MappingsMap}>,
) => {
var result;
try {
result = minify(filename, code, sourceMap);
} catch (error) {
callback(error);
}
callback(null, result);
};

exports.transformCode = transformCode; // for easier testing
Loading

0 comments on commit 414da08

Please sign in to comment.