flow like the river

This commit is contained in:
root 2025-11-07 00:06:12 +01:00
commit 013fe673f3
42435 changed files with 5764238 additions and 0 deletions

View file

@ -0,0 +1,149 @@
'use strict';
const types = require('babel-types');
const template = require('babel-template');
const traverse = require('babel-traverse').default;
const urlJoin = require('../utils/urlJoin');
const isURL = require('../utils/is-url');
const matchesPattern = require('./matches-pattern');
const requireTemplate = template('require("_bundle_loader")');
const argTemplate = template('require.resolve(MODULE)');
const serviceWorkerPattern = ['navigator', 'serviceWorker', 'register'];
module.exports = {
ImportDeclaration(node, asset) {
asset.isES6Module = true;
addDependency(asset, node.source);
},
ExportNamedDeclaration(node, asset) {
asset.isES6Module = true;
if (node.source) {
addDependency(asset, node.source);
}
},
ExportAllDeclaration(node, asset) {
asset.isES6Module = true;
addDependency(asset, node.source);
},
ExportDefaultDeclaration(node, asset) {
asset.isES6Module = true;
},
CallExpression(node, asset, ancestors) {
let callee = node.callee,
args = node.arguments;
let isRequire = types.isIdentifier(callee) && callee.name === 'require' && args.length === 1 && types.isStringLiteral(args[0]) && !hasBinding(ancestors, 'require') && !isInFalsyBranch(ancestors);
if (isRequire) {
let optional = ancestors.some(a => types.isTryStatement(a)) || undefined;
addDependency(asset, args[0], { optional });
return;
}
let isDynamicImport = callee.type === 'Import' && args.length === 1 && types.isStringLiteral(args[0]);
if (isDynamicImport) {
asset.addDependency('_bundle_loader');
addDependency(asset, args[0], { dynamic: true });
node.callee = requireTemplate().expression;
node.arguments[0] = argTemplate({ MODULE: args[0] }).expression;
asset.isAstDirty = true;
return;
}
const isRegisterServiceWorker = types.isStringLiteral(args[0]) && matchesPattern(callee, serviceWorkerPattern);
if (isRegisterServiceWorker) {
// Treat service workers as an entry point so filenames remain consistent across builds.
// https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#avoid_changing_the_url_of_your_service_worker_script
addURLDependency(asset, args[0], { entry: true });
return;
}
},
NewExpression(node, asset) {
const callee = node.callee,
args = node.arguments;
const isWebWorker = callee.type === 'Identifier' && callee.name === 'Worker' && args.length === 1 && types.isStringLiteral(args[0]);
if (isWebWorker) {
addURLDependency(asset, args[0]);
return;
}
}
};
function hasBinding(node, name) {
if (Array.isArray(node)) {
return node.some(ancestor => hasBinding(ancestor, name));
} else if (types.isProgram(node) || types.isBlockStatement(node) || types.isBlock(node)) {
return node.body.some(statement => hasBinding(statement, name));
} else if (types.isFunctionDeclaration(node) || types.isFunctionExpression(node) || types.isArrowFunctionExpression(node)) {
return node.id !== null && node.id.name === name || node.params.some(param => types.isIdentifier(param) && param.name === name);
} else if (types.isVariableDeclaration(node)) {
return node.declarations.some(declaration => declaration.id.name === name);
}
return false;
}
function isInFalsyBranch(ancestors) {
// Check if any ancestors are if statements
return ancestors.some((node, index) => {
if (types.isIfStatement(node)) {
let res = evaluateExpression(node.test);
if (res && res.confident) {
// If the test is truthy, exclude the dep if it is in the alternate branch.
// If the test if falsy, exclude the dep if it is in the consequent branch.
let child = ancestors[index + 1];
return res.value ? child === node.alternate : child === node.consequent;
}
}
});
}
function evaluateExpression(node) {
// Wrap the node in a standalone program so we can traverse it
node = types.file(types.program([types.expressionStatement(node)]));
// Find the first expression and evaluate it.
let res = null;
traverse(node, {
Expression(path) {
res = path.evaluate();
path.stop();
}
});
return res;
}
function addDependency(asset, node, opts = {}) {
if (asset.options.target !== 'browser') {
const isRelativeImport = /^[/~.]/.test(node.value);
if (!isRelativeImport) return;
}
opts.loc = node.loc && node.loc.start;
asset.addDependency(node.value, opts);
}
function addURLDependency(asset, node, opts = {}) {
opts.loc = node.loc && node.loc.start;
let assetPath = asset.addURLDependency(node.value, opts);
if (!isURL(assetPath)) {
assetPath = urlJoin(asset.options.publicURL, assetPath);
}
node.value = assetPath;
asset.isAstDirty = true;
}

View file

@ -0,0 +1,30 @@
'use strict';
const types = require('babel-types');
const matchesPattern = require('./matches-pattern');
module.exports = {
MemberExpression(node, asset) {
// Inline environment variables accessed on process.env
if (matchesPattern(node.object, 'process.env')) {
let key = types.toComputedKey(node);
if (types.isStringLiteral(key)) {
let val = types.valueToNode(process.env[key.value]);
morph(node, val);
asset.isAstDirty = true;
asset.cacheData.env[key.value] = process.env[key.value];
}
}
}
};
// replace object properties
function morph(object, newProperties) {
for (let key in object) {
delete object[key];
}
for (let key in newProperties) {
object[key] = newProperties[key];
}
}

196
VISUALIZACION/node_modules/parcel-bundler/lib/visitors/fs.js generated vendored Executable file
View file

@ -0,0 +1,196 @@
'use strict';
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
const t = require('babel-types');
const Path = require('path');
const fs = require('fs');
const template = require('babel-template');
const logger = require('../Logger');
const bufferTemplate = template('Buffer(CONTENT, ENC)');
module.exports = {
AssignmentExpression(path) {
if (!isRequire(path.node.right, 'fs', 'readFileSync')) {
return;
}
for (let name in path.getBindingIdentifiers()) {
const binding = path.scope.getBinding(name);
if (!binding) continue;
binding.path.setData('__require', path.node);
}
},
CallExpression(path, asset) {
// See https://github.com/defunctzombie/node-browser-resolve#skip
let ignore = asset.package && asset.package.browser && asset.package.browser.fs === false;
if (!ignore && referencesImport(path, 'fs', 'readFileSync')) {
let vars = {
__dirname: Path.dirname(asset.name),
__filename: asset.basename
};
let filename, args, res;
try {
var _path$get$map = path.get('arguments').map(arg => evaluate(arg, vars));
var _path$get$map2 = _toArray(_path$get$map);
filename = _path$get$map2[0];
args = _path$get$map2.slice(1);
filename = Path.resolve(filename);
res = fs.readFileSync(filename, ...args);
} catch (err) {
if (err instanceof NodeNotEvaluatedError) {
// Warn using a code frame
err.fileName = asset.name;
asset.generateErrorMessage(err);
logger.warn(err);
return;
}
// Add location info so we log a code frame with the error
err.loc = path.node.arguments.length > 0 ? path.node.arguments[0].loc.start : path.node.loc.start;
throw err;
}
let replacementNode;
if (Buffer.isBuffer(res)) {
replacementNode = bufferTemplate({
CONTENT: t.stringLiteral(res.toString('base64')),
ENC: t.stringLiteral('base64')
});
} else {
replacementNode = t.stringLiteral(res);
}
asset.addDependency(filename, { includedInParent: true });
path.replaceWith(replacementNode);
asset.isAstDirty = true;
}
}
};
function isRequire(node, name, method) {
// e.g. require('fs').readFileSync
if (t.isMemberExpression(node) && node.property.name === method) {
node = node.object;
}
if (!t.isCallExpression(node)) {
return false;
}
var _node = node;
let callee = _node.callee,
args = _node.arguments;
let isRequire = t.isIdentifier(callee) && callee.name === 'require' && args.length === 1 && t.isStringLiteral(args[0]);
if (!isRequire) {
return false;
}
if (name && args[0].value !== name) {
return false;
}
return true;
}
function referencesImport(path, name, method) {
let callee = path.node.callee;
let bindingPath;
// e.g. readFileSync()
if (t.isIdentifier(callee)) {
bindingPath = getBindingPath(path, callee.name);
} else if (t.isMemberExpression(callee)) {
if (callee.property.name !== method) {
return false;
}
// e.g. fs.readFileSync()
if (t.isIdentifier(callee.object)) {
bindingPath = getBindingPath(path, callee.object.name);
// require('fs').readFileSync()
} else if (isRequire(callee.object, name)) {
return true;
}
} else {
return false;
}
if (!bindingPath) {
return;
}
let bindingNode = bindingPath.getData('__require') || bindingPath.node;
let parent = bindingPath.parentPath;
// e.g. import fs from 'fs';
if (parent.isImportDeclaration()) {
if (bindingPath.isImportSpecifier() && bindingPath.node.imported.name !== method) {
return false;
}
return parent.node.source.value === name;
// e.g. var fs = require('fs');
} else if (t.isVariableDeclarator(bindingNode) || t.isAssignmentExpression(bindingNode)) {
let left = bindingNode.id || bindingNode.left;
let right = bindingNode.init || bindingNode.right;
// e.g. var {readFileSync} = require('fs');
if (t.isObjectPattern(left)) {
let prop = left.properties.find(p => p.value.name === callee.name);
if (!prop || prop.key.name !== method) {
return false;
}
} else if (!t.isIdentifier(left)) {
return false;
}
return isRequire(right, name, method);
}
return false;
}
function getBindingPath(path, name) {
let binding = path.scope.getBinding(name);
return binding && binding.path;
}
function NodeNotEvaluatedError(node) {
this.message = 'Cannot statically evaluate fs argument';
this.node = node;
this.loc = node.loc.start;
}
function evaluate(path, vars) {
// Inline variables
path.traverse({
Identifier: function Identifier(ident) {
let key = ident.node.name;
if (key in vars) {
ident.replaceWith(t.valueToNode(vars[key]));
}
}
});
let res = path.evaluate();
if (!res.confident) {
throw new NodeNotEvaluatedError(path.node);
}
return res.value;
}

View file

@ -0,0 +1,53 @@
'use strict';
const Path = require('path');
const types = require('babel-types');
const VARS = {
process: asset => {
asset.addDependency('process');
return 'var process = require("process");';
},
global: () => 'var global = arguments[3];',
__dirname: asset => `var __dirname = ${JSON.stringify(Path.dirname(asset.name))};`,
__filename: asset => `var __filename = ${JSON.stringify(asset.name)};`,
Buffer: asset => {
asset.addDependency('buffer');
return 'var Buffer = require("buffer").Buffer;';
},
// Prevent AMD defines from working when loading UMD bundles.
// Ideally the CommonJS check would come before the AMD check, but many
// existing modules do the checks the opposite way leading to modules
// not exporting anything to Parcel.
define: () => 'var define;'
};
module.exports = {
Identifier(node, asset, ancestors) {
let parent = ancestors[ancestors.length - 2];
if (VARS.hasOwnProperty(node.name) && !asset.globals.has(node.name) && types.isReferenced(node, parent)) {
asset.globals.set(node.name, VARS[node.name](asset));
}
},
Declaration(node, asset, ancestors) {
// If there is a global declaration of one of the variables, remove our declaration
let identifiers = types.getBindingIdentifiers(node);
for (let id in identifiers) {
if (VARS.hasOwnProperty(id) && !inScope(ancestors)) {
// Don't delete entirely, so we don't add it again when the declaration is referenced
asset.globals.set(id, '');
}
}
}
};
function inScope(ancestors) {
for (let i = ancestors.length - 2; i >= 0; i--) {
if (types.isScope(ancestors[i]) && !types.isProgram(ancestors[i])) {
return true;
}
}
return false;
}

View file

@ -0,0 +1,374 @@
'use strict';
const matchesPattern = require('./matches-pattern');
const t = require('babel-types');
const template = require('babel-template');
const WRAPPER_TEMPLATE = template(`
var NAME = (function () {
var exports = this;
var module = {exports: this};
BODY;
return module.exports;
}).call({});
`);
const EXPORT_ASSIGN_TEMPLATE = template('EXPORTS.NAME = LOCAL');
const REQUIRE_CALL_TEMPLATE = template('$parcel$require(ID, SOURCE)');
const TYPEOF = {
module: 'object',
require: 'function'
};
module.exports = {
Program: {
enter(path, asset) {
asset.cacheData.exports = {};
asset.cacheData.wildcards = [];
let shouldWrap = false;
path.traverse({
CallExpression(path) {
// If we see an `eval` call, wrap the module in a function.
// Otherwise, local variables accessed inside the eval won't work.
let callee = path.node.callee;
if (t.isIdentifier(callee) && callee.name === 'eval' && !path.scope.hasBinding('eval', true)) {
shouldWrap = true;
path.stop();
}
},
ReturnStatement(path) {
// Wrap in a function if we see a top-level return statement.
if (path.getFunctionParent().isProgram()) {
shouldWrap = true;
path.replaceWith(t.returnStatement(t.memberExpression(t.identifier('module'), t.identifier('exports'))));
path.stop();
}
},
ReferencedIdentifier(path) {
// We must wrap if `module` is referenced as a free identifier rather
// than a statically resolvable member expression.
if (path.node.name === 'module' && (!path.parentPath.isMemberExpression() || path.parent.computed) && !(path.parentPath.isUnaryExpression() && path.parent.operator === 'typeof') && !path.scope.hasBinding('module') && !path.scope.getData('shouldWrap')) {
shouldWrap = true;
path.stop();
}
}
});
path.scope.setData('shouldWrap', shouldWrap);
},
exit(path, asset) {
let scope = path.scope;
if (scope.getData('shouldWrap')) {
path.replaceWith(t.program([WRAPPER_TEMPLATE({
NAME: getExportsIdentifier(asset),
BODY: path.node.body
})]));
} else {
// Re-crawl scope so we are sure to have all bindings.
scope.crawl();
// Rename each binding in the top-level scope to something unique.
for (let name in scope.bindings) {
if (!name.startsWith('$' + asset.id)) {
let newName = '$' + asset.id + '$var$' + name;
scope.rename(name, newName);
}
}
}
path.stop();
asset.isAstDirty = true;
}
},
MemberExpression(path, asset) {
if (path.scope.hasBinding('module') || path.scope.getData('shouldWrap')) {
return;
}
if (matchesPattern(path.node, 'module.exports')) {
path.replaceWith(getExportsIdentifier(asset));
}
if (matchesPattern(path.node, 'module.id')) {
path.replaceWith(t.numericLiteral(asset.id));
}
if (matchesPattern(path.node, 'module.hot')) {
path.replaceWith(t.identifier('null'));
}
if (matchesPattern(path.node, 'module.bundle.modules')) {
path.replaceWith(t.memberExpression(t.identifier('require'), t.identifier('modules')));
}
},
ReferencedIdentifier(path, asset) {
if (path.node.name === 'exports' && !path.scope.hasBinding('exports') && !path.scope.getData('shouldWrap')) {
path.replaceWith(getExportsIdentifier(asset));
}
},
ThisExpression(path, asset) {
if (!path.scope.parent && !path.scope.getData('shouldWrap')) {
path.replaceWith(getExportsIdentifier(asset));
}
},
AssignmentExpression(path, asset) {
let left = path.node.left;
if (t.isIdentifier(left) && left.name === 'exports' && !path.scope.hasBinding('exports') && !path.scope.getData('shouldWrap')) {
path.get('left').replaceWith(getExportsIdentifier(asset));
}
},
UnaryExpression(path) {
// Replace `typeof module` with "object"
if (path.node.operator === 'typeof' && t.isIdentifier(path.node.argument) && TYPEOF[path.node.argument.name] && !path.scope.hasBinding(path.node.argument.name) && !path.scope.getData('shouldWrap')) {
path.replaceWith(t.stringLiteral(TYPEOF[path.node.argument.name]));
}
},
CallExpression(path, asset) {
var _path$node = path.node;
let callee = _path$node.callee,
args = _path$node.arguments;
let isRequire = t.isIdentifier(callee) && callee.name === 'require' && args.length === 1 && t.isStringLiteral(args[0]) && !path.scope.hasBinding('require');
if (isRequire) {
// Ignore require calls that were ignored earlier.
if (!asset.dependencies.has(args[0].value)) {
return;
}
// Generate a variable name based on the current asset id and the module name to require.
// This will be replaced by the final variable name of the resolved asset in the packager.
// path.replaceWith(getIdentifier(asset, 'require', args[0].value));
path.replaceWith(REQUIRE_CALL_TEMPLATE({
ID: t.numericLiteral(asset.id),
SOURCE: t.stringLiteral(args[0].value)
}));
}
let isRequireResolve = matchesPattern(callee, 'require.resolve') && args.length === 1 && t.isStringLiteral(args[0]) && !path.scope.hasBinding('require');
if (isRequireResolve) {
path.replaceWith(getIdentifier(asset, 'require_resolve', args[0].value));
}
},
ImportDeclaration(path, asset) {
// For each specifier, rename the local variables to point to the imported name.
// This will be replaced by the final variable name of the resolved asset in the packager.
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = path.node.specifiers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let specifier = _step.value;
if (t.isImportDefaultSpecifier(specifier)) {
path.scope.rename(specifier.local.name, getName(asset, 'import', path.node.source.value, 'default'));
} else if (t.isImportSpecifier(specifier)) {
path.scope.rename(specifier.local.name, getName(asset, 'import', path.node.source.value, specifier.imported.name));
} else if (t.isImportNamespaceSpecifier(specifier)) {
path.scope.rename(specifier.local.name, getName(asset, 'require', path.node.source.value));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
path.remove();
},
ExportDefaultDeclaration(path, asset) {
let declaration = path.node.declaration;
let identifier = getIdentifier(asset, 'export', 'default');
if (t.isIdentifier(declaration)) {
// Rename the variable being exported.
safeRename(path, declaration.name, identifier.name);
path.remove();
} else if (t.isExpression(declaration) || !declaration.id) {
// Declare a variable to hold the exported value.
path.replaceWith(t.variableDeclaration('var', [t.variableDeclarator(identifier, t.toExpression(declaration))]));
} else {
// Rename the declaration to the exported name.
safeRename(path, declaration.id.name, identifier.name);
path.replaceWith(declaration);
}
// Add assignment to exports object for namespace imports and commonjs.
if (path.scope.hasGlobal('module') || path.scope.hasGlobal('exports')) {
path.insertAfter(EXPORT_ASSIGN_TEMPLATE({
EXPORTS: getExportsIdentifier(asset),
NAME: t.identifier('default'),
LOCAL: identifier
}));
}
asset.cacheData.exports[identifier.name] = 'default';
// Mark the asset as an ES6 module, so we handle imports correctly in the packager.
asset.cacheData.isES6Module = true;
},
ExportNamedDeclaration(path, asset) {
var _path$node2 = path.node;
let declaration = _path$node2.declaration,
source = _path$node2.source,
specifiers = _path$node2.specifiers;
if (source) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = specifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
let specifier = _step2.value;
let local, exported;
if (t.isExportDefaultSpecifier(specifier)) {
local = getIdentifier(asset, 'import', source.value, 'default');
exported = specifier.exported;
} else if (t.isExportNamespaceSpecifier(specifier)) {
local = getIdentifier(asset, 'require', source.value);
exported = specifier.exported;
} else if (t.isExportSpecifier(specifier)) {
local = getIdentifier(asset, 'import', source.value, specifier.local.name);
exported = specifier.exported;
}
// Create a variable to re-export from the imported module.
path.insertAfter(t.variableDeclaration('var', [t.variableDeclarator(getIdentifier(asset, 'export', exported.name), local)]));
if (path.scope.hasGlobal('module') || path.scope.hasGlobal('exports')) {
path.insertAfter(EXPORT_ASSIGN_TEMPLATE({
EXPORTS: getExportsIdentifier(asset),
NAME: t.identifier(exported.name),
LOCAL: local
}));
}
asset.cacheData.exports[getName(asset, 'export', exported.name)] = exported.name;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
path.remove();
} else if (declaration) {
path.replaceWith(declaration);
let identifiers = t.getBindingIdentifiers(declaration);
for (let id in identifiers) {
addExport(asset, path, identifiers[id], identifiers[id]);
}
} else if (specifiers.length > 0) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = specifiers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
let specifier = _step3.value;
addExport(asset, path, specifier.local, specifier.exported);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
path.remove();
}
// Mark the asset as an ES6 module, so we handle imports correctly in the packager.
asset.cacheData.isES6Module = true;
},
ExportAllDeclaration(path, asset) {
asset.cacheData.wildcards.push(path.node.source.value);
asset.cacheData.isES6Module = true;
path.remove();
}
};
function addExport(asset, path, local, exported) {
// Check if this identifier has already been exported.
// If so, create an export alias for it, otherwise, rename the local variable to an export.
if (asset.cacheData.exports[local.name]) {
asset.cacheData.exports[getName(asset, 'export', exported.name)] = asset.cacheData.exports[local.name];
} else {
asset.cacheData.exports[getName(asset, 'export', exported.name)] = exported.name;
path.scope.rename(local.name, getName(asset, 'export', exported.name));
}
}
function safeRename(path, from, to) {
// If the binding that we're renaming is constant, it's safe to rename it.
// Otherwise, create a new binding that references the original.
let binding = path.scope.getBinding(from);
if (binding && binding.constant) {
path.scope.rename(from, to);
} else {
path.insertAfter(t.variableDeclaration('var', [t.variableDeclarator(t.identifier(to), t.identifier(from))]));
}
}
function getName(asset, type, ...rest) {
return '$' + asset.id + '$' + type + (rest.length ? '$' + rest.map(name => name === 'default' ? name : t.toIdentifier(name)).join('$') : '');
}
function getIdentifier(asset, type, ...rest) {
return t.identifier(getName(asset, type, ...rest));
}
function getExportsIdentifier(asset) {
return getIdentifier(asset, 'exports');
}

View file

@ -0,0 +1,38 @@
'use strict';
const types = require('babel-types');
// from babel-types. remove when we upgrade to babel 7.
// https://github.com/babel/babel/blob/0189b387026c35472dccf45d14d58312d249f799/packages/babel-types/src/index.js#L347
module.exports = function matchesPattern(member, match, allowPartial) {
// not a member expression
if (!types.isMemberExpression(member)) return false;
const parts = Array.isArray(match) ? match : match.split('.');
const nodes = [];
let node;
for (node = member; types.isMemberExpression(node); node = node.object) {
nodes.push(node.property);
}
nodes.push(node);
if (nodes.length < parts.length) return false;
if (!allowPartial && nodes.length > parts.length) return false;
for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) {
const node = nodes[j];
let value;
if (types.isIdentifier(node)) {
value = node.name;
} else if (types.isStringLiteral(node)) {
value = node.value;
} else {
return false;
}
if (parts[i] !== value) return false;
}
return true;
};