🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

flow-parser

Package Overview
Dependencies
Maintainers
7
Versions
422
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

flow-parser - npm Package Compare versions

Comparing version
0.318.0
to
0.319.0
+1055
oxidized/babel/TransformESTreeToBabel.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _ESTreeVisitorKeys = _interopRequireDefault(require("../generated/ESTreeVisitorKeys"));
var _createSyntaxError = require("../utils/createSyntaxError");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const EMPTY_PARENT = null;
const FlowESTreeAndBabelVisitorKeys = { ..._ESTreeVisitorKeys.default,
BigIntLiteral: [],
BlockStatement: ['directives', ..._ESTreeVisitorKeys.default.BlockStatement],
BooleanLiteral: [],
ClassExpression: ['superTypeParameters', ..._ESTreeVisitorKeys.default.ClassExpression],
ClassDeclaration: ['superTypeParameters', ..._ESTreeVisitorKeys.default.ClassDeclaration],
ClassMethod: ['key', 'params', 'body', 'returnType', 'typeParameters'],
ClassPrivateMethod: ['key', 'params', 'body', 'returnType', 'typeParameters'],
ClassProperty: ['key', 'value', 'typeAnnotation', 'variance'],
ClassPrivateProperty: ['key', 'value', 'typeAnnotation', 'variance'],
Directive: ['value'],
DirectiveLiteral: [],
ExportNamespaceSpecifier: ['exported'],
File: ['program', 'comments'],
Import: [],
NullLiteral: [],
NumericLiteral: [],
ObjectMethod: [..._ESTreeVisitorKeys.default.Property, 'params', 'body', 'returnType', 'typeParameters'],
ObjectProperty: _ESTreeVisitorKeys.default.Property,
OptionalCallExpression: ['callee', 'arguments', 'typeArguments'],
OptionalMemberExpression: ['object', 'property'],
PrivateName: ['id'],
Program: ['directives', ..._ESTreeVisitorKeys.default.Program],
RegExpLiteral: [],
RestElement: [..._ESTreeVisitorKeys.default.RestElement, 'typeAnnotation'],
StringLiteral: [],
TupleTypeAnnotation: ['types'],
CommentBlock: [],
CommentLine: []
};
function nodeWith(node, overrideProps) {
return _SimpleTransform.SimpleTransform.nodeWith(node, overrideProps, FlowESTreeAndBabelVisitorKeys);
}
function fixSourceLocation(node, _options) {
const loc = node.loc;
if (loc == null) {
return;
}
node.loc = {
start: loc.start,
end: loc.end
};
if (node.type === 'Identifier') {
node.loc.identifierName = node.name;
}
node.start = node.range[0];
node.end = node.range[1];
delete node.range;
delete node.parent;
}
function mapNodeWithDirectives(node) {
if (node.directives != null) {
return node;
}
const directives = [];
for (const child of node.body) {
if (child.type === 'ExpressionStatement' && child.directive != null) {
directives.push({
type: 'Directive',
value: {
type: 'DirectiveLiteral',
value: child.directive,
extra: {
rawValue: child.directive,
raw: child.expression.type === 'Literal' ? child.expression.raw : ''
},
loc: child.expression.loc,
range: child.expression.range,
parent: EMPTY_PARENT
},
loc: child.loc,
range: child.range,
parent: node
});
} else {
break;
}
}
return nodeWith(node, {
directives,
body: directives.length === 0 ? node.body : node.body.slice(directives.length)
});
}
function mapProgram(node) {
var _program$directives;
const program = mapNodeWithDirectives(node);
const startLoc = {
line: 1,
column: 0
};
let endLoc = program.loc.end;
let endRange = program.range[1];
if (program.comments.length > 0) {
const lastComment = program.comments[program.comments.length - 1];
if (lastComment.range[1] > endRange) {
endLoc = lastComment.loc.end;
endRange = lastComment.range[1];
}
}
const loc = {
start: startLoc,
end: endLoc
};
const range = [0, endRange];
const babelComments = program.comments.map(comment => {
switch (comment.type) {
case 'Line':
{
return {
type: 'CommentLine',
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
case 'Block':
{
return {
type: 'CommentBlock',
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
}
});
return {
type: 'File',
program: {
type: 'Program',
body: program.body,
directives: (_program$directives = program.directives) != null ? _program$directives : [],
sourceType: program.sourceType,
interpreter: program.interpreter,
loc,
range,
parent: EMPTY_PARENT
},
comments: babelComments,
loc,
range,
parent: EMPTY_PARENT
};
}
function mapTemplateElement(node) {
const startCharsToExclude = 1;
const endCharsToExclude = node.tail ? 1 : 2;
node.loc = {
start: {
line: node.loc.start.line,
column: node.loc.start.column + startCharsToExclude
},
end: {
line: node.loc.end.line,
column: node.loc.end.column - endCharsToExclude
}
};
node.range = [node.range[0] + startCharsToExclude, node.range[1] - endCharsToExclude];
return node;
}
function mapProperty(node) {
const key = node.key;
const value = node.value;
if (node.method || node.kind !== 'init') {
if (value.type !== 'FunctionExpression') {
throw (0, _createSyntaxError.createSyntaxError)(node, `Invalid method property, the value must be a "FunctionExpression" or "ArrowFunctionExpression. Instead got "${value.type}".`);
}
const newNode = {
type: 'ObjectMethod',
kind: node.kind === 'init' ? 'method' : node.kind,
method: node.kind === 'init' ? true : false,
computed: node.computed,
key: key,
id: null,
params: value.params,
body: value.body,
async: value.async,
generator: value.generator,
returnType: value.returnType,
typeParameters: value.typeParameters,
loc: node.loc,
range: node.range,
parent: node.parent
};
if (node.kind !== 'init') {
newNode.variance = null;
}
return newNode;
}
const propertyValue = value;
return {
type: 'ObjectProperty',
computed: node.computed,
key: node.key,
value: propertyValue,
method: node.method,
shorthand: node.shorthand,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapMethodDefinition(node) {
const value = node.value;
const BaseClassMethod = {
kind: node.kind,
computed: node.computed,
static: node.static,
key: node.key,
id: null,
params: value.params,
body: value.body,
async: value.async,
generator: value.generator,
returnType: value.returnType,
typeParameters: value.typeParameters,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
if (node.key.type === 'PrivateIdentifier') {
return { ...BaseClassMethod,
type: 'ClassPrivateMethod'
};
}
return { ...BaseClassMethod,
type: 'ClassMethod'
};
}
function mapExportAllDeclaration(node) {
if (node.exported != null) {
return {
type: 'ExportNamedDeclaration',
declaration: null,
specifiers: [{
type: 'ExportNamespaceSpecifier',
exported: node.exported,
loc: {
start: {
column: node.loc.start.column + 'export '.length,
line: node.loc.start.line
},
end: node.exported.loc.end
},
range: [node.range[0] + 'export '.length, node.exported.range[1]],
parent: EMPTY_PARENT
}],
source: node.source,
exportKind: node.exportKind,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
delete node.exported;
return node;
}
function mapRestElement(node) {
const argument = node.argument;
if ((argument.type === 'Identifier' || argument.type === 'ObjectPattern' || argument.type === 'ArrayPattern') && argument.typeAnnotation != null) {
const argumentRange = argument.range;
let argumentLoc = argument.loc;
if (argument.type === 'Identifier') {
argumentRange[1] = argumentRange[0] + argument.name.length;
argumentLoc = {
start: argumentLoc.start,
end: {
line: argumentLoc.start.line,
column: argumentLoc.start.column + argument.name.length
}
};
}
return nodeWith(node, {
typeAnnotation: argument.typeAnnotation,
argument: nodeWith(argument, {
typeAnnotation: null,
range: argumentRange,
loc: argumentLoc
})
});
}
return node;
}
function mapImportExpression(node) {
return {
type: 'CallExpression',
callee: {
type: 'Import',
loc: {
start: node.loc.start,
end: {
line: node.loc.start.line,
column: node.loc.start.column + 'import'.length
}
},
range: [node.range[0], node.range[0] + 'import'.length],
parent: EMPTY_PARENT
},
arguments: [node.source],
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapPrivateIdentifier(node) {
return {
type: 'PrivateName',
id: {
type: 'Identifier',
name: node.name,
optional: false,
typeAnnotation: null,
loc: {
start: {
line: node.loc.start.line,
column: node.loc.start.column + 1
},
end: node.loc.end
},
range: [node.range[0] + 1, node.range[1]],
parent: EMPTY_PARENT
},
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapPropertyDefinition(node) {
if (node.key.type === 'PrivateIdentifier') {
return {
type: 'ClassPrivateProperty',
key: mapPrivateIdentifier(node.key),
value: node.value,
typeAnnotation: node.typeAnnotation,
static: node.static,
variance: node.variance,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
return {
type: 'ClassProperty',
key: node.key,
value: node.value,
typeAnnotation: node.typeAnnotation,
static: node.static,
variance: node.variance,
declare: node.declare,
optional: node.optional,
computed: node.computed,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapTypeofTypeAnnotation(node) {
delete node.typeArguments;
if (node.argument.type !== 'GenericTypeAnnotation') {
return nodeWith(node, {
argument: {
type: 'GenericTypeAnnotation',
id: node.argument,
typeParameters: null,
loc: node.argument.loc,
range: node.argument.range,
parent: EMPTY_PARENT
}
});
}
return node;
}
function mapDeclareVariable(node) {
if (node.kind != null) {
delete node.kind;
}
return node;
}
function mapJSXElement(node) {
if (node.openingElement.typeArguments != null) {
delete node.openingElement.typeArguments;
}
return node;
}
function mapChainExpressionInnerNode(node) {
switch (node.type) {
case 'MemberExpression':
{
const innerObject = mapChainExpressionInnerNode(node.object);
if (!node.optional && innerObject.type !== 'OptionalMemberExpression' && innerObject.type !== 'OptionalCallExpression') {
return node;
}
return {
type: 'OptionalMemberExpression',
object: innerObject,
property: node.property,
computed: node.computed,
optional: node.optional,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
case 'CallExpression':
{
const innerCallee = mapChainExpressionInnerNode(node.callee);
if (!node.optional && innerCallee.type !== 'OptionalMemberExpression' && innerCallee.type !== 'OptionalCallExpression') {
return node;
}
return {
type: 'OptionalCallExpression',
callee: innerCallee,
optional: node.optional,
arguments: node.arguments,
typeArguments: node.typeArguments,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
default:
{
return node;
}
}
}
function mapChainExpression(node) {
return mapChainExpressionInnerNode(node.expression);
}
function mapLiteral(node) {
const base = {
loc: node.loc,
range: node.range,
parent: node.parent
};
switch (node.literalType) {
case 'string':
{
return {
type: 'StringLiteral',
value: node.value,
extra: {
rawValue: node.value,
raw: node.raw
},
...base
};
}
case 'numeric':
{
return {
type: 'NumericLiteral',
value: node.value,
extra: {
rawValue: node.value,
raw: node.raw
},
...base
};
}
case 'bigint':
{
return {
type: 'BigIntLiteral',
value: node.bigint,
extra: {
rawValue: node.bigint,
raw: node.raw
},
...base
};
}
case 'boolean':
{
return {
type: 'BooleanLiteral',
value: node.value,
...base
};
}
case 'null':
{
return {
type: 'NullLiteral',
...base
};
}
case 'regexp':
{
return {
type: 'RegExpLiteral',
extra: {
raw: node.raw
},
pattern: node.regex.pattern,
flags: node.regex.flags,
...base
};
}
}
}
function transformNode(node) {
switch (node.type) {
case 'Program':
{
var _node$parent;
if (((_node$parent = node.parent) == null ? void 0 : _node$parent.type) === 'File') {
return node;
}
return mapProgram(node);
}
case 'BlockStatement':
{
return mapNodeWithDirectives(node);
}
case 'Property':
{
return mapProperty(node);
}
case 'TemplateElement':
{
return mapTemplateElement(node);
}
case 'MethodDefinition':
{
return mapMethodDefinition(node);
}
case 'ExportAllDeclaration':
{
return mapExportAllDeclaration(node);
}
case 'RestElement':
{
return mapRestElement(node);
}
case 'ImportExpression':
{
return mapImportExpression(node);
}
case 'PrivateIdentifier':
{
return mapPrivateIdentifier(node);
}
case 'PropertyDefinition':
{
return mapPropertyDefinition(node);
}
case 'TypeofTypeAnnotation':
{
return mapTypeofTypeAnnotation(node);
}
case 'DeclareVariable':
{
return mapDeclareVariable(node);
}
case 'JSXElement':
{
return mapJSXElement(node);
}
case 'Literal':
{
return mapLiteral(node);
}
case 'ChainExpression':
{
return mapChainExpression(node);
}
case 'TypeCastExpression':
{
node.loc.start.column = node.loc.start.column + 1;
node.loc.end.column = node.loc.end.column - 1;
node.range = [node.range[0] + 1, node.range[1] - 1];
return node;
}
case 'AsExpression':
{
const {
typeAnnotation
} = node;
node.type = 'TypeCastExpression';
node.typeAnnotation = {
type: 'TypeAnnotation',
typeAnnotation,
loc: typeAnnotation.loc,
range: typeAnnotation.range
};
return node;
}
case 'AsConstExpression':
{
return node.expression;
}
case 'NumberLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'StringLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'BigIntLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.bigint,
raw: node.raw
};
delete node.bigint;
delete node.raw;
return node;
}
case 'BooleanLiteralTypeAnnotation':
{
delete node.raw;
return node;
}
case 'TupleTypeAnnotation':
{
delete node.inexact;
node.types = node.elementTypes;
delete node.elementTypes;
return node;
}
case 'UnknownTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'unknown',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'NeverTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'never',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'UndefinedTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'undefined',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'JSXText':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'Identifier':
{
if (node.optional === false || node.optional == null) {
delete node.optional;
}
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'CallExpression':
{
if (node.optional === false) {
delete node.optional;
}
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'OptionalCallExpression':
{
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'MemberExpression':
{
delete node.optional;
return node;
}
case 'ExpressionStatement':
{
delete node.directive;
return node;
}
case 'ObjectPattern':
case 'ArrayPattern':
{
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
case 'ClassMethod':
{
delete node.expression;
if (node.predicate == null) {
delete node.predicate;
}
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ObjectMethod':
{
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassPrivateMethod':
{
if (node.computed === false) {
delete node.computed;
}
if (node.predicate == null) {
delete node.predicate;
}
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassExpression':
case 'ClassDeclaration':
{
if (node.decorators == null || node.decorators.length === 0) {
delete node.decorators;
}
if (node.implements == null || node.implements.length === 0) {
delete node.implements;
}
if (node.superTypeArguments == null) {
delete node.superTypeArguments;
} else {
node.superTypeParameters = node.superTypeArguments;
delete node.superTypeArguments;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassProperty':
{
if (node.optional === false) {
delete node.optional;
}
if (node.declare === false) {
delete node.declare;
}
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'ClassPrivateProperty':
{
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'ExportNamedDeclaration':
{
if (node.declaration == null) {
delete node.declaration;
}
return node;
}
case 'ImportDeclaration':
{
if (node.attributes == null || node.attributes.length === 0) {
delete node.attributes;
}
return node;
}
case 'ArrayExpression':
{
delete node.trailingComma;
return node;
}
case 'JSXOpeningElement':
{
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'DeclareOpaqueType':
case 'OpaqueType':
{
if (node.lowerBound != null) {
delete node.lowerBound;
}
if (node.upperBound != null) {
delete node.upperBound;
}
return node;
}
default:
{
return node;
}
}
}
function transformProgram(program, options) {
var _resultNode$type;
const resultNode = _SimpleTransform.SimpleTransform.transform(program, {
transform(node) {
return transformNode(node);
},
visitorKeys: FlowESTreeAndBabelVisitorKeys
});
_SimpleTraverser.SimpleTraverser.traverse(resultNode, {
enter(node) {
fixSourceLocation(node, options);
},
leave() {},
visitorKeys: FlowESTreeAndBabelVisitorKeys
});
if ((resultNode == null ? void 0 : resultNode.type) === 'File') {
return resultNode;
}
throw new Error(`Unknown AST node of type "${(_resultNode$type = resultNode == null ? void 0 : resultNode.type) != null ? _resultNode$type : 'NULL'}" returned from Babel conversion`);
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
function transformProgram(program, _options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'AsExpression':
case 'AsConstExpression':
case 'TypeCastExpression':
{
return node.expression;
}
case 'CallExpression':
case 'NewExpression':
{
if (node.typeArguments != null) {
return nodeWith(node, {
typeArguments: null
});
}
return node;
}
case 'ObjectPattern':
case 'ArrayPattern':
case 'Identifier':
{
if (node.typeAnnotation != null) {
return nodeWith(node, {
typeAnnotation: null
});
}
return node;
}
case 'DeclareClass':
case 'DeclareFunction':
case 'DeclareInterface':
case 'DeclareModule':
case 'DeclareModuleExports':
case 'DeclareNamespace':
case 'DeclareOpaqueType':
case 'DeclareTypeAlias':
case 'DeclareVariable':
case 'InterfaceDeclaration':
case 'OpaqueType':
case 'TypeAlias':
{
return null;
}
case 'FunctionDeclaration':
case 'ArrowFunctionExpression':
case 'FunctionExpression':
{
const newParams = [];
for (let i = 0; i < node.params.length; i++) {
if (i === 0 && node.params[0].type === 'Identifier' && node.params[0].name === 'this') {
continue;
}
let param = node.params[i];
if (param.type === 'AssignmentPattern') {
param = param.left;
}
if (param.optional === true) {
param = nodeWith(param, {
optional: false
});
}
newParams.push(param);
}
return nodeWith(node, {
params: newParams,
returnType: null,
typeParameters: null,
predicate: null
});
}
case 'ClassDeclaration':
case 'ClassExpression':
{
return nodeWith(node, {
typeParameters: null,
superTypeArguments: null,
implements: [],
decorators: []
});
}
case 'PropertyDefinition':
{
return nodeWith(node, {
typeAnnotation: null,
variance: null,
declare: false,
optional: false
});
}
case 'ImportDeclaration':
{
if (node.importKind === 'type' || node.importKind === 'typeof') {
return null;
}
const nonTypeSpecifiers = node.specifiers.filter(s => s.type !== 'ImportSpecifier' || s.importKind !== 'type' && s.importKind !== 'typeof');
if (nonTypeSpecifiers.length === 0) {
return null;
}
if (nonTypeSpecifiers.length === node.specifiers.length) {
return node;
}
return nodeWith(node, {
specifiers: nonTypeSpecifiers
});
}
case 'ExportAllDeclaration':
case 'ExportNamedDeclaration':
{
if (node.exportKind === 'type') {
return null;
}
return node;
}
default:
{
return node;
}
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _createSyntaxError = require("../utils/createSyntaxError");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
const EMPTY_PARENT = null;
function createSimpleGenericTypeAnnotation(name, nodeForLoc) {
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name,
optional: false,
typeAnnotation: null,
loc: nodeForLoc.loc,
range: nodeForLoc.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: nodeForLoc.loc,
range: nodeForLoc.range,
parent: nodeForLoc.parent
};
}
function createAnyTypeAnnotation(node) {
return {
type: 'AnyTypeAnnotation',
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapDeclareEnum(node) {
return {
type: 'DeclareVariable',
kind: 'const',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: createAnyTypeAnnotation(node.body),
loc: node.body.loc,
range: node.body.range,
parent: EMPTY_PARENT
}
}),
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapDeclareNamespace(node) {
return {
type: 'DeclareVariable',
kind: 'const',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: createAnyTypeAnnotation(node.body),
loc: node.body.loc,
range: node.body.range,
parent: EMPTY_PARENT
}
}),
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapFunction(node) {
if (node.params.length !== 0 && node.params[0].name === 'this') {
return nodeWith(node, {
params: node.params.slice(1)
});
}
return node;
}
function mapQualifiedTypeofIdentifier(node) {
return {
type: 'QualifiedTypeIdentifier',
qualification: node.qualification.type === 'QualifiedTypeofIdentifier' ? mapQualifiedTypeofIdentifier(node.qualification) : node.qualification,
id: node.id,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function transformProgram(program, _options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'SymbolTypeAnnotation':
{
return createSimpleGenericTypeAnnotation('symbol', node);
}
case 'BigIntTypeAnnotation':
{
return createSimpleGenericTypeAnnotation('bigint', node);
}
case 'ObjectTypeAnnotation':
{
const shouldStrip = node.properties.some(prop => prop.type === 'ObjectTypeMappedTypeProperty');
if (shouldStrip) {
return createAnyTypeAnnotation(node);
}
return node;
}
case 'ObjectTypeMappedTypeProperty':
{
throw (0, _createSyntaxError.createSyntaxError)(node, `Invalid AST structure, ObjectTypeMappedTypeProperty found outside of an ObjectTypeAnnotation`);
}
case 'IndexedAccessType':
case 'OptionalIndexedAccessType':
case 'KeyofTypeAnnotation':
case 'ConditionalTypeAnnotation':
case 'InferTypeAnnotation':
case 'TupleTypeLabeledElement':
case 'TupleTypeSpreadElement':
case 'ComponentTypeAnnotation':
case 'HookTypeAnnotation':
case 'TypeOperator':
case 'TypePredicate':
{
return createAnyTypeAnnotation(node);
}
case 'QualifiedTypeofIdentifier':
{
return mapQualifiedTypeofIdentifier(node);
}
case 'DeclareEnum':
{
return mapDeclareEnum(node);
}
case 'DeclareNamespace':
{
return mapDeclareNamespace(node);
}
case 'FunctionDeclaration':
case 'FunctionExpression':
{
return mapFunction(node);
}
default:
{
return node;
}
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _createSyntaxError = require("../utils/createSyntaxError");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
const EMPTY_PARENT = null;
function createDefaultPosition() {
return {
line: 1,
column: 0
};
}
function mapDeclareComponent(node) {
return {
type: 'DeclareVariable',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'AnyTypeAnnotation',
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
}
}),
kind: 'const',
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function getComponentParameterName(paramName) {
switch (paramName.type) {
case 'Identifier':
return paramName.name;
case 'Literal':
return paramName.value;
default:
throw (0, _createSyntaxError.createSyntaxError)(paramName, `Unknown Component parameter name type of "${paramName.type}"`);
}
}
function createPropsTypeAnnotation(propTypes, spread, loc, range) {
const createParamsTypeLoc = () => ({
loc: {
start: (loc == null ? void 0 : loc.start) != null ? loc.start : createDefaultPosition(),
end: (loc == null ? void 0 : loc.end) != null ? loc.end : createDefaultPosition()
},
range: range != null ? range : [0, 0],
parent: EMPTY_PARENT
});
if (spread != null && propTypes.length === 0) {
return {
type: 'TypeAnnotation',
typeAnnotation: spread.argument,
...createParamsTypeLoc()
};
}
const typeProperties = [...propTypes];
if (spread != null) {
typeProperties.unshift(spread);
}
const propTypeObj = {
type: 'ObjectTypeAnnotation',
callProperties: [],
properties: typeProperties,
indexers: [],
internalSlots: [],
exact: false,
inexact: false,
...createParamsTypeLoc()
};
return {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: '$ReadOnly',
optional: false,
typeAnnotation: null,
...createParamsTypeLoc()
},
typeParameters: {
type: 'TypeParameterInstantiation',
params: [propTypeObj],
...createParamsTypeLoc()
},
...createParamsTypeLoc()
},
...createParamsTypeLoc()
};
}
function mapComponentParameters(params, options) {
var _options$reactRuntime;
if (params.length === 0) {
return {
props: null,
ref: null
};
}
if (params.length === 1 && params[0].type === 'RestElement' && params[0].argument.type === 'Identifier') {
const restElementArgument = params[0].argument;
return {
props: restElementArgument,
ref: null
};
}
let refParam = null;
const paramsWithoutRef = ((_options$reactRuntime = options.reactRuntimeTarget) != null ? _options$reactRuntime : '18') === '18' ? params.filter(param => {
if (param.type === 'ComponentParameter' && getComponentParameterName(param.name) === 'ref') {
refParam = param;
return false;
}
return true;
}) : params;
const [propTypes, spread] = paramsWithoutRef.reduce(([propTypes, spread], param) => {
switch (param.type) {
case 'RestElement':
{
if (spread != null) {
throw (0, _createSyntaxError.createSyntaxError)(param, `Invalid state, multiple rest elements found as Component Parameters`);
}
return [propTypes, mapComponentParameterRestElementType(param)];
}
case 'ComponentParameter':
{
propTypes.push(mapComponentParameterType(param));
return [propTypes, spread];
}
}
}, [[], null]);
const propsProperties = paramsWithoutRef.flatMap(mapComponentParameter);
let props = null;
if (propsProperties.length === 0) {
if (refParam == null) {
throw new Error('TransformComponentSyntax: Invalid state, ref should always be set at this point if props are empty');
}
const emptyParamsLoc = {
start: refParam.loc.start,
end: refParam.loc.start
};
const emptyParamsRange = [refParam.range[0], refParam.range[0]];
props = {
type: 'Identifier',
name: '_$$empty_props_placeholder$$',
optional: false,
typeAnnotation: createPropsTypeAnnotation([], null, emptyParamsLoc, emptyParamsRange),
loc: emptyParamsLoc,
range: emptyParamsRange,
parent: EMPTY_PARENT
};
} else {
const lastPropsProperty = propsProperties[propsProperties.length - 1];
props = {
type: 'ObjectPattern',
properties: propsProperties,
typeAnnotation: createPropsTypeAnnotation(propTypes, spread, {
start: lastPropsProperty.loc.end,
end: lastPropsProperty.loc.end
}, [lastPropsProperty.range[1], lastPropsProperty.range[1]]),
loc: {
start: propsProperties[0].loc.start,
end: lastPropsProperty.loc.end
},
range: [propsProperties[0].range[0], lastPropsProperty.range[1]],
parent: EMPTY_PARENT
};
}
let ref = null;
if (refParam != null) {
ref = refParam.local;
}
return {
props,
ref
};
}
function mapComponentParameterType(param) {
var _typeAnnotation$typeA;
const typeAnnotation = param.local.type === 'AssignmentPattern' ? param.local.left.typeAnnotation : param.local.typeAnnotation;
const optional = param.local.type === 'AssignmentPattern' ? true : param.local.type === 'Identifier' ? param.local.optional : false;
return {
type: 'ObjectTypeProperty',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(param.name),
value: (_typeAnnotation$typeA = typeAnnotation == null ? void 0 : typeAnnotation.typeAnnotation) != null ? _typeAnnotation$typeA : {
type: 'AnyTypeAnnotation',
loc: param.local.loc,
range: param.local.range,
parent: EMPTY_PARENT
},
kind: 'init',
optional,
method: false,
static: false,
proto: false,
variance: null,
loc: param.local.loc,
range: param.local.range,
parent: EMPTY_PARENT
};
}
function mapComponentParameterRestElementType(param) {
var _param$argument$typeA, _param$argument$typeA2;
if (param.argument.type !== 'Identifier' && param.argument.type !== 'ObjectPattern') {
throw (0, _createSyntaxError.createSyntaxError)(param, `Invalid ${param.argument.type} encountered in restParameter`);
}
return {
type: 'ObjectTypeSpreadProperty',
argument: (_param$argument$typeA = (_param$argument$typeA2 = param.argument.typeAnnotation) == null ? void 0 : _param$argument$typeA2.typeAnnotation) != null ? _param$argument$typeA : {
type: 'AnyTypeAnnotation',
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
},
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
};
}
function mapComponentParameter(param) {
switch (param.type) {
case 'RestElement':
{
switch (param.argument.type) {
case 'Identifier':
{
const a = nodeWith(param, {
typeAnnotation: null,
argument: nodeWith(param.argument, {
typeAnnotation: null
})
});
return [a];
}
case 'ObjectPattern':
{
return param.argument.properties.map(property => {
return nodeWith(property, {
typeAnnotation: null
});
});
}
default:
{
throw (0, _createSyntaxError.createSyntaxError)(param, `Unhandled ${param.argument.type} encountered in restParameter`);
}
}
}
case 'ComponentParameter':
{
let value;
if (param.local.type === 'AssignmentPattern') {
value = nodeWith(param.local, {
left: nodeWith(param.local.left, {
typeAnnotation: null,
optional: false
})
});
} else {
value = nodeWith(param.local, {
typeAnnotation: null,
optional: false
});
}
if (param.name.type === 'Identifier' && param.shorthand && (value.type === 'Identifier' || value.type === 'AssignmentPattern')) {
return [{
type: 'Property',
key: param.name,
kind: 'init',
value,
method: false,
shorthand: true,
computed: false,
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
}];
}
return [{
type: 'Property',
key: param.name,
kind: 'init',
value,
method: false,
shorthand: false,
computed: false,
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
}];
}
default:
{
throw (0, _createSyntaxError.createSyntaxError)(param, `Unknown Component parameter type of "${param.type}"`);
}
}
}
function createForwardRefWrapper(originalComponent) {
const internalCompId = {
type: 'Identifier',
name: `${originalComponent.id.name}_withRef`,
optional: false,
typeAnnotation: null,
loc: originalComponent.id.loc,
range: originalComponent.id.range,
parent: EMPTY_PARENT
};
return {
forwardRefStatement: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: (0, _astNodeMutationHelpers.shallowCloneNode)(originalComponent.id),
init: {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: {
type: 'Identifier',
name: 'React',
optional: false,
typeAnnotation: null,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
property: {
type: 'Identifier',
name: 'forwardRef',
optional: false,
typeAnnotation: null,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
computed: false,
optional: false,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
arguments: [(0, _astNodeMutationHelpers.shallowCloneNode)(internalCompId)],
typeArguments: null,
optional: false,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
}],
loc: originalComponent.loc,
range: originalComponent.range,
parent: originalComponent.parent
},
internalCompId: internalCompId,
forwardRefCompId: originalComponent.id
};
}
function mapComponentDeclaration(node, options) {
var _node$async;
const createRendersTypeLoc = () => ({
loc: {
start: node.body.loc.end,
end: node.body.loc.end
},
range: [node.body.range[1], node.body.range[1]],
parent: EMPTY_PARENT
});
const returnType = {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'GenericTypeAnnotation',
id: {
type: 'QualifiedTypeIdentifier',
qualification: {
type: 'Identifier',
name: 'React',
optional: false,
typeAnnotation: null,
...createRendersTypeLoc()
},
id: {
type: 'Identifier',
name: 'Node',
optional: false,
typeAnnotation: null,
...createRendersTypeLoc()
},
...createRendersTypeLoc()
},
typeParameters: null,
...createRendersTypeLoc()
},
...createRendersTypeLoc()
};
const {
props,
ref
} = mapComponentParameters(node.params, options);
let forwardRefDetails = null;
if (ref != null) {
forwardRefDetails = createForwardRefWrapper(node);
}
const comp = {
type: 'FunctionDeclaration',
id: forwardRefDetails != null ? (0, _astNodeMutationHelpers.shallowCloneNode)(forwardRefDetails.internalCompId) : (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
__componentDeclaration: true,
typeParameters: node.typeParameters,
params: props == null ? [] : ref == null ? [props] : [props, ref],
returnType,
body: node.body,
async: (_node$async = node.async) != null ? _node$async : false,
generator: false,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
return {
comp,
forwardRefDetails
};
}
function mapDeclareHook(node) {
return {
type: 'DeclareFunction',
id: {
type: 'Identifier',
name: node.id.name,
optional: node.id.optional,
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'FunctionTypeAnnotation',
this: null,
params: node.id.typeAnnotation.typeAnnotation.params,
typeParameters: node.id.typeAnnotation.typeAnnotation.typeParameters,
rest: node.id.typeAnnotation.typeAnnotation.rest,
returnType: node.id.typeAnnotation.typeAnnotation.returnType,
loc: node.id.typeAnnotation.typeAnnotation.loc,
range: node.id.typeAnnotation.typeAnnotation.range,
parent: node.id.typeAnnotation.typeAnnotation.parent
},
loc: node.id.typeAnnotation.loc,
range: node.id.typeAnnotation.range,
parent: node.id.typeAnnotation.parent
},
loc: node.id.loc,
range: node.id.range,
parent: node.id.parent
},
loc: node.loc,
range: node.range,
parent: node.parent,
predicate: null
};
}
function mapHookDeclaration(node) {
var _node$async2;
const comp = {
type: 'FunctionDeclaration',
id: node.id && (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
__hookDeclaration: true,
typeParameters: node.typeParameters,
params: node.params,
returnType: node.returnType,
body: node.body,
async: (_node$async2 = node.async) != null ? _node$async2 : false,
generator: false,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
return comp;
}
function scanForFirstComponentReference(compName, bodyList) {
for (let i = 0; i < bodyList.length; i++) {
const bodyNode = bodyList[i];
let referencePos = null;
_SimpleTraverser.SimpleTraverser.traverse(bodyNode, {
enter(node) {
switch (node.type) {
case 'Identifier':
{
if (node.name === compName) {
referencePos = i;
throw _SimpleTraverser.SimpleTraverser.Break;
}
}
}
},
leave(_node) {}
});
if (referencePos != null) {
return referencePos;
}
}
return null;
}
function mapComponentDeclarationIntoList(node, newBody, options, insertExport) {
const {
comp,
forwardRefDetails
} = mapComponentDeclaration(node, options);
if (forwardRefDetails != null) {
const referencePos = scanForFirstComponentReference(forwardRefDetails.forwardRefCompId.name, newBody);
if (referencePos != null) {
newBody.splice(referencePos, 0, forwardRefDetails.forwardRefStatement);
} else {
newBody.push(forwardRefDetails.forwardRefStatement);
}
newBody.push(comp);
if (insertExport != null) {
newBody.push(insertExport(forwardRefDetails.forwardRefCompId));
}
return;
}
newBody.push(insertExport != null ? insertExport(comp) : comp);
}
function mapStatementList(stmts, options) {
const newBody = [];
for (const node of stmts) {
switch (node.type) {
case 'ComponentDeclaration':
{
mapComponentDeclarationIntoList(node, newBody, options);
break;
}
case 'HookDeclaration':
{
const decl = mapHookDeclaration(node);
newBody.push(decl);
break;
}
case 'ExportNamedDeclaration':
{
var _node$declaration, _node$declaration2;
if (((_node$declaration = node.declaration) == null ? void 0 : _node$declaration.type) === 'ComponentDeclaration') {
mapComponentDeclarationIntoList(node.declaration, newBody, options, componentOrRef => {
switch (componentOrRef.type) {
case 'FunctionDeclaration':
{
return nodeWith(node, {
declaration: componentOrRef
});
}
case 'Identifier':
{
return {
type: 'ExportNamedDeclaration',
declaration: null,
specifiers: [{
type: 'ExportSpecifier',
exported: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
local: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
}],
exportKind: 'value',
source: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
}
});
break;
}
if (((_node$declaration2 = node.declaration) == null ? void 0 : _node$declaration2.type) === 'HookDeclaration') {
const comp = mapHookDeclaration(node.declaration);
newBody.push(nodeWith(node, {
declaration: comp
}));
break;
}
newBody.push(node);
break;
}
case 'ExportDefaultDeclaration':
{
var _node$declaration3, _node$declaration4;
if (((_node$declaration3 = node.declaration) == null ? void 0 : _node$declaration3.type) === 'ComponentDeclaration') {
mapComponentDeclarationIntoList(node.declaration, newBody, options, componentOrRef => nodeWith(node, {
declaration: componentOrRef
}));
break;
}
if (((_node$declaration4 = node.declaration) == null ? void 0 : _node$declaration4.type) === 'HookDeclaration') {
const comp = mapHookDeclaration(node.declaration);
newBody.push(nodeWith(node, {
declaration: comp
}));
break;
}
newBody.push(node);
break;
}
default:
{
newBody.push(node);
}
}
}
return newBody;
}
function transformProgram(program, options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'DeclareComponent':
{
return mapDeclareComponent(node);
}
case 'DeclareHook':
{
return mapDeclareHook(node);
}
case 'Program':
case 'BlockStatement':
{
return nodeWith(node, {
body: mapStatementList(node.body, options)
});
}
case 'SwitchCase':
{
const consequent = mapStatementList(node.consequent, options);
return nodeWith(node, {
consequent
});
}
case 'ComponentDeclaration':
{
var _node$parent;
throw (0, _createSyntaxError.createSyntaxError)(node, `Components must be defined at the top level of a module or within a ` + `BlockStatement, instead got parent of "${(_node$parent = node.parent) == null ? void 0 : _node$parent.type}".`);
}
case 'HookDeclaration':
{
var _node$parent2;
throw (0, _createSyntaxError.createSyntaxError)(node, `Hooks must be defined at the top level of a module or within a ` + `BlockStatement, instead got parent of "${(_node$parent2 = node.parent) == null ? void 0 : _node$parent2.type}".`);
}
default:
{
return node;
}
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _flowEstree = require("flow-estree");
var _SimpleTransform = require("../transform/SimpleTransform");
var _Builders = require("../utils/Builders");
function mapEnumDeclaration(node, options) {
var _options$transformOpt, _options$transformOpt2;
const {
body
} = node;
const {
members
} = body;
const getRuntime = (_options$transformOpt = options.transformOptions) == null ? void 0 : (_options$transformOpt2 = _options$transformOpt.TransformEnumSyntax) == null ? void 0 : _options$transformOpt2.getRuntime;
const enumModule = typeof getRuntime === 'function' ? getRuntime() : (0, _Builders.callExpression)((0, _Builders.ident)('require'), [(0, _Builders.stringLiteral)('flow-enums-runtime')]);
const mirrored = body.type === 'EnumStringBody' && (!members.length || members[0].type === 'EnumDefaultedMember');
const enumExpression = mirrored ? (0, _Builders.callExpression)({
type: 'MemberExpression',
object: enumModule,
property: (0, _Builders.ident)('Mirrored'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [{
type: 'ArrayExpression',
elements: members.map(member => (0, _Builders.stringLiteral)(member.id.name)),
trailingComma: false,
...(0, _Builders.etc)()
}]) : (0, _Builders.callExpression)(enumModule, [{
type: 'ObjectExpression',
properties: members.map(member => ({
type: 'Property',
key: member.id,
value: member.type === 'EnumDefaultedMember' ? (0, _Builders.callExpression)((0, _Builders.ident)('Symbol'), [(0, _Builders.stringLiteral)(member.id.name)]) : member.init,
kind: 'init',
method: false,
shorthand: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
})),
...(0, _Builders.etc)()
}]);
return (0, _Builders.variableDeclaration)('const', node.id, enumExpression);
}
function transformProgram(program, options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'EnumDeclaration':
{
return mapEnumDeclaration(node, options);
}
case 'ExportDefaultDeclaration':
{
const {
declaration
} = node;
if ((0, _flowEstree.isEnumDeclaration)(declaration)) {
const enumDeclaration = mapEnumDeclaration(declaration, options);
const exportDefault = _SimpleTransform.SimpleTransform.nodeWith(node, {
declaration: (0, _Builders.ident)(declaration.id.name)
});
return [enumDeclaration, exportDefault];
} else {
return node;
}
}
default:
{
return node;
}
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _createSyntaxError = require("../utils/createSyntaxError");
var _Builders = require("../utils/Builders");
var _GenID = _interopRequireDefault(require("../utils/GenID"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let genID = null;
function genIdent() {
if (genID == null) {
throw Error('GenID must be initialized at the start of the transform.');
}
return (0, _Builders.ident)(genID.id());
}
function objKeyToString(node) {
switch (node.type) {
case 'Identifier':
return node.name;
case 'Literal':
{
const {
value
} = node;
if (typeof value === 'number') {
return String(value);
} else if (typeof value === 'string') {
return value;
} else {
return node.raw;
}
}
}
}
function convertMemberPattern(pattern) {
const {
base,
property,
loc,
range
} = pattern;
const object = base.type === 'MatchIdentifierPattern' ? base.id : convertMemberPattern(base);
if (property.type === 'Identifier') {
return {
type: 'MemberExpression',
object,
property,
computed: false,
optional: false,
...(0, _Builders.etc)({
loc,
range
})
};
} else {
return {
type: 'MemberExpression',
object,
property,
computed: true,
optional: false,
...(0, _Builders.etc)({
loc,
range
})
};
}
}
function checkDuplicateBindingName(seenBindingNames, node, name) {
if (seenBindingNames.has(name)) {
throw (0, _createSyntaxError.createSyntaxError)(node, `Duplicate variable name '${name}' in match case pattern.`);
}
seenBindingNames.add(name);
}
function checkBindingKind(node, kind) {
if (kind === 'var') {
throw (0, _createSyntaxError.createSyntaxError)(node, `'var' bindings are not allowed. Use 'const' or 'let'.`);
}
}
function needsPropExistsCond(pattern) {
switch (pattern.type) {
case 'MatchWildcardPattern':
case 'MatchBindingPattern':
case 'MatchIdentifierPattern':
case 'MatchMemberPattern':
return true;
case 'MatchLiteralPattern':
case 'MatchUnaryPattern':
case 'MatchObjectPattern':
case 'MatchInstancePattern':
case 'MatchArrayPattern':
return false;
case 'MatchAsPattern':
{
const {
pattern: asPattern
} = pattern;
return needsPropExistsCond(asPattern);
}
case 'MatchOrPattern':
{
const {
patterns
} = pattern;
return patterns.some(needsPropExistsCond);
}
}
}
function analyzeProperties(key, pattern, seenBindingNames, properties, rest) {
const conditions = [];
const bindings = [];
const objKeys = [];
const seenNames = new Set();
properties.forEach(prop => {
const {
key: objKey,
pattern: propPattern
} = prop;
objKeys.push(objKey);
const name = objKeyToString(objKey);
if (seenNames.has(name)) {
throw (0, _createSyntaxError.createSyntaxError)(propPattern, `Duplicate property name '${name}' in match object pattern.`);
}
seenNames.add(name);
const propKey = key.concat(objKey);
if (needsPropExistsCond(propPattern)) {
conditions.push({
type: 'prop-exists',
key,
propName: name
});
}
const {
conditions: childConditions,
bindings: childBindings
} = analyzePattern(propPattern, propKey, seenBindingNames);
conditions.push(...childConditions);
bindings.push(...childBindings);
});
if (rest != null && rest.argument != null) {
const {
id,
kind
} = rest.argument;
checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
checkBindingKind(pattern, kind);
bindings.push({
type: 'object-rest',
key,
exclude: objKeys,
kind,
id
});
}
return {
conditions,
bindings
};
}
function constructorExpression(constructor) {
switch (constructor.type) {
case 'MatchIdentifierPattern':
return constructor.id;
case 'MatchMemberPattern':
return convertMemberPattern(constructor);
}
}
function analyzePattern(pattern, key, seenBindingNames) {
switch (pattern.type) {
case 'MatchWildcardPattern':
{
return {
conditions: [],
bindings: []
};
}
case 'MatchLiteralPattern':
{
const {
literal
} = pattern;
const condition = {
type: 'eq',
key,
arg: literal
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchUnaryPattern':
{
const {
operator,
argument,
loc,
range
} = pattern;
if (argument.value === 0) {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `'+0' and '-0' are not yet supported in match unary patterns.`);
}
const arg = {
type: 'UnaryExpression',
operator,
argument,
prefix: true,
...(0, _Builders.etc)({
loc,
range
})
};
const condition = {
type: 'eq',
key,
arg
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchIdentifierPattern':
{
const {
id
} = pattern;
const condition = id.name === 'NaN' ? {
type: 'is-nan',
key
} : {
type: 'eq',
key,
arg: id
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchMemberPattern':
{
const arg = convertMemberPattern(pattern);
const condition = {
type: 'eq',
key,
arg
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchBindingPattern':
{
const {
id,
kind
} = pattern;
checkDuplicateBindingName(seenBindingNames, pattern, id.name);
checkBindingKind(pattern, kind);
const binding = {
type: 'id',
key,
kind,
id
};
return {
conditions: [],
bindings: [binding]
};
}
case 'MatchAsPattern':
{
const {
pattern: asPattern,
target
} = pattern;
if (asPattern.type === 'MatchBindingPattern') {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `Match 'as' patterns are not allowed directly on binding patterns.`);
}
const {
conditions,
bindings
} = analyzePattern(asPattern, key, seenBindingNames);
const defaultKind = 'const';
const [id, kind] = target.type === 'MatchBindingPattern' ? [target.id, target.kind] : [target, defaultKind];
checkDuplicateBindingName(seenBindingNames, pattern, id.name);
checkBindingKind(pattern, kind);
const binding = {
type: 'id',
key,
kind,
id
};
return {
conditions,
bindings: bindings.concat(binding)
};
}
case 'MatchArrayPattern':
{
const {
elements,
rest
} = pattern;
const lengthOp = rest == null ? 'eq' : 'gte';
const conditions = [{
type: 'array',
key,
length: elements.length,
lengthOp
}];
const bindings = [];
elements.forEach((element, i) => {
const elementKey = key.concat((0, _Builders.numberLiteral)(i));
const {
conditions: childConditions,
bindings: childBindings
} = analyzePattern(element, elementKey, seenBindingNames);
conditions.push(...childConditions);
bindings.push(...childBindings);
});
if (rest != null && rest.argument != null) {
const {
id,
kind
} = rest.argument;
checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
checkBindingKind(pattern, kind);
bindings.push({
type: 'array-rest',
key,
exclude: elements.length,
kind,
id
});
}
return {
conditions,
bindings
};
}
case 'MatchObjectPattern':
{
const {
properties,
rest
} = pattern;
const {
conditions: propertyConditions,
bindings
} = analyzeProperties(key, pattern, seenBindingNames, properties, rest);
const conditions = [{
type: 'object',
key
}, ...propertyConditions];
return {
conditions,
bindings
};
}
case 'MatchInstancePattern':
{
const {
targetConstructor,
properties: {
properties,
rest
}
} = pattern;
const {
conditions: propertyConditions,
bindings
} = analyzeProperties(key, pattern, seenBindingNames, properties, rest);
const conditions = [{
type: 'instanceof',
key,
constructor: constructorExpression(targetConstructor)
}, ...propertyConditions];
return {
conditions,
bindings
};
}
case 'MatchOrPattern':
{
const {
patterns
} = pattern;
let hasWildcard = false;
const orConditions = patterns.map(subpattern => {
const {
conditions,
bindings
} = analyzePattern(subpattern, key, seenBindingNames);
if (bindings.length > 0) {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `Bindings in match 'or' patterns are not yet supported.`);
}
if (conditions.length === 0) {
hasWildcard = true;
}
return conditions;
});
if (hasWildcard) {
return {
conditions: [],
bindings: []
};
}
return {
conditions: [{
type: 'or',
orConditions
}],
bindings: []
};
}
}
}
function expressionOfKey(root, key) {
return key.reduce((acc, prop) => prop.type === 'Identifier' ? {
type: 'MemberExpression',
object: acc,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
computed: false,
optional: false,
...(0, _Builders.etc)()
} : {
type: 'MemberExpression',
object: acc,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
computed: true,
optional: false,
...(0, _Builders.etc)()
}, (0, _astNodeMutationHelpers.deepCloneNode)(root));
}
function testsOfCondition(root, condition) {
switch (condition.type) {
case 'eq':
{
const {
key,
arg
} = condition;
return [{
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: arg,
operator: '===',
...(0, _Builders.etc)()
}];
}
case 'is-nan':
{
const {
key
} = condition;
const callee = {
type: 'MemberExpression',
object: (0, _Builders.ident)('Number'),
property: (0, _Builders.ident)('isNaN'),
computed: false,
optional: false,
...(0, _Builders.etc)()
};
return [(0, _Builders.callExpression)(callee, [expressionOfKey(root, key)])];
}
case 'array':
{
const {
key,
length,
lengthOp
} = condition;
const operator = lengthOp === 'eq' ? '===' : '>=';
const isArray = (0, _Builders.callExpression)({
type: 'MemberExpression',
object: (0, _Builders.ident)('Array'),
property: (0, _Builders.ident)('isArray'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [expressionOfKey(root, key)]);
const lengthCheck = {
type: 'BinaryExpression',
left: {
type: 'MemberExpression',
object: expressionOfKey(root, key),
property: (0, _Builders.ident)('length'),
computed: false,
optional: false,
...(0, _Builders.etc)()
},
right: (0, _Builders.numberLiteral)(length),
operator,
...(0, _Builders.etc)()
};
return [isArray, lengthCheck];
}
case 'object':
{
const {
key
} = condition;
const typeofObject = (0, _Builders.typeofExpression)(expressionOfKey(root, key), 'object');
const typeofFunction = (0, _Builders.typeofExpression)(expressionOfKey(root, key), 'function');
const notNull = {
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: (0, _Builders.nullLiteral)(),
operator: '!==',
...(0, _Builders.etc)()
};
return [(0, _Builders.disjunction)([(0, _Builders.conjunction)([typeofObject, notNull]), typeofFunction])];
}
case 'instanceof':
{
const {
key,
constructor
} = condition;
return [{
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: constructor,
operator: 'instanceof',
...(0, _Builders.etc)()
}];
}
case 'prop-exists':
{
const {
key,
propName
} = condition;
const inObject = {
type: 'BinaryExpression',
left: (0, _Builders.stringLiteral)(propName),
right: expressionOfKey(root, key),
operator: 'in',
...(0, _Builders.etc)()
};
return [inObject];
}
case 'or':
{
const {
orConditions
} = condition;
const tests = orConditions.map(conditions => (0, _Builders.conjunction)(testsOfConditions(root, conditions)));
return [(0, _Builders.disjunction)(tests)];
}
}
}
function testsOfConditions(root, conditions) {
return conditions.flatMap(condition => testsOfCondition(root, condition));
}
function statementsOfBindings(root, bindings) {
return bindings.map(binding => {
switch (binding.type) {
case 'id':
{
const {
key,
kind,
id
} = binding;
return (0, _Builders.variableDeclaration)(kind, id, expressionOfKey(root, key));
}
case 'array-rest':
{
const {
key,
kind,
id,
exclude
} = binding;
const init = (0, _Builders.callExpression)({
type: 'MemberExpression',
object: expressionOfKey(root, key),
property: (0, _Builders.ident)('slice'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [(0, _Builders.numberLiteral)(exclude)]);
return (0, _Builders.variableDeclaration)(kind, id, init);
}
case 'object-rest':
{
const {
key,
kind,
id,
exclude
} = binding;
const destructuring = {
type: 'ObjectPattern',
properties: exclude.map(prop => prop.type === 'Identifier' ? {
type: 'Property',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
value: genIdent(),
kind: 'init',
computed: false,
method: false,
shorthand: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
} : {
type: 'Property',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
value: genIdent(),
kind: 'init',
computed: true,
method: false,
shorthand: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
}).concat({
type: 'RestElement',
argument: id,
...(0, _Builders.etc)()
}),
typeAnnotation: null,
...(0, _Builders.etc)()
};
return (0, _Builders.variableDeclaration)(kind, destructuring, expressionOfKey(root, key));
}
}
});
}
const fallthroughErrorMsgText = `Match: No case succesfully matched. Make exhaustive or add a wildcard case using '_'.`;
function fallthroughErrorMsg(value) {
return {
type: 'BinaryExpression',
operator: '+',
left: (0, _Builders.stringLiteral)(`${fallthroughErrorMsgText} Argument: `),
right: value,
...(0, _Builders.etc)()
};
}
function fallthroughError(value) {
return (0, _Builders.throwStatement)(fallthroughErrorMsg(value));
}
function calculateSimpleArgument(node) {
switch (node.type) {
case 'Identifier':
case 'Super':
return true;
case 'MemberExpression':
{
const {
object,
property,
computed
} = node;
if (computed && property.type !== 'Literal') {
return false;
}
return calculateSimpleArgument(object);
}
default:
return false;
}
}
function analyzeCases(cases) {
let hasBindings = false;
let hasWildcard = false;
const analyses = [];
for (let i = 0; i < cases.length; i++) {
const {
pattern,
guard,
body
} = cases[i];
const {
conditions,
bindings
} = analyzePattern(pattern, [], new Set());
hasBindings = hasBindings || bindings.length > 0;
analyses.push({
conditions,
bindings,
guard,
body
});
if (conditions.length === 0 && guard == null) {
hasWildcard = true;
break;
}
}
return {
hasBindings,
hasWildcard,
analyses
};
}
function mapMatchExpression(node) {
const {
argument,
cases
} = node;
const {
hasBindings,
hasWildcard,
analyses
} = analyzeCases(cases);
const isSimpleArgument = !hasBindings && calculateSimpleArgument(argument);
const genRoot = !isSimpleArgument ? genIdent() : null;
const root = genRoot == null ? argument : genRoot;
if (isSimpleArgument) {
const wildcardAnalaysis = hasWildcard ? analyses.pop() : null;
const lastBody = wildcardAnalaysis != null ? wildcardAnalaysis.body : (0, _Builders.iife)([fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root))]);
return analyses.reverse().reduce((acc, analysis) => {
const {
conditions,
guard,
body
} = analysis;
const tests = testsOfConditions(root, conditions);
if (guard != null) {
tests.push(guard);
}
return {
type: 'ConditionalExpression',
test: (0, _Builders.conjunction)(tests),
consequent: body,
alternate: acc,
...(0, _Builders.etc)()
};
}, lastBody);
}
const statements = analyses.map(({
conditions,
bindings,
guard,
body
}) => {
const returnNode = {
type: 'ReturnStatement',
argument: body,
...(0, _Builders.etc)()
};
const bodyNode = guard == null ? returnNode : {
type: 'IfStatement',
test: guard,
consequent: returnNode,
...(0, _Builders.etc)()
};
const bindingNodes = statementsOfBindings(root, bindings);
const caseBody = bindingNodes.concat(bodyNode);
if (conditions.length > 0) {
const tests = testsOfConditions(root, conditions);
return {
type: 'IfStatement',
test: (0, _Builders.conjunction)(tests),
consequent: {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
};
} else {
if (bindingNodes.length > 0) {
return {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
};
} else {
return bodyNode;
}
}
});
if (!hasWildcard) {
statements.push(fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root)));
}
const [params, args] = genRoot == null ? [[], []] : [[genRoot], [argument]];
return (0, _Builders.iife)(statements, params, args);
}
function mapMatchStatement(node) {
const {
argument,
cases
} = node;
const {
hasBindings,
hasWildcard,
analyses
} = analyzeCases(cases);
const topLabel = genIdent();
const isSimpleArgument = !hasBindings && calculateSimpleArgument(argument);
const genRoot = !isSimpleArgument ? genIdent() : null;
const root = genRoot == null ? argument : genRoot;
const statements = [];
if (genRoot != null) {
statements.push((0, _Builders.variableDeclaration)('const', genRoot, argument));
}
analyses.forEach(({
conditions,
bindings,
guard,
body
}) => {
const breakNode = {
type: 'BreakStatement',
label: (0, _astNodeMutationHelpers.shallowCloneNode)(topLabel),
...(0, _Builders.etc)()
};
const bodyStatements = body.body.concat(breakNode);
const guardedBodyStatements = guard == null ? bodyStatements : [{
type: 'IfStatement',
test: guard,
consequent: {
type: 'BlockStatement',
body: bodyStatements,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
}];
const bindingNodes = statementsOfBindings(root, bindings);
const caseBody = bindingNodes.concat(guardedBodyStatements);
if (conditions.length > 0) {
const tests = testsOfConditions(root, conditions);
statements.push({
type: 'IfStatement',
test: (0, _Builders.conjunction)(tests),
consequent: {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
});
} else {
statements.push({
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
});
}
});
if (!hasWildcard) {
statements.push(fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root)));
}
return {
type: 'LabeledStatement',
label: topLabel,
body: {
type: 'BlockStatement',
body: statements,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
};
}
function transformProgram(program, _options) {
genID = new _GenID.default('m');
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'MatchExpression':
{
return mapMatchExpression(node);
}
case 'MatchStatement':
{
return mapMatchStatement(node);
}
case 'Identifier':
{
if (genID == null) {
throw Error('GenID must be initialized at the start of the transform.');
}
genID.addUsage(node.name);
return node;
}
default:
{
return node;
}
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _flowEstree = require("flow-estree");
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _Builders = require("../utils/Builders");
var _isReservedWord = _interopRequireDefault(require("../utils/isReservedWord"));
var _GenID = _interopRequireDefault(require("../utils/GenID"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function nameOfKey(key) {
switch (key.type) {
case 'Identifier':
return key.name;
case 'Literal':
if ((0, _flowEstree.isBigIntLiteral)(key)) {
return key.bigint;
}
return String(key.value);
}
}
function mapRecordDeclaration(genID, node) {
const ownProperties = [];
const staticProperties = [];
const methods = [];
const staticMethods = [];
for (const element of node.body.elements) {
switch (element.type) {
case 'RecordDeclarationProperty':
ownProperties.push(element);
break;
case 'RecordDeclarationStaticProperty':
staticProperties.push(element);
break;
case 'MethodDefinition':
if (element.static) {
staticMethods.push(element);
} else {
methods.push(element);
}
break;
}
}
const reservedPropNames = new Map();
const constructorParam = {
type: 'ObjectPattern',
properties: ownProperties.map(prop => {
const {
key,
defaultValue
} = prop;
const keyName = nameOfKey(key);
const getValue = bindingIdent => defaultValue != null ? {
type: 'AssignmentPattern',
left: bindingIdent,
right: (0, _astNodeMutationHelpers.deepCloneNode)(defaultValue),
...(0, _Builders.etc)()
} : bindingIdent;
switch (key.type) {
case 'Identifier':
{
const needsNewBinding = (0, _isReservedWord.default)(keyName);
const bindingName = needsNewBinding ? genID.id() : keyName;
const bindingIdent = (0, _Builders.ident)(bindingName);
if (needsNewBinding) {
reservedPropNames.set(keyName, bindingName);
}
if (needsNewBinding) {
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: false,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
} else {
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: true,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
}
}
case 'Literal':
{
const bindingName = genID.id();
const bindingIdent = (0, _Builders.ident)(bindingName);
reservedPropNames.set(keyName, bindingName);
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: false,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
}
}
}),
typeAnnotation: null,
...(0, _Builders.etc)()
};
const constructor = {
type: 'MethodDefinition',
key: (0, _Builders.ident)('constructor'),
kind: 'constructor',
computed: false,
static: false,
decorators: [],
value: {
type: 'FunctionExpression',
id: null,
params: [constructorParam],
body: {
type: 'BlockStatement',
body: ownProperties.map(({
key
}) => {
var _reservedPropNames$ge;
const keyName = nameOfKey(key);
const bindingIdent = (0, _Builders.ident)((_reservedPropNames$ge = reservedPropNames.get(keyName)) != null ? _reservedPropNames$ge : keyName);
const object = {
type: 'ThisExpression',
...(0, _Builders.etc)()
};
const memberExpression = key.type === 'Identifier' ? {
type: 'MemberExpression',
object,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
computed: false,
optional: false,
...(0, _Builders.etc)()
} : {
type: 'MemberExpression',
object,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
computed: true,
optional: false,
...(0, _Builders.etc)()
};
return {
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: memberExpression,
right: bindingIdent,
...(0, _Builders.etc)()
},
directive: null,
...(0, _Builders.etc)()
};
}),
...(0, _Builders.etc)()
},
generator: false,
async: false,
predicate: null,
returnType: null,
typeParameters: null,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
const classStaticProperties = staticProperties.map(prop => ({
type: 'PropertyDefinition',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop.key),
value: (0, _astNodeMutationHelpers.deepCloneNode)(prop.value),
static: true,
decorators: [],
typeAnnotation: null,
variance: null,
computed: false,
declare: false,
optional: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
}));
const classBodyElements = [constructor, ...methods, ...classStaticProperties, ...staticMethods];
return {
type: 'ClassDeclaration',
id: (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
body: {
type: 'ClassBody',
body: classBodyElements,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
},
superClass: null,
typeParameters: null,
superTypeArguments: null,
implements: [],
decorators: [],
...(0, _Builders.etc)()
};
}
function mapRecordExpression(node) {
const obj = {
type: 'ObjectExpression',
properties: node.properties.properties,
...(0, _Builders.etc)()
};
return {
type: 'NewExpression',
callee: node.recordConstructor,
arguments: [obj],
typeArguments: null,
...(0, _Builders.etc)()
};
}
function transformProgram(program, _options) {
const genID = new _GenID.default('r');
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'RecordDeclaration':
{
return mapRecordDeclaration(genID, node);
}
case 'RecordExpression':
{
return mapRecordExpression(node);
}
case 'Identifier':
{
genID.addUsage(node.name);
return node;
}
default:
return node;
}
}
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse = parse;
var _FlowParserDeserializer = _interopRequireDefault(require("./FlowParserDeserializer"));
var _FlowParserWASM = _interopRequireDefault(require("./FlowParserWASM"));
var _getModuleDocblock = require("./getModuleDocblock");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let FlowParserWASM;
let flowParse;
let flowParseResult_free;
let flowParseResult_getError;
let flowParseResult_getErrorLine;
let flowParseResult_getErrorColumn;
let flowParseResult_getProgramBuffer;
let flowParseResult_getPositionBuffer;
let flowParseResult_getPositionBufferSize;
let flowParseResult_getStringBuffer;
function initFlowParserWASM() {
if (FlowParserWASM != null) {
return;
}
FlowParserWASM = (0, _FlowParserWASM.default)({
quit(_status, toThrow) {
throw toThrow;
}
});
flowParse = FlowParserWASM.cwrap('hermesParse', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']);
flowParseResult_free = FlowParserWASM.cwrap('hermesParseResult_free', 'void', ['number']);
flowParseResult_getError = FlowParserWASM.cwrap('hermesParseResult_getError', 'string', ['number']);
flowParseResult_getErrorLine = FlowParserWASM.cwrap('hermesParseResult_getErrorLine', 'number', ['number']);
flowParseResult_getErrorColumn = FlowParserWASM.cwrap('hermesParseResult_getErrorColumn', 'number', ['number']);
flowParseResult_getProgramBuffer = FlowParserWASM.cwrap('hermesParseResult_getProgramBuffer', 'number', ['number']);
flowParseResult_getPositionBuffer = FlowParserWASM.cwrap('hermesParseResult_getPositionBuffer', 'number', ['number']);
flowParseResult_getPositionBufferSize = FlowParserWASM.cwrap('hermesParseResult_getPositionBufferSize', 'number', ['number']);
flowParseResult_getStringBuffer = FlowParserWASM.cwrap('hermesParseResult_getStringBuffer', 'number', ['number']);
}
function copyToHeap(buffer, addr) {
FlowParserWASM.HEAP8.set(buffer, addr);
FlowParserWASM.HEAP8[addr + buffer.length] = 0;
}
function flag(v) {
return v === true ? 1 : 0;
}
function parse(source, options) {
initFlowParserWASM();
const sourceBuffer = Buffer.from(source, 'utf8');
const filename = typeof options.sourceFilename === 'string' ? options.sourceFilename : '';
const filenameBuffer = filename.length > 0 ? Buffer.from(filename, 'utf8') : null;
let sourceAddr = 0;
let filenameAddr = 0;
let filenameLen = 0;
let parseResult = 0;
try {
sourceAddr = FlowParserWASM._malloc(sourceBuffer.length + 1);
if (!sourceAddr) {
throw new Error('Parser out of memory');
}
if (filenameBuffer != null) {
filenameAddr = FlowParserWASM._malloc(filenameBuffer.length + 1);
if (!filenameAddr) {
throw new Error('Parser out of memory');
}
copyToHeap(filenameBuffer, filenameAddr);
filenameLen = filenameBuffer.length + 1;
}
copyToHeap(sourceBuffer, sourceAddr);
const enableTypes = options.enableTypes === false ? 0 : 1;
const sourceTypeCode = options.sourceType === 'script' ? 1 : options.sourceType === 'module' ? 2 : 0;
parseResult = flowParse(sourceAddr, sourceBuffer.length + 1, filenameAddr, filenameLen, flag(options.enableExperimentalComponentSyntax), flag(options.enableExperimentalFlowMatchSyntax), flag(options.enableExperimentalDecorators), flag(options.tokens), flag(options.allowReturnOutsideFunction), flag(options.assertOperator), flag(options.enableEnums), flag(options.enableRecords), enableTypes, sourceTypeCode, flag(options.enableTypesPragmaDetection), 0);
const programBuffer = flowParseResult_getProgramBuffer(parseResult);
if (!programBuffer) {
const err = flowParseResult_getError(parseResult);
const syntaxError = new SyntaxError(err || 'unknown parse error');
syntaxError.loc = {
line: flowParseResult_getErrorLine(parseResult),
column: flowParseResult_getErrorColumn(parseResult)
};
throw syntaxError;
}
const deserializer = new _FlowParserDeserializer.default(programBuffer, flowParseResult_getPositionBuffer(parseResult), flowParseResult_getPositionBufferSize(parseResult), flowParseResult_getStringBuffer(parseResult), FlowParserWASM, options);
const ast = deserializer.deserialize();
if (ast.type !== 'Program') {
throw new Error(`Expected Program, got ${ast.type}`);
}
const sourceFilename = typeof options.sourceFilename === 'string' ? options.sourceFilename : null;
const visitedNodes = new WeakSet();
const locRanges = new WeakMap();
function fixLocs(node) {
if (node == null || typeof node !== 'object') {
return;
}
const wireNode = node;
if (visitedNodes.has(wireNode)) {
return;
}
visitedNodes.add(wireNode);
if (wireNode.loc != null) {
const loc = wireNode.loc;
let range = locRanges.get(loc);
if (range == null) {
const rangeStart = loc.rangeStart;
const rangeEnd = loc.rangeEnd;
if (rangeStart == null || rangeEnd == null) {
throw new Error('Expected serialized source range');
}
loc.source = sourceFilename;
range = [rangeStart, rangeEnd];
locRanges.set(loc, range);
delete loc.rangeStart;
delete loc.rangeEnd;
}
wireNode.range = range;
}
for (const key of Object.keys(wireNode)) {
const val = wireNode[key];
if (Array.isArray(val)) {
for (const child of val) {
fixLocs(child);
}
} else {
fixLocs(val);
}
}
}
fixLocs(ast);
if (options.throwOnParseErrors !== false) {
const errors = ast.errors;
if (errors != null && errors.length > 0) {
const first = errors[0];
const start = first.loc.start;
if (start == null) {
throw new Error('Expected serialized parser error start location');
}
const line = start.line;
const column = start.column;
const syntaxError = new SyntaxError(`${first.message} (${line}:${column})`);
syntaxError.loc = {
line,
column
};
throw syntaxError;
}
}
if (options.sourceType === 'script' || options.sourceType === 'module') {
ast.sourceType = options.sourceType;
} else {
ast.sourceType = detectSourceType(ast);
}
ast.docblock = (0, _getModuleDocblock.getModuleDocblock)(ast);
return asProgram(ast);
} finally {
if (parseResult !== 0) {
flowParseResult_free(parseResult);
}
if (sourceAddr !== 0) {
FlowParserWASM._free(sourceAddr);
}
if (filenameAddr !== 0) {
FlowParserWASM._free(filenameAddr);
}
}
}
function asProgram(ast) {
const program = ast;
return program;
}
function detectSourceType(program) {
if (!Array.isArray(program.body)) {
return 'script';
}
for (const stmt of program.body) {
if (stmt == null) {
continue;
}
switch (stmt.type) {
case 'ImportDeclaration':
if (stmt.importKind === 'value' || stmt.importKind == null) {
return 'module';
}
break;
case 'ExportDefaultDeclaration':
return 'module';
case 'ExportNamedDeclaration':
case 'ExportAllDeclaration':
if (stmt.exportKind === 'value' || stmt.exportKind == null) {
return 'module';
}
break;
}
}
return 'script';
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _HermesParserDecodeUTF8String = _interopRequireDefault(require("./HermesParserDecodeUTF8String"));
var _FlowParserNodeDeserializers = _interopRequireDefault(require("./FlowParserNodeDeserializers"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class FlowParserDeserializer {
constructor(programBuffer, positionBuffer, positionBufferSize, stringBufferBase, wasmParser, options) {
this.programBufferIdx = void 0;
this.positionBufferIdx = void 0;
this.positionBufferSize = void 0;
this.stringBufferBase = void 0;
this.locMap = void 0;
this.HEAPU8 = void 0;
this.HEAPU32 = void 0;
this.HEAPF64 = void 0;
this.options = void 0;
this.commentTypes = ['Block', 'Line'];
this.tokenTypes = ['Boolean', 'Identifier', 'Keyword', 'Null', 'Numeric', 'BigInt', 'Punctuator', 'String', 'RegularExpression', 'Template', 'JSXText'];
this.programBufferIdx = programBuffer / 4;
this.positionBufferIdx = positionBuffer / 4;
this.positionBufferSize = positionBufferSize;
this.stringBufferBase = stringBufferBase;
this.locMap = {};
this.HEAPU8 = wasmParser.HEAPU8;
this.HEAPU32 = wasmParser.HEAPU32;
this.HEAPF64 = wasmParser.HEAPF64;
this.options = options;
}
next() {
const num = this.HEAPU32[this.programBufferIdx++];
return num;
}
deserialize() {
const program = {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList(),
comments: this.deserializeComments()
};
program.interpreter = this.deserializeNode();
if (this.options.tokens === true) {
program.tokens = this.deserializeTokens();
} else {
this.deserializeTokens();
}
program.errors = this.deserializeErrors();
this.fillLocs();
return program;
}
deserializeErrors() {
const size = this.next();
const errors = [];
for (let i = 0; i < size; i++) {
const loc = this.addEmptyLoc();
const message = this.deserializeString();
if (message == null) {
throw new Error('Expected serialized parser error message');
}
errors.push({
loc,
message
});
}
return errors;
}
deserializeBoolean() {
return Boolean(this.next());
}
deserializeNumber() {
let floatIdx;
if (this.programBufferIdx % 2 === 0) {
floatIdx = this.programBufferIdx / 2;
this.programBufferIdx += 2;
} else {
floatIdx = (this.programBufferIdx + 1) / 2;
this.programBufferIdx += 3;
}
return this.HEAPF64[floatIdx];
}
deserializeString() {
const offsetPlusOne = this.next();
if (offsetPlusOne === 0) {
return null;
}
const size = this.next();
return (0, _HermesParserDecodeUTF8String.default)(this.stringBufferBase + offsetPlusOne - 1, size, this.HEAPU8);
}
deserializeNode() {
const nodeType = this.next();
if (nodeType === 0) {
return null;
}
const nodeDeserializer = _FlowParserNodeDeserializers.default[nodeType - 1].bind(this);
return nodeDeserializer();
}
deserializeNodeList() {
const size = this.next();
const nodeList = [];
for (let i = 0; i < size; i++) {
nodeList.push(this.deserializeNode());
}
return nodeList;
}
deserializeComments() {
const size = this.next();
const comments = [];
for (let i = 0; i < size; i++) {
const commentType = this.commentTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
comments.push({
type: commentType,
loc,
value
});
}
return comments;
}
deserializeTokens() {
const size = this.next();
const tokens = [];
for (let i = 0; i < size; i++) {
const tokenType = this.tokenTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
tokens.push({
type: tokenType,
loc,
value
});
}
return tokens;
}
addEmptyLoc() {
const loc = {};
this.locMap[this.next()] = loc;
return loc;
}
fillLocs() {
for (let i = 0; i < this.positionBufferSize; i++) {
const locId = this.HEAPU32[this.positionBufferIdx++];
const kind = this.HEAPU32[this.positionBufferIdx++];
const line = this.HEAPU32[this.positionBufferIdx++];
const column = this.HEAPU32[this.positionBufferIdx++];
const offset = this.HEAPU32[this.positionBufferIdx++];
const loc = this.locMap[locId];
if (kind === 0) {
loc.start = {
line,
column
};
loc.rangeStart = offset;
} else {
loc.end = {
line,
column
};
loc.rangeEnd = offset;
}
}
}
}
exports.default = FlowParserDeserializer;

Sorry, the diff of this file is not supported yet

'use strict';
module.exports = [function () {
return {
type: 'EmptyStatement',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ExpressionStatement',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
directive: this.deserializeString()
};
}, function () {
return {
type: 'BlockStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'IfStatement',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
consequent: this.deserializeNode(),
alternate: this.deserializeNode()
};
}, function () {
return {
type: 'LabeledStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'BreakStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode()
};
}, function () {
return {
type: 'ContinueStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode()
};
}, function () {
return {
type: 'WithStatement',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'SwitchStatement',
loc: this.addEmptyLoc(),
discriminant: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'ReturnStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ThrowStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TryStatement',
loc: this.addEmptyLoc(),
block: this.deserializeNode(),
handler: this.deserializeNode(),
finalizer: this.deserializeNode()
};
}, function () {
return {
type: 'WhileStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
test: this.deserializeNode()
};
}, function () {
return {
type: 'DoWhileStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
test: this.deserializeNode()
};
}, function () {
return {
type: 'ForStatement',
loc: this.addEmptyLoc(),
init: this.deserializeNode(),
test: this.deserializeNode(),
update: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ForInStatement',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ForOfStatement',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
body: this.deserializeNode(),
await: this.deserializeBoolean()
};
}, function () {
return {
type: 'DebuggerStatement',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MatchStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'FunctionDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
generator: this.deserializeBoolean(),
async: this.deserializeBoolean(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'VariableDeclaration',
loc: this.addEmptyLoc(),
kind: this.deserializeString(),
declarations: this.deserializeNodeList()
};
}, function () {
return {
type: 'VariableDeclarator',
loc: this.addEmptyLoc(),
init: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'ClassDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
superClass: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode(),
superTypeArguments: this.deserializeNode(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'ComponentDeclaration',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'HookDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
returnType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeAlias',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ImportDeclaration',
loc: this.addEmptyLoc(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode(),
importKind: this.deserializeString(),
attributes: this.deserializeNodeList()
};
}, function () {
return {
type: 'ImportDefaultSpecifier',
loc: this.addEmptyLoc(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ImportNamespaceSpecifier',
loc: this.addEmptyLoc(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ImportSpecifier',
loc: this.addEmptyLoc(),
imported: this.deserializeNode(),
local: this.deserializeNode(),
importKind: this.deserializeString()
};
}, function () {
return {
type: 'ImportAttribute',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'ImportEqualsDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
moduleReference: this.deserializeNode(),
importKind: this.deserializeString(),
isExport: this.deserializeBoolean()
};
}, function () {
return {
type: 'ExternalModuleReference',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ExportNamedDeclaration',
loc: this.addEmptyLoc(),
declaration: this.deserializeNode(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode(),
exportKind: this.deserializeString()
};
}, function () {
return {
type: 'ExportDefaultDeclaration',
loc: this.addEmptyLoc(),
declaration: this.deserializeNode()
};
}, function () {
return {
type: 'ExportAllDeclaration',
loc: this.addEmptyLoc(),
source: this.deserializeNode(),
exported: this.deserializeNode(),
exportKind: this.deserializeString()
};
}, function () {
return {
type: 'ExportSpecifier',
loc: this.addEmptyLoc(),
exported: this.deserializeNode(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ExportNamespaceSpecifier',
loc: this.addEmptyLoc(),
exported: this.deserializeNode()
};
}, function () {
return {
type: 'ExportAssignment',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ThisExpression',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'Super',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ArrayExpression',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
trailingComma: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectExpression',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList()
};
}, function () {
return {
type: 'FunctionExpression',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
generator: this.deserializeBoolean(),
async: this.deserializeBoolean(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'ArrowFunctionExpression',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
async: this.deserializeBoolean(),
id: this.deserializeNode(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'SequenceExpression',
loc: this.addEmptyLoc(),
expressions: this.deserializeNodeList()
};
}, function () {
return {
type: 'UnaryExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode(),
prefix: this.deserializeBoolean()
};
}, function () {
return {
type: 'BinaryExpression',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
operator: this.deserializeString()
};
}, function () {
return {
type: 'LogicalExpression',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
operator: this.deserializeString()
};
}, function () {
return {
type: 'ConditionalExpression',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
alternate: this.deserializeNode(),
consequent: this.deserializeNode()
};
}, function () {
return {
type: 'UpdateExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode(),
prefix: this.deserializeBoolean()
};
}, function () {
return {
type: 'AssignmentExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
left: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'MemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode(),
computed: this.deserializeBoolean(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'OptionalMemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode(),
computed: this.deserializeBoolean(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'CallExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'OptionalCallExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'NewExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList()
};
}, function () {
return {
type: 'YieldExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
delegate: this.deserializeBoolean()
};
}, function () {
return {
type: 'AwaitExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ImportExpression',
loc: this.addEmptyLoc(),
source: this.deserializeNode(),
options: this.deserializeNode()
};
}, function () {
return {
type: 'MetaProperty',
loc: this.addEmptyLoc(),
meta: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'TaggedTemplateExpression',
loc: this.addEmptyLoc(),
tag: this.deserializeNode(),
quasi: this.deserializeNode()
};
}, function () {
return {
type: 'TemplateLiteral',
loc: this.addEmptyLoc(),
quasis: this.deserializeNodeList(),
expressions: this.deserializeNodeList()
};
}, function () {
return {
type: 'TemplateElement',
loc: this.addEmptyLoc(),
tail: this.deserializeBoolean(),
value: {
cooked: this.deserializeString(),
raw: this.deserializeString()
}
};
}, function () {
return {
type: 'TypeCastExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'AsExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'SatisfiesExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'AsConstExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'NonNullExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
chain: this.deserializeBoolean()
};
}, function () {
return {
type: 'MatchExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'RecordExpression',
loc: this.addEmptyLoc(),
recordConstructor: this.deserializeNode(),
typeArguments: this.deserializeNode(),
properties: this.deserializeNode()
};
}, function () {
return {
type: 'RecordExpressionProperties',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList()
};
}, function () {
const loc = this.addEmptyLoc();
const valueKind = this.next();
let value = null;
if (valueKind === 1) value = this.deserializeBoolean();else if (valueKind === 2) value = this.deserializeNumber();else if (valueKind === 3) value = this.deserializeString();
const literalType = this.deserializeString();
const raw = this.deserializeString();
const bigint = this.deserializeString();
const regexPattern = this.deserializeString();
const regexFlags = this.deserializeString();
const node = {
type: 'Literal',
loc,
value,
raw,
literalType
};
if (bigint != null) {
node.bigint = bigint;
try {
node.value = typeof BigInt === 'function' ? BigInt(bigint) : null;
} catch (e) {
node.value = null;
}
}
if (regexPattern != null) {
const flags = regexFlags != null ? regexFlags : '';
node.regex = {
pattern: regexPattern,
flags
};
try {
node.value = new RegExp(regexPattern, flags);
} catch (e) {
node.value = null;
}
}
return node;
}, function () {
return {
type: 'Identifier',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'PrivateIdentifier',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ArrayPattern',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'RestElement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'AssignmentPattern',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'Property',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
kind: this.deserializeString(),
method: this.deserializeBoolean(),
shorthand: this.deserializeBoolean(),
computed: this.deserializeBoolean()
};
}, function () {
return {
type: 'SpreadElement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ClassExpression',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
superClass: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode(),
superTypeArguments: this.deserializeNode(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'ClassBody',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'ClassImplements',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'MethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
kind: this.deserializeString(),
static: this.deserializeBoolean(),
computed: this.deserializeBoolean(),
decorators: this.deserializeNodeList(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'PropertyDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
computed: this.deserializeBoolean(),
static: this.deserializeBoolean(),
variance: this.deserializeNode(),
tsAccessibility: this.deserializeString(),
declare: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
override: this.deserializeBoolean(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'StaticBlock',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'Decorator',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ParameterProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
computed: this.deserializeBoolean(),
static: this.deserializeBoolean(),
variance: this.deserializeNode(),
tsAccessibility: this.deserializeString(),
declare: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'DeclareMethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
static: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
computed: this.deserializeBoolean(),
kind: this.deserializeString(),
override: this.deserializeBoolean()
};
}, function () {
return {
type: 'AbstractMethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
computed: this.deserializeBoolean(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'AbstractPropertyDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
computed: this.deserializeBoolean(),
variance: this.deserializeNode(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'SwitchCase',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
consequent: this.deserializeNodeList()
};
}, function () {
return {
type: 'CatchClause',
loc: this.addEmptyLoc(),
param: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ComponentParameter',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
local: this.deserializeNode(),
shorthand: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclareVariable',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'DeclareFunction',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
predicate: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareClass',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
extends: this.deserializeNodeList(),
implements: this.deserializeNodeList(),
mixins: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareComponent',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareHook',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareModule',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareModuleExports',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareExportDeclaration',
loc: this.addEmptyLoc(),
default: this.deserializeBoolean(),
declaration: this.deserializeNode(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareExportAllDeclaration',
loc: this.addEmptyLoc(),
source: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareNamespace',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareInterface',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
body: this.deserializeNode(),
extends: this.deserializeNodeList()
};
}, function () {
return {
type: 'DeclareTypeAlias',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareEnum',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeAnnotation',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'Variance',
loc: this.addEmptyLoc(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'AnyTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MixedTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'EmptyTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'VoidTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NullLiteralTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'SymbolTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NumberTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'BigIntTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'StringTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'BooleanTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NullableTypeAnnotation',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ArrayTypeAnnotation',
loc: this.addEmptyLoc(),
elementType: this.deserializeNode()
};
}, function () {
return {
type: 'IndexedAccessType',
loc: this.addEmptyLoc(),
objectType: this.deserializeNode(),
indexType: this.deserializeNode()
};
}, function () {
return {
type: 'OptionalIndexedAccessType',
loc: this.addEmptyLoc(),
objectType: this.deserializeNode(),
indexType: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'UnionTypeAnnotation',
loc: this.addEmptyLoc(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'IntersectionTypeAnnotation',
loc: this.addEmptyLoc(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'KeyofTypeAnnotation',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TypeOperator',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'StringLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeString(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'NumberLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeNumber(),
raw: this.deserializeString()
};
}, function () {
const loc = this.addEmptyLoc();
this.deserializeNode();
const raw = this.deserializeString();
const bigint = this.deserializeString();
let value = null;
if (bigint != null && typeof BigInt === 'function') {
try {
value = BigInt(bigint);
} catch (e) {
value = null;
}
}
return {
type: 'BigIntLiteralTypeAnnotation',
loc,
value,
raw,
bigint
};
}, function () {
return {
type: 'BooleanLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeBoolean(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'ExistsTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'UnknownTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NeverTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'UndefinedTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'GenericTypeAnnotation',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'QualifiedTypeIdentifier',
loc: this.addEmptyLoc(),
qualification: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'QualifiedTypeofIdentifier',
loc: this.addEmptyLoc(),
qualification: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'TypeofTypeAnnotation',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'ImportType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TupleTypeAnnotation',
loc: this.addEmptyLoc(),
elementTypes: this.deserializeNodeList(),
inexact: this.deserializeBoolean()
};
}, function () {
return {
type: 'TupleTypeLabeledElement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
elementType: this.deserializeNode(),
variance: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'TupleTypeSpreadElement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeAnnotation',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
indexers: this.deserializeNodeList(),
callProperties: this.deserializeNodeList(),
internalSlots: this.deserializeNodeList(),
inexact: this.deserializeBoolean(),
exact: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectTypeProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
method: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
static: this.deserializeBoolean(),
proto: this.deserializeBoolean(),
variance: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'ObjectTypeSpreadProperty',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeIndexer',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
key: this.deserializeNode(),
value: this.deserializeNode(),
static: this.deserializeBoolean(),
variance: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeCallProperty',
loc: this.addEmptyLoc(),
value: this.deserializeNode(),
static: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectTypeMappedTypeProperty',
loc: this.addEmptyLoc(),
keyTparam: this.deserializeNode(),
propType: this.deserializeNode(),
sourceType: this.deserializeNode(),
variance: this.deserializeNode(),
optional: this.deserializeString()
};
}, function () {
return {
type: 'ObjectTypeInternalSlot',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
optional: this.deserializeBoolean(),
static: this.deserializeBoolean(),
method: this.deserializeBoolean(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'FunctionTypeParam',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'TypePredicate',
loc: this.addEmptyLoc(),
parameterName: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'ConditionalTypeAnnotation',
loc: this.addEmptyLoc(),
checkType: this.deserializeNode(),
extendsType: this.deserializeNode(),
trueType: this.deserializeNode(),
falseType: this.deserializeNode()
};
}, function () {
return {
type: 'InferTypeAnnotation',
loc: this.addEmptyLoc(),
typeParameter: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceExtends',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceTypeAnnotation',
loc: this.addEmptyLoc(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeParameterDeclaration',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList()
};
}, function () {
return {
type: 'TypeParameter',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
const: this.deserializeBoolean(),
bound: this.deserializeNode(),
variance: this.deserializeNode(),
default: this.deserializeNode(),
usesExtendsBound: this.deserializeBoolean()
};
}, function () {
return {
type: 'TypeParameterInstantiation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList()
};
}, function () {
return {
type: 'ComponentTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ComponentTypeParameter',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclaredPredicate',
loc: this.addEmptyLoc(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'InferredPredicate',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXElement',
loc: this.addEmptyLoc(),
openingElement: this.deserializeNode(),
children: this.deserializeNodeList(),
closingElement: this.deserializeNode()
};
}, function () {
return {
type: 'JSXFragment',
loc: this.addEmptyLoc(),
openingFragment: this.deserializeNode(),
children: this.deserializeNodeList(),
closingFragment: this.deserializeNode()
};
}, function () {
return {
type: 'JSXOpeningElement',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
attributes: this.deserializeNodeList(),
selfClosing: this.deserializeBoolean(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'JSXOpeningFragment',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXClosingElement',
loc: this.addEmptyLoc(),
name: this.deserializeNode()
};
}, function () {
return {
type: 'JSXClosingFragment',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXAttribute',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'JSXSpreadAttribute',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'JSXEmptyExpression',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXExpressionContainer',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'JSXSpreadChild',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'JSXText',
loc: this.addEmptyLoc(),
value: this.deserializeString(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'JSXMemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'JSXNamespacedName',
loc: this.addEmptyLoc(),
namespace: this.deserializeNode(),
name: this.deserializeNode()
};
}, function () {
return {
type: 'JSXIdentifier',
loc: this.addEmptyLoc(),
name: this.deserializeString()
};
}, function () {
return {
type: 'EnumBooleanBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumBooleanMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumNumberBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumNumberMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumStringBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumStringMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumSymbolBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumDefaultedMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'EnumBigIntBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumBigIntMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationBody',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList()
};
}, function () {
return {
type: 'RecordDeclarationProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
defaultValue: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationStaticProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationImplements',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'MatchExpressionCase',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
body: this.deserializeNode(),
guard: this.deserializeNode()
};
}, function () {
return {
type: 'MatchStatementCase',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
body: this.deserializeNode(),
guard: this.deserializeNode()
};
}, function () {
return {
type: 'MatchWildcardPattern',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MatchLiteralPattern',
loc: this.addEmptyLoc(),
literal: this.deserializeNode()
};
}, function () {
return {
type: 'MatchUnaryPattern',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'MatchObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchInstancePattern',
loc: this.addEmptyLoc(),
targetConstructor: this.deserializeNode(),
properties: this.deserializeNode()
};
}, function () {
return {
type: 'MatchInstanceObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchOrPattern',
loc: this.addEmptyLoc(),
patterns: this.deserializeNodeList()
};
}, function () {
return {
type: 'MatchAsPattern',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
target: this.deserializeNode()
};
}, function () {
return {
type: 'MatchIdentifierPattern',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'MatchMemberPattern',
loc: this.addEmptyLoc(),
base: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'MatchBindingPattern',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'MatchArrayPattern',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchObjectPatternProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
pattern: this.deserializeNode(),
shorthand: this.deserializeBoolean()
};
}, function () {
return {
type: 'MatchRestPattern',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'InterpreterDirective',
loc: this.addEmptyLoc(),
value: this.deserializeString()
};
}, function () {
return {
type: 'FunctionTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
this: this.deserializeNode(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'RendersType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'RendersMaybeType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'RendersStarType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TemplateLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
quasis: this.deserializeNodeList(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'NamespaceExportDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareClassExtendsCall',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'OpaqueType',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
impltype: this.deserializeNode(),
lowerBound: this.deserializeNode(),
upperBound: this.deserializeNode(),
supertype: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareOpaqueType',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
impltype: this.deserializeNode(),
lowerBound: this.deserializeNode(),
upperBound: this.deserializeNode(),
supertype: this.deserializeNode()
};
}, function () {
return {
type: 'EnumBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeString(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'HookTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ConstructorTypeAnnotation',
loc: this.addEmptyLoc(),
abstract: this.deserializeBoolean(),
params: this.deserializeNodeList(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypePrivateField',
loc: this.addEmptyLoc(),
key: this.deserializeNode()
};
}, function () {
return {
type: 'TupleTypeElement',
loc: this.addEmptyLoc(),
elementType: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclareComponent',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
id: this.deserializeNode(),
implicitDeclare: this.deserializeBoolean(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'ThisTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ChainExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}];

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

'use strict';
module.exports = {
AbstractMethodDefinition: ['key', 'value'],
AbstractPropertyDefinition: ['key', 'value', 'variance'],
AnyTypeAnnotation: [],
ArrayExpression: ['elements'],
ArrayPattern: ['elements', 'typeAnnotation'],
ArrayTypeAnnotation: ['elementType'],
ArrowFunctionExpression: ['params', 'body', 'typeParameters', 'returnType', 'predicate'],
AsConstExpression: ['expression'],
AsExpression: ['expression', 'typeAnnotation'],
AssignmentExpression: ['left', 'right'],
AssignmentPattern: ['left', 'right'],
AwaitExpression: ['argument'],
BigIntLiteralTypeAnnotation: [],
BigIntTypeAnnotation: [],
BinaryExpression: ['left', 'right'],
BlockStatement: ['body'],
BooleanLiteralTypeAnnotation: [],
BooleanTypeAnnotation: [],
BreakStatement: ['label'],
CallExpression: ['callee', 'typeArguments', 'arguments'],
CatchClause: ['param', 'body'],
ChainExpression: ['expression'],
ClassBody: ['body'],
ClassDeclaration: ['id', 'typeParameters', 'superClass', 'superTypeArguments', 'implements', 'decorators', 'body'],
ClassExpression: ['id', 'typeParameters', 'superClass', 'superTypeArguments', 'implements', 'decorators', 'body'],
ClassImplements: ['id', 'typeParameters'],
ComponentDeclaration: ['id', 'params', 'body', 'typeParameters', 'rendersType'],
ComponentParameter: ['name', 'local'],
ComponentTypeAnnotation: ['params', 'rest', 'typeParameters', 'rendersType'],
ComponentTypeParameter: ['name', 'typeAnnotation'],
ConditionalExpression: ['test', 'consequent', 'alternate'],
ConditionalTypeAnnotation: ['checkType', 'extendsType', 'trueType', 'falseType'],
ConstructorTypeAnnotation: ['params', 'returnType', 'rest', 'typeParameters'],
ContinueStatement: ['label'],
DebuggerStatement: [],
DeclareClass: ['id', 'typeParameters', 'extends', 'implements', 'mixins', 'body'],
DeclareClassExtendsCall: ['callee', 'argument'],
DeclareComponent: ['id', 'params', 'rest', 'typeParameters', 'rendersType'],
DeclareEnum: ['id', 'body'],
DeclareExportAllDeclaration: ['source'],
DeclareExportDeclaration: ['declaration', 'specifiers', 'source'],
DeclareFunction: ['id', 'predicate'],
DeclareHook: ['id'],
DeclareInterface: ['id', 'typeParameters', 'extends', 'body'],
DeclareMethodDefinition: ['key', 'value'],
DeclareModule: ['id', 'body'],
DeclareModuleExports: ['typeAnnotation'],
DeclareNamespace: ['id', 'body'],
DeclareOpaqueType: ['id', 'typeParameters', 'impltype', 'lowerBound', 'upperBound', 'supertype'],
DeclareTypeAlias: ['id', 'typeParameters', 'right'],
DeclareVariable: ['id'],
DeclaredPredicate: ['value'],
Decorator: ['expression'],
DoWhileStatement: ['body', 'test'],
EmptyStatement: [],
EmptyTypeAnnotation: [],
EnumBigIntBody: ['members'],
EnumBigIntMember: ['id', 'init'],
EnumBody: ['members'],
EnumBooleanBody: ['members'],
EnumBooleanMember: ['id', 'init'],
EnumDeclaration: ['id', 'body'],
EnumDefaultedMember: ['id'],
EnumNumberBody: ['members'],
EnumNumberMember: ['id', 'init'],
EnumStringBody: ['members'],
EnumStringMember: ['id', 'init'],
EnumSymbolBody: ['members'],
ExistsTypeAnnotation: [],
ExportAllDeclaration: ['exported', 'source'],
ExportAssignment: ['expression'],
ExportDefaultDeclaration: ['declaration'],
ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
ExportNamespaceSpecifier: ['exported'],
ExportSpecifier: ['exported', 'local'],
ExpressionStatement: ['expression'],
ExternalModuleReference: ['expression'],
ForInStatement: ['left', 'right', 'body'],
ForOfStatement: ['left', 'right', 'body'],
ForStatement: ['init', 'test', 'update', 'body'],
FunctionDeclaration: ['id', 'params', 'body', 'typeParameters', 'returnType', 'predicate'],
FunctionExpression: ['id', 'params', 'body', 'typeParameters', 'returnType', 'predicate'],
FunctionTypeAnnotation: ['params', 'this', 'returnType', 'rest', 'typeParameters'],
FunctionTypeParam: ['name', 'typeAnnotation'],
GenericTypeAnnotation: ['id', 'typeParameters'],
HookDeclaration: ['id', 'params', 'body', 'typeParameters', 'returnType'],
HookTypeAnnotation: ['params', 'returnType', 'rest', 'typeParameters'],
Identifier: ['typeAnnotation'],
IfStatement: ['test', 'consequent', 'alternate'],
ImportAttribute: ['key', 'value'],
ImportDeclaration: ['specifiers', 'source', 'attributes'],
ImportDefaultSpecifier: ['local'],
ImportEqualsDeclaration: ['id', 'moduleReference'],
ImportExpression: ['source', 'options'],
ImportNamespaceSpecifier: ['local'],
ImportSpecifier: ['imported', 'local'],
ImportType: ['argument'],
IndexedAccessType: ['objectType', 'indexType'],
InferTypeAnnotation: ['typeParameter'],
InferredPredicate: [],
InterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'],
InterfaceExtends: ['id', 'typeParameters'],
InterfaceTypeAnnotation: ['extends', 'body'],
InterpreterDirective: [],
IntersectionTypeAnnotation: ['types'],
JSXAttribute: ['name', 'value'],
JSXClosingElement: ['name'],
JSXClosingFragment: [],
JSXElement: ['openingElement', 'children', 'closingElement'],
JSXEmptyExpression: [],
JSXExpressionContainer: ['expression'],
JSXFragment: ['openingFragment', 'children', 'closingFragment'],
JSXIdentifier: [],
JSXMemberExpression: ['object', 'property'],
JSXNamespacedName: ['namespace', 'name'],
JSXOpeningElement: ['name', 'attributes', 'typeArguments'],
JSXOpeningFragment: [],
JSXSpreadAttribute: ['argument'],
JSXSpreadChild: ['expression'],
JSXText: [],
KeyofTypeAnnotation: ['argument'],
LabeledStatement: ['label', 'body'],
LogicalExpression: ['left', 'right'],
MatchArrayPattern: ['elements', 'rest'],
MatchAsPattern: ['pattern', 'target'],
MatchBindingPattern: ['id'],
MatchExpression: ['argument', 'cases'],
MatchExpressionCase: ['pattern', 'body', 'guard'],
MatchIdentifierPattern: ['id'],
MatchInstanceObjectPattern: ['properties', 'rest'],
MatchInstancePattern: ['targetConstructor', 'properties'],
MatchLiteralPattern: ['literal'],
MatchMemberPattern: ['base', 'property'],
MatchObjectPattern: ['properties', 'rest'],
MatchObjectPatternProperty: ['key', 'pattern'],
MatchOrPattern: ['patterns'],
MatchRestPattern: ['argument'],
MatchStatement: ['argument', 'cases'],
MatchStatementCase: ['pattern', 'body', 'guard'],
MatchUnaryPattern: ['argument'],
MatchWildcardPattern: [],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', 'property'],
MethodDefinition: ['key', 'value', 'decorators'],
MixedTypeAnnotation: [],
NamespaceExportDeclaration: ['id'],
NeverTypeAnnotation: [],
NewExpression: ['callee', 'typeArguments', 'arguments'],
NonNullExpression: ['argument'],
NullLiteralTypeAnnotation: [],
NullableTypeAnnotation: ['typeAnnotation'],
NumberLiteralTypeAnnotation: [],
NumberTypeAnnotation: [],
ObjectExpression: ['properties'],
ObjectPattern: ['properties', 'typeAnnotation'],
ObjectTypeAnnotation: ['properties', 'indexers', 'callProperties', 'internalSlots'],
ObjectTypeCallProperty: ['value'],
ObjectTypeIndexer: ['id', 'key', 'value', 'variance'],
ObjectTypeInternalSlot: ['id', 'value'],
ObjectTypeMappedTypeProperty: ['keyTparam', 'propType', 'sourceType', 'variance'],
ObjectTypePrivateField: ['key'],
ObjectTypeProperty: ['key', 'value', 'variance'],
ObjectTypeSpreadProperty: ['argument'],
OpaqueType: ['id', 'typeParameters', 'impltype', 'lowerBound', 'upperBound', 'supertype'],
OptionalIndexedAccessType: ['objectType', 'indexType'],
ParameterProperty: ['key', 'value', 'typeAnnotation', 'variance', 'decorators'],
PrivateIdentifier: [],
Program: ['body'],
Property: ['key', 'value'],
PropertyDefinition: ['key', 'value', 'decorators', 'variance', 'typeAnnotation'],
QualifiedTypeIdentifier: ['qualification', 'id'],
QualifiedTypeofIdentifier: ['qualification', 'id'],
RecordDeclaration: ['id', 'typeParameters', 'implements', 'body'],
RecordDeclarationBody: ['elements'],
RecordDeclarationImplements: ['id', 'typeArguments'],
RecordDeclarationProperty: ['key', 'typeAnnotation', 'defaultValue'],
RecordDeclarationStaticProperty: ['key', 'typeAnnotation', 'value'],
RecordExpression: ['recordConstructor', 'typeArguments', 'properties'],
RecordExpressionProperties: ['properties'],
RendersMaybeType: ['argument'],
RendersStarType: ['argument'],
RendersType: ['argument'],
RestElement: ['argument'],
ReturnStatement: ['argument'],
SatisfiesExpression: ['expression', 'typeAnnotation'],
SequenceExpression: ['expressions'],
SpreadElement: ['argument'],
StaticBlock: ['body'],
StringLiteralTypeAnnotation: [],
StringTypeAnnotation: [],
Super: [],
SwitchCase: ['test', 'consequent'],
SwitchStatement: ['discriminant', 'cases'],
SymbolTypeAnnotation: [],
TaggedTemplateExpression: ['tag', 'quasi'],
TemplateElement: [],
TemplateLiteral: ['quasis', 'expressions'],
TemplateLiteralTypeAnnotation: ['quasis', 'types'],
ThisExpression: [],
ThisTypeAnnotation: [],
ThrowStatement: ['argument'],
TryStatement: ['block', 'handler', 'finalizer'],
TupleTypeAnnotation: ['elementTypes'],
TupleTypeElement: ['elementType'],
TupleTypeLabeledElement: ['label', 'elementType', 'variance'],
TupleTypeSpreadElement: ['label', 'typeAnnotation'],
TypeAlias: ['id', 'typeParameters', 'right'],
TypeAnnotation: ['typeAnnotation'],
TypeCastExpression: ['expression', 'typeAnnotation'],
TypeOperator: ['typeAnnotation'],
TypeParameter: ['bound', 'variance', 'default'],
TypeParameterDeclaration: ['params'],
TypeParameterInstantiation: ['params'],
TypePredicate: ['parameterName', 'typeAnnotation'],
TypeofTypeAnnotation: ['argument', 'typeArguments'],
UnaryExpression: ['argument'],
UndefinedTypeAnnotation: [],
UnionTypeAnnotation: ['types'],
UnknownTypeAnnotation: [],
UpdateExpression: ['argument'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
Variance: [],
VoidTypeAnnotation: [],
WhileStatement: ['test', 'body'],
WithStatement: ['object', 'body'],
YieldExpression: ['argument'],
OptionalMemberExpression: ['object', 'property'],
OptionalCallExpression: ['callee', 'typeArguments', 'arguments'],
Literal: []
};

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getModuleDocblock = getModuleDocblock;
exports.parseDocblockString = parseDocblockString;
const DIRECTIVE_REGEX = /^\s*@([a-zA-Z0-9_-]+)( +.+)?$/;
function parseDocblockString(docblock) {
const directiveLines = docblock.split('\n').map(line => line.trimStart().replace(/^\* ?/, '').trim()).filter(line => line.startsWith('@'));
const directives = Object.create(null);
for (const line of directiveLines) {
var _match$;
const match = DIRECTIVE_REGEX.exec(line);
if (match == null) {
continue;
}
const name = match[1];
const value = ((_match$ = match[2]) != null ? _match$ : '').trim();
if (directives[name]) {
directives[name].push(value);
} else {
directives[name] = [value];
}
}
return directives;
}
function getModuleDocblock(hermesProgram) {
const docblockNode = (() => {
if (hermesProgram.type !== 'Program') {
return null;
}
const program = hermesProgram;
if (program.comments.length === 0) {
return null;
}
const firstComment = (() => {
const first = program.comments[0];
if (first.type === 'Block') {
return first;
}
if (program.comments.length === 1) {
return null;
}
const second = program.comments[1];
if (first.type === 'Line' && first.range[0] === 0 && second.type === 'Block') {
return second;
}
return null;
})();
if (firstComment == null) {
return null;
}
if (program.body.length > 0 && program.body[0].range[0] < firstComment.range[0]) {
return null;
}
return firstComment;
})();
if (docblockNode == null) {
return null;
}
return {
directives: parseDocblockString(docblockNode.value),
comment: docblockNode
};
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = HermesParserDecodeUTF8String;
function HermesParserDecodeUTF8String(ptrIn, length, heap) {
let ptr = ptrIn;
const endPtr = ptr + length;
let str = '';
while (ptr < endPtr) {
let u0 = heap[ptr++];
if (!(u0 & 0x80)) {
str += String.fromCharCode(u0);
continue;
}
const u1 = heap[ptr++] & 0x3f;
if ((u0 & 0xe0) === 0xc0) {
str += String.fromCharCode((u0 & 0x1f) << 6 | u1);
continue;
}
const u2 = heap[ptr++] & 0x3f;
if ((u0 & 0xf0) === 0xe0) {
u0 = (u0 & 0x0f) << 12 | u1 << 6 | u2;
} else {
u0 = (u0 & 0x07) << 18 | u1 << 12 | u2 << 6 | heap[ptr++] & 0x3f;
}
if (u0 < 0x10000) {
str += String.fromCharCode(u0);
} else {
u0 -= 0x10000;
str += String.fromCharCode(0xd800 | u0 >> 10, 0xdc00 | u0 & 0x3ff);
}
}
return str;
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
parse: true,
mutateESTreeASTForPrettier: true,
Transforms: true,
FlowVisitorKeys: true,
astArrayMutationHelpers: true,
astNodeMutationHelpers: true
};
exports.mutateESTreeASTForPrettier = exports.astNodeMutationHelpers = exports.astArrayMutationHelpers = exports.Transforms = void 0;
exports.parse = parse;
var FlowParser = _interopRequireWildcard(require("./FlowParser"));
var _ESTreeVisitorKeys = _interopRequireDefault(require("./generated/ESTreeVisitorKeys"));
exports.FlowVisitorKeys = _ESTreeVisitorKeys.default;
var TransformComponentSyntax = _interopRequireWildcard(require("./estree/TransformComponentSyntax"));
var TransformEnumSyntax = _interopRequireWildcard(require("./estree/TransformEnumSyntax"));
var TransformMatchSyntax = _interopRequireWildcard(require("./estree/TransformMatchSyntax"));
var TransformRecordSyntax = _interopRequireWildcard(require("./estree/TransformRecordSyntax"));
var StripFlowTypesForBabel = _interopRequireWildcard(require("./estree/StripFlowTypesForBabel"));
var TransformESTreeToBabel = _interopRequireWildcard(require("./babel/TransformESTreeToBabel"));
var StripFlowTypes = _interopRequireWildcard(require("./estree/StripFlowTypes"));
var _ParserOptions = require("./ParserOptions");
Object.keys(_ParserOptions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _ParserOptions[key]) return;
exports[key] = _ParserOptions[key];
});
var _SimpleTraverser = require("./traverse/SimpleTraverser");
Object.keys(_SimpleTraverser).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _SimpleTraverser[key]) return;
exports[key] = _SimpleTraverser[key];
});
var _SimpleTransform = require("./transform/SimpleTransform");
Object.keys(_SimpleTransform).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _SimpleTransform[key]) return;
exports[key] = _SimpleTransform[key];
});
var _getVisitorKeys = require("./traverse/getVisitorKeys");
Object.keys(_getVisitorKeys).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _getVisitorKeys[key]) return;
exports[key] = _getVisitorKeys[key];
});
var _astArrayMutationHelpers = _interopRequireWildcard(require("./transform/astArrayMutationHelpers"));
exports.astArrayMutationHelpers = _astArrayMutationHelpers;
var _astNodeMutationHelpers = _interopRequireWildcard(require("./transform/astNodeMutationHelpers"));
exports.astNodeMutationHelpers = _astNodeMutationHelpers;
var _mutateESTreeASTForPrettier = _interopRequireDefault(require("./utils/mutateESTreeASTForPrettier"));
exports.mutateESTreeASTForPrettier = _mutateESTreeASTForPrettier.default;
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const DEFAULTS = {
flow: 'detect'
};
function getOptions(opts) {
const options = { ...DEFAULTS,
...(opts != null ? opts : {})
};
if (options.flow !== 'all' && options.flow !== 'detect') {
throw new Error('flow option must be "all" or "detect"');
}
if (options.sourceType === 'unambiguous') {
delete options.sourceType;
} else if (options.sourceType != null && options.sourceType !== 'script' && options.sourceType !== 'module') {
throw new Error('sourceType option must be "script", "module", or "unambiguous" if set');
}
if (options.enableExperimentalComponentSyntax == null) {
options.enableExperimentalComponentSyntax = true;
}
if (options.enableExperimentalFlowMatchSyntax == null) {
options.enableExperimentalFlowMatchSyntax = true;
}
if (options.enableExperimentalFlowRecordSyntax == null) {
options.enableExperimentalFlowRecordSyntax = true;
}
options.enableRecords = options.enableExperimentalFlowRecordSyntax;
if (options.enableEnums == null) {
options.enableEnums = true;
}
if (options.enableExperimentalDecorators == null) {
options.enableExperimentalDecorators = true;
}
options.tokens = options.tokens === true;
options.allowReturnOutsideFunction = options.allowReturnOutsideFunction === true;
return options;
}
function parse(code, opts) {
var _options$transformOpt, _options$transformOpt2;
const options = getOptions(opts);
if (options.flow === 'all') {
options.enableTypes = true;
} else {
options.enableTypesPragmaDetection = true;
}
const estreeAST = FlowParser.parse(code, options);
if (options.babel !== true) {
return estreeAST;
}
const loweredESTreeAST = [(_options$transformOpt = options.transformOptions) != null && (_options$transformOpt2 = _options$transformOpt.TransformEnumSyntax) != null && _options$transformOpt2.enable ? TransformEnumSyntax.transformProgram : null, TransformMatchSyntax.transformProgram, TransformComponentSyntax.transformProgram, TransformRecordSyntax.transformProgram, StripFlowTypesForBabel.transformProgram].reduce((ast, transform) => {
var _transform;
return (_transform = transform == null ? void 0 : transform(ast, options)) != null ? _transform : ast;
}, estreeAST);
return TransformESTreeToBabel.transformProgram(loweredESTreeAST, options);
}
const Transforms = {
transformEnumSyntax: TransformEnumSyntax.transformProgram,
transformMatchSyntax: TransformMatchSyntax.transformProgram,
transformComponentSyntax: TransformComponentSyntax.transformProgram,
transformRecordSyntax: TransformRecordSyntax.transformProgram,
stripFlowTypesForBabel: StripFlowTypesForBabel.transformProgram,
stripFlowTypes: StripFlowTypes.transformProgram
};
exports.Transforms = Transforms;

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _ESTreeVisitorKeys = _interopRequireDefault(require("../generated/ESTreeVisitorKeys"));
var _createSyntaxError = require("../utils/createSyntaxError");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const EMPTY_PARENT = null;
const FlowESTreeAndBabelVisitorKeys = { ..._ESTreeVisitorKeys.default,
BigIntLiteral: [],
BlockStatement: ['directives', ..._ESTreeVisitorKeys.default.BlockStatement],
BooleanLiteral: [],
ClassExpression: ['superTypeParameters', ..._ESTreeVisitorKeys.default.ClassExpression],
ClassDeclaration: ['superTypeParameters', ..._ESTreeVisitorKeys.default.ClassDeclaration],
ClassMethod: ['key', 'params', 'body', 'returnType', 'typeParameters'],
ClassPrivateMethod: ['key', 'params', 'body', 'returnType', 'typeParameters'],
ClassProperty: ['key', 'value', 'typeAnnotation', 'variance'],
ClassPrivateProperty: ['key', 'value', 'typeAnnotation', 'variance'],
Directive: ['value'],
DirectiveLiteral: [],
ExportNamespaceSpecifier: ['exported'],
File: ['program', 'comments'],
Import: [],
NullLiteral: [],
NumericLiteral: [],
ObjectMethod: [..._ESTreeVisitorKeys.default.Property, 'params', 'body', 'returnType', 'typeParameters'],
ObjectProperty: _ESTreeVisitorKeys.default.Property,
OptionalCallExpression: ['callee', 'arguments', 'typeArguments'],
OptionalMemberExpression: ['object', 'property'],
PrivateName: ['id'],
Program: ['directives', ..._ESTreeVisitorKeys.default.Program],
RegExpLiteral: [],
RestElement: [..._ESTreeVisitorKeys.default.RestElement, 'typeAnnotation'],
StringLiteral: [],
TupleTypeAnnotation: ['types'],
CommentBlock: [],
CommentLine: []
};
function nodeWith(node, overrideProps) {
return _SimpleTransform.SimpleTransform.nodeWith(node, overrideProps, FlowESTreeAndBabelVisitorKeys);
}
function fixSourceLocation(node, _options) {
const loc = node.loc;
if (loc == null) {
return;
}
node.loc = {
start: loc.start,
end: loc.end
};
if (node.type === 'Identifier') {
node.loc.identifierName = node.name;
}
node.start = node.range[0];
node.end = node.range[1];
delete node.range;
delete node.parent;
}
function mapNodeWithDirectives(node) {
if (node.directives != null) {
return node;
}
const directives = [];
for (const child of node.body) {
if (child.type === 'ExpressionStatement' && child.directive != null) {
directives.push({
type: 'Directive',
value: {
type: 'DirectiveLiteral',
value: child.directive,
extra: {
rawValue: child.directive,
raw: child.expression.type === 'Literal' ? child.expression.raw : ''
},
loc: child.expression.loc,
range: child.expression.range,
parent: EMPTY_PARENT
},
loc: child.loc,
range: child.range,
parent: node
});
} else {
break;
}
}
return nodeWith(node, {
directives,
body: directives.length === 0 ? node.body : node.body.slice(directives.length)
});
}
function mapProgram(node) {
var _program$directives;
const program = mapNodeWithDirectives(node);
const startLoc = {
line: 1,
column: 0
};
let endLoc = program.loc.end;
let endRange = program.range[1];
if (program.comments.length > 0) {
const lastComment = program.comments[program.comments.length - 1];
if (lastComment.range[1] > endRange) {
endLoc = lastComment.loc.end;
endRange = lastComment.range[1];
}
}
const loc = {
start: startLoc,
end: endLoc
};
const range = [0, endRange];
const babelComments = program.comments.map(comment => {
switch (comment.type) {
case 'Line':
{
return {
type: 'CommentLine',
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
case 'Block':
{
return {
type: 'CommentBlock',
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
}
});
return {
type: 'File',
program: {
type: 'Program',
body: program.body,
directives: (_program$directives = program.directives) != null ? _program$directives : [],
sourceType: program.sourceType,
interpreter: program.interpreter,
loc,
range,
parent: EMPTY_PARENT
},
comments: babelComments,
loc,
range,
parent: EMPTY_PARENT
};
}
function mapTemplateElement(node) {
const startCharsToExclude = 1;
const endCharsToExclude = node.tail ? 1 : 2;
node.loc = {
start: {
line: node.loc.start.line,
column: node.loc.start.column + startCharsToExclude
},
end: {
line: node.loc.end.line,
column: node.loc.end.column - endCharsToExclude
}
};
node.range = [node.range[0] + startCharsToExclude, node.range[1] - endCharsToExclude];
return node;
}
function mapProperty(node) {
const key = node.key;
const value = node.value;
if (node.method || node.kind !== 'init') {
if (value.type !== 'FunctionExpression') {
throw (0, _createSyntaxError.createSyntaxError)(node, `Invalid method property, the value must be a "FunctionExpression" or "ArrowFunctionExpression. Instead got "${value.type}".`);
}
const newNode = {
type: 'ObjectMethod',
kind: node.kind === 'init' ? 'method' : node.kind,
method: node.kind === 'init' ? true : false,
computed: node.computed,
key: key,
id: null,
params: value.params,
body: value.body,
async: value.async,
generator: value.generator,
returnType: value.returnType,
typeParameters: value.typeParameters,
loc: node.loc,
range: node.range,
parent: node.parent
};
if (node.kind !== 'init') {
newNode.variance = null;
}
return newNode;
}
const propertyValue = value;
return {
type: 'ObjectProperty',
computed: node.computed,
key: node.key,
value: propertyValue,
method: node.method,
shorthand: node.shorthand,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapMethodDefinition(node) {
const value = node.value;
const BaseClassMethod = {
kind: node.kind,
computed: node.computed,
static: node.static,
key: node.key,
id: null,
params: value.params,
body: value.body,
async: value.async,
generator: value.generator,
returnType: value.returnType,
typeParameters: value.typeParameters,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
if (node.key.type === 'PrivateIdentifier') {
return { ...BaseClassMethod,
type: 'ClassPrivateMethod'
};
}
return { ...BaseClassMethod,
type: 'ClassMethod'
};
}
function mapExportAllDeclaration(node) {
if (node.exported != null) {
return {
type: 'ExportNamedDeclaration',
declaration: null,
specifiers: [{
type: 'ExportNamespaceSpecifier',
exported: node.exported,
loc: {
start: {
column: node.loc.start.column + 'export '.length,
line: node.loc.start.line
},
end: node.exported.loc.end
},
range: [node.range[0] + 'export '.length, node.exported.range[1]],
parent: EMPTY_PARENT
}],
source: node.source,
exportKind: node.exportKind,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
delete node.exported;
return node;
}
function mapRestElement(node) {
const argument = node.argument;
if ((argument.type === 'Identifier' || argument.type === 'ObjectPattern' || argument.type === 'ArrayPattern') && argument.typeAnnotation != null) {
const argumentRange = argument.range;
let argumentLoc = argument.loc;
if (argument.type === 'Identifier') {
argumentRange[1] = argumentRange[0] + argument.name.length;
argumentLoc = {
start: argumentLoc.start,
end: {
line: argumentLoc.start.line,
column: argumentLoc.start.column + argument.name.length
}
};
}
return nodeWith(node, {
typeAnnotation: argument.typeAnnotation,
argument: nodeWith(argument, {
typeAnnotation: null,
range: argumentRange,
loc: argumentLoc
})
});
}
return node;
}
function mapImportExpression(node) {
return {
type: 'CallExpression',
callee: {
type: 'Import',
loc: {
start: node.loc.start,
end: {
line: node.loc.start.line,
column: node.loc.start.column + 'import'.length
}
},
range: [node.range[0], node.range[0] + 'import'.length],
parent: EMPTY_PARENT
},
arguments: [node.source],
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapPrivateIdentifier(node) {
return {
type: 'PrivateName',
id: {
type: 'Identifier',
name: node.name,
optional: false,
typeAnnotation: null,
loc: {
start: {
line: node.loc.start.line,
column: node.loc.start.column + 1
},
end: node.loc.end
},
range: [node.range[0] + 1, node.range[1]],
parent: EMPTY_PARENT
},
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapPropertyDefinition(node) {
if (node.key.type === 'PrivateIdentifier') {
return {
type: 'ClassPrivateProperty',
key: mapPrivateIdentifier(node.key),
value: node.value,
typeAnnotation: node.typeAnnotation,
static: node.static,
variance: node.variance,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
return {
type: 'ClassProperty',
key: node.key,
value: node.value,
typeAnnotation: node.typeAnnotation,
static: node.static,
variance: node.variance,
declare: node.declare,
optional: node.optional,
computed: node.computed,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapTypeofTypeAnnotation(node) {
delete node.typeArguments;
if (node.argument.type !== 'GenericTypeAnnotation') {
return nodeWith(node, {
argument: {
type: 'GenericTypeAnnotation',
id: node.argument,
typeParameters: null,
loc: node.argument.loc,
range: node.argument.range,
parent: EMPTY_PARENT
}
});
}
return node;
}
function mapDeclareVariable(node) {
if (node.kind != null) {
delete node.kind;
}
return node;
}
function mapJSXElement(node) {
if (node.openingElement.typeArguments != null) {
delete node.openingElement.typeArguments;
}
return node;
}
function mapChainExpressionInnerNode(node) {
switch (node.type) {
case 'MemberExpression':
{
const innerObject = mapChainExpressionInnerNode(node.object);
if (!node.optional && innerObject.type !== 'OptionalMemberExpression' && innerObject.type !== 'OptionalCallExpression') {
return node;
}
return {
type: 'OptionalMemberExpression',
object: innerObject,
property: node.property,
computed: node.computed,
optional: node.optional,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
case 'CallExpression':
{
const innerCallee = mapChainExpressionInnerNode(node.callee);
if (!node.optional && innerCallee.type !== 'OptionalMemberExpression' && innerCallee.type !== 'OptionalCallExpression') {
return node;
}
return {
type: 'OptionalCallExpression',
callee: innerCallee,
optional: node.optional,
arguments: node.arguments,
typeArguments: node.typeArguments,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
default:
{
return node;
}
}
}
function mapChainExpression(node) {
return mapChainExpressionInnerNode(node.expression);
}
function mapLiteral(node) {
const base = {
loc: node.loc,
range: node.range,
parent: node.parent
};
switch (node.literalType) {
case 'string':
{
return {
type: 'StringLiteral',
value: node.value,
extra: {
rawValue: node.value,
raw: node.raw
},
...base
};
}
case 'numeric':
{
return {
type: 'NumericLiteral',
value: node.value,
extra: {
rawValue: node.value,
raw: node.raw
},
...base
};
}
case 'bigint':
{
return {
type: 'BigIntLiteral',
value: node.bigint,
extra: {
rawValue: node.bigint,
raw: node.raw
},
...base
};
}
case 'boolean':
{
return {
type: 'BooleanLiteral',
value: node.value,
...base
};
}
case 'null':
{
return {
type: 'NullLiteral',
...base
};
}
case 'regexp':
{
return {
type: 'RegExpLiteral',
extra: {
raw: node.raw
},
pattern: node.regex.pattern,
flags: node.regex.flags,
...base
};
}
}
}
function transformNode(node) {
switch (node.type) {
case 'Program':
{
var _node$parent;
if (((_node$parent = node.parent) == null ? void 0 : _node$parent.type) === 'File') {
return node;
}
return mapProgram(node);
}
case 'BlockStatement':
{
return mapNodeWithDirectives(node);
}
case 'Property':
{
return mapProperty(node);
}
case 'TemplateElement':
{
return mapTemplateElement(node);
}
case 'MethodDefinition':
{
return mapMethodDefinition(node);
}
case 'ExportAllDeclaration':
{
return mapExportAllDeclaration(node);
}
case 'RestElement':
{
return mapRestElement(node);
}
case 'ImportExpression':
{
return mapImportExpression(node);
}
case 'PrivateIdentifier':
{
return mapPrivateIdentifier(node);
}
case 'PropertyDefinition':
{
return mapPropertyDefinition(node);
}
case 'TypeofTypeAnnotation':
{
return mapTypeofTypeAnnotation(node);
}
case 'DeclareVariable':
{
return mapDeclareVariable(node);
}
case 'JSXElement':
{
return mapJSXElement(node);
}
case 'Literal':
{
return mapLiteral(node);
}
case 'ChainExpression':
{
return mapChainExpression(node);
}
case 'TypeCastExpression':
{
node.loc.start.column = node.loc.start.column + 1;
node.loc.end.column = node.loc.end.column - 1;
node.range = [node.range[0] + 1, node.range[1] - 1];
return node;
}
case 'AsExpression':
{
const {
typeAnnotation
} = node;
node.type = 'TypeCastExpression';
node.typeAnnotation = {
type: 'TypeAnnotation',
typeAnnotation,
loc: typeAnnotation.loc,
range: typeAnnotation.range
};
return node;
}
case 'AsConstExpression':
{
return node.expression;
}
case 'NumberLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'StringLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'BigIntLiteralTypeAnnotation':
{
node.extra = {
rawValue: node.bigint,
raw: node.raw
};
delete node.bigint;
delete node.raw;
return node;
}
case 'BooleanLiteralTypeAnnotation':
{
delete node.raw;
return node;
}
case 'TupleTypeAnnotation':
{
delete node.inexact;
node.types = node.elementTypes;
delete node.elementTypes;
return node;
}
case 'UnknownTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'unknown',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'NeverTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'never',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'UndefinedTypeAnnotation':
{
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: 'undefined',
optional: false,
typeAnnotation: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
};
}
case 'JSXText':
{
node.extra = {
rawValue: node.value,
raw: node.raw
};
delete node.raw;
return node;
}
case 'Identifier':
{
if (node.optional === false || node.optional == null) {
delete node.optional;
}
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'CallExpression':
{
if (node.optional === false) {
delete node.optional;
}
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'OptionalCallExpression':
{
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'MemberExpression':
{
delete node.optional;
return node;
}
case 'ExpressionStatement':
{
delete node.directive;
return node;
}
case 'ObjectPattern':
case 'ArrayPattern':
{
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
case 'ClassMethod':
{
delete node.expression;
if (node.predicate == null) {
delete node.predicate;
}
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ObjectMethod':
{
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassPrivateMethod':
{
if (node.computed === false) {
delete node.computed;
}
if (node.predicate == null) {
delete node.predicate;
}
if (node.returnType == null) {
delete node.returnType;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassExpression':
case 'ClassDeclaration':
{
if (node.decorators == null || node.decorators.length === 0) {
delete node.decorators;
}
if (node.implements == null || node.implements.length === 0) {
delete node.implements;
}
if (node.superTypeArguments == null) {
delete node.superTypeArguments;
} else {
node.superTypeParameters = node.superTypeArguments;
delete node.superTypeArguments;
}
if (node.typeParameters == null) {
delete node.typeParameters;
}
return node;
}
case 'ClassProperty':
{
if (node.optional === false) {
delete node.optional;
}
if (node.declare === false) {
delete node.declare;
}
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'ClassPrivateProperty':
{
if (node.typeAnnotation == null) {
delete node.typeAnnotation;
}
return node;
}
case 'ExportNamedDeclaration':
{
if (node.declaration == null) {
delete node.declaration;
}
return node;
}
case 'ImportDeclaration':
{
if (node.attributes == null || node.attributes.length === 0) {
delete node.attributes;
}
return node;
}
case 'ArrayExpression':
{
delete node.trailingComma;
return node;
}
case 'JSXOpeningElement':
{
if (node.typeArguments == null) {
delete node.typeArguments;
}
return node;
}
case 'DeclareOpaqueType':
case 'OpaqueType':
{
if (node.lowerBound != null) {
delete node.lowerBound;
}
if (node.upperBound != null) {
delete node.upperBound;
}
return node;
}
default:
{
return node;
}
}
}
function transformProgram(program, options) {
var _resultNode$type;
const resultNode = _SimpleTransform.SimpleTransform.transform(program, {
transform(node) {
return transformNode(node);
},
visitorKeys: FlowESTreeAndBabelVisitorKeys
});
_SimpleTraverser.SimpleTraverser.traverse(resultNode, {
enter(node) {
fixSourceLocation(node, options);
},
leave() {},
visitorKeys: FlowESTreeAndBabelVisitorKeys
});
if ((resultNode == null ? void 0 : resultNode.type) === 'File') {
return resultNode;
}
throw new Error(`Unknown AST node of type "${(_resultNode$type = resultNode == null ? void 0 : resultNode.type) != null ? _resultNode$type : 'NULL'}" returned from Babel conversion`);
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
function transformProgram(program, _options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'AsExpression':
case 'AsConstExpression':
case 'TypeCastExpression':
{
return node.expression;
}
case 'CallExpression':
case 'NewExpression':
{
if (node.typeArguments != null) {
return nodeWith(node, {
typeArguments: null
});
}
return node;
}
case 'ObjectPattern':
case 'ArrayPattern':
case 'Identifier':
{
if (node.typeAnnotation != null) {
return nodeWith(node, {
typeAnnotation: null
});
}
return node;
}
case 'DeclareClass':
case 'DeclareFunction':
case 'DeclareInterface':
case 'DeclareModule':
case 'DeclareModuleExports':
case 'DeclareNamespace':
case 'DeclareOpaqueType':
case 'DeclareTypeAlias':
case 'DeclareVariable':
case 'InterfaceDeclaration':
case 'OpaqueType':
case 'TypeAlias':
{
return null;
}
case 'FunctionDeclaration':
case 'ArrowFunctionExpression':
case 'FunctionExpression':
{
const newParams = [];
for (let i = 0; i < node.params.length; i++) {
if (i === 0 && node.params[0].type === 'Identifier' && node.params[0].name === 'this') {
continue;
}
let param = node.params[i];
if (param.type === 'AssignmentPattern') {
param = param.left;
}
if (param.optional === true) {
param = nodeWith(param, {
optional: false
});
}
newParams.push(param);
}
return nodeWith(node, {
params: newParams,
returnType: null,
typeParameters: null,
predicate: null
});
}
case 'ClassDeclaration':
case 'ClassExpression':
{
return nodeWith(node, {
typeParameters: null,
superTypeArguments: null,
implements: [],
decorators: []
});
}
case 'PropertyDefinition':
{
return nodeWith(node, {
typeAnnotation: null,
variance: null,
declare: false,
optional: false
});
}
case 'ImportDeclaration':
{
if (node.importKind === 'type' || node.importKind === 'typeof') {
return null;
}
const nonTypeSpecifiers = node.specifiers.filter(s => s.type !== 'ImportSpecifier' || s.importKind !== 'type' && s.importKind !== 'typeof');
if (nonTypeSpecifiers.length === 0) {
return null;
}
if (nonTypeSpecifiers.length === node.specifiers.length) {
return node;
}
return nodeWith(node, {
specifiers: nonTypeSpecifiers
});
}
case 'ExportAllDeclaration':
case 'ExportNamedDeclaration':
{
if (node.exportKind === 'type') {
return null;
}
return node;
}
default:
{
return node;
}
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _createSyntaxError = require("../utils/createSyntaxError");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
const EMPTY_PARENT = null;
function createSimpleGenericTypeAnnotation(name, nodeForLoc) {
return {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name,
optional: false,
typeAnnotation: null,
loc: nodeForLoc.loc,
range: nodeForLoc.range,
parent: EMPTY_PARENT
},
typeParameters: null,
loc: nodeForLoc.loc,
range: nodeForLoc.range,
parent: nodeForLoc.parent
};
}
function createAnyTypeAnnotation(node) {
return {
type: 'AnyTypeAnnotation',
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapDeclareEnum(node) {
return {
type: 'DeclareVariable',
kind: 'const',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: createAnyTypeAnnotation(node.body),
loc: node.body.loc,
range: node.body.range,
parent: EMPTY_PARENT
}
}),
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapDeclareNamespace(node) {
return {
type: 'DeclareVariable',
kind: 'const',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: createAnyTypeAnnotation(node.body),
loc: node.body.loc,
range: node.body.range,
parent: EMPTY_PARENT
}
}),
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function mapFunction(node) {
if (node.params.length !== 0 && node.params[0].name === 'this') {
return nodeWith(node, {
params: node.params.slice(1)
});
}
return node;
}
function mapQualifiedTypeofIdentifier(node) {
return {
type: 'QualifiedTypeIdentifier',
qualification: node.qualification.type === 'QualifiedTypeofIdentifier' ? mapQualifiedTypeofIdentifier(node.qualification) : node.qualification,
id: node.id,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function transformProgram(program, _options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'SymbolTypeAnnotation':
{
return createSimpleGenericTypeAnnotation('symbol', node);
}
case 'BigIntTypeAnnotation':
{
return createSimpleGenericTypeAnnotation('bigint', node);
}
case 'ObjectTypeAnnotation':
{
const shouldStrip = node.properties.some(prop => prop.type === 'ObjectTypeMappedTypeProperty');
if (shouldStrip) {
return createAnyTypeAnnotation(node);
}
return node;
}
case 'ObjectTypeMappedTypeProperty':
{
throw (0, _createSyntaxError.createSyntaxError)(node, `Invalid AST structure, ObjectTypeMappedTypeProperty found outside of an ObjectTypeAnnotation`);
}
case 'IndexedAccessType':
case 'OptionalIndexedAccessType':
case 'KeyofTypeAnnotation':
case 'ConditionalTypeAnnotation':
case 'InferTypeAnnotation':
case 'TupleTypeLabeledElement':
case 'TupleTypeSpreadElement':
case 'ComponentTypeAnnotation':
case 'HookTypeAnnotation':
case 'TypeOperator':
case 'TypePredicate':
{
return createAnyTypeAnnotation(node);
}
case 'QualifiedTypeofIdentifier':
{
return mapQualifiedTypeofIdentifier(node);
}
case 'DeclareEnum':
{
return mapDeclareEnum(node);
}
case 'DeclareNamespace':
{
return mapDeclareNamespace(node);
}
case 'FunctionDeclaration':
case 'FunctionExpression':
{
return mapFunction(node);
}
default:
{
return node;
}
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _createSyntaxError = require("../utils/createSyntaxError");
const nodeWith = _SimpleTransform.SimpleTransform.nodeWith;
const EMPTY_PARENT = null;
function createDefaultPosition() {
return {
line: 1,
column: 0
};
}
function mapDeclareComponent(node) {
return {
type: 'DeclareVariable',
id: nodeWith(node.id, {
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'AnyTypeAnnotation',
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
},
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
}
}),
kind: 'const',
loc: node.loc,
range: node.range,
parent: node.parent
};
}
function getComponentParameterName(paramName) {
switch (paramName.type) {
case 'Identifier':
return paramName.name;
case 'Literal':
return paramName.value;
default:
throw (0, _createSyntaxError.createSyntaxError)(paramName, `Unknown Component parameter name type of "${paramName.type}"`);
}
}
function createPropsTypeAnnotation(propTypes, spread, loc, range) {
const createParamsTypeLoc = () => ({
loc: {
start: (loc == null ? void 0 : loc.start) != null ? loc.start : createDefaultPosition(),
end: (loc == null ? void 0 : loc.end) != null ? loc.end : createDefaultPosition()
},
range: range != null ? range : [0, 0],
parent: EMPTY_PARENT
});
if (spread != null && propTypes.length === 0) {
return {
type: 'TypeAnnotation',
typeAnnotation: spread.argument,
...createParamsTypeLoc()
};
}
const typeProperties = [...propTypes];
if (spread != null) {
typeProperties.unshift(spread);
}
const propTypeObj = {
type: 'ObjectTypeAnnotation',
callProperties: [],
properties: typeProperties,
indexers: [],
internalSlots: [],
exact: false,
inexact: false,
...createParamsTypeLoc()
};
return {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'GenericTypeAnnotation',
id: {
type: 'Identifier',
name: '$ReadOnly',
optional: false,
typeAnnotation: null,
...createParamsTypeLoc()
},
typeParameters: {
type: 'TypeParameterInstantiation',
params: [propTypeObj],
...createParamsTypeLoc()
},
...createParamsTypeLoc()
},
...createParamsTypeLoc()
};
}
function mapComponentParameters(params, options) {
var _options$reactRuntime;
if (params.length === 0) {
return {
props: null,
ref: null
};
}
if (params.length === 1 && params[0].type === 'RestElement' && params[0].argument.type === 'Identifier') {
const restElementArgument = params[0].argument;
return {
props: restElementArgument,
ref: null
};
}
let refParam = null;
const paramsWithoutRef = ((_options$reactRuntime = options.reactRuntimeTarget) != null ? _options$reactRuntime : '18') === '18' ? params.filter(param => {
if (param.type === 'ComponentParameter' && getComponentParameterName(param.name) === 'ref') {
refParam = param;
return false;
}
return true;
}) : params;
const [propTypes, spread] = paramsWithoutRef.reduce(([propTypes, spread], param) => {
switch (param.type) {
case 'RestElement':
{
if (spread != null) {
throw (0, _createSyntaxError.createSyntaxError)(param, `Invalid state, multiple rest elements found as Component Parameters`);
}
return [propTypes, mapComponentParameterRestElementType(param)];
}
case 'ComponentParameter':
{
propTypes.push(mapComponentParameterType(param));
return [propTypes, spread];
}
}
}, [[], null]);
const propsProperties = paramsWithoutRef.flatMap(mapComponentParameter);
let props = null;
if (propsProperties.length === 0) {
if (refParam == null) {
throw new Error('TransformComponentSyntax: Invalid state, ref should always be set at this point if props are empty');
}
const emptyParamsLoc = {
start: refParam.loc.start,
end: refParam.loc.start
};
const emptyParamsRange = [refParam.range[0], refParam.range[0]];
props = {
type: 'Identifier',
name: '_$$empty_props_placeholder$$',
optional: false,
typeAnnotation: createPropsTypeAnnotation([], null, emptyParamsLoc, emptyParamsRange),
loc: emptyParamsLoc,
range: emptyParamsRange,
parent: EMPTY_PARENT
};
} else {
const lastPropsProperty = propsProperties[propsProperties.length - 1];
props = {
type: 'ObjectPattern',
properties: propsProperties,
typeAnnotation: createPropsTypeAnnotation(propTypes, spread, {
start: lastPropsProperty.loc.end,
end: lastPropsProperty.loc.end
}, [lastPropsProperty.range[1], lastPropsProperty.range[1]]),
loc: {
start: propsProperties[0].loc.start,
end: lastPropsProperty.loc.end
},
range: [propsProperties[0].range[0], lastPropsProperty.range[1]],
parent: EMPTY_PARENT
};
}
let ref = null;
if (refParam != null) {
ref = refParam.local;
}
return {
props,
ref
};
}
function mapComponentParameterType(param) {
var _typeAnnotation$typeA;
const typeAnnotation = param.local.type === 'AssignmentPattern' ? param.local.left.typeAnnotation : param.local.typeAnnotation;
const optional = param.local.type === 'AssignmentPattern' ? true : param.local.type === 'Identifier' ? param.local.optional : false;
return {
type: 'ObjectTypeProperty',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(param.name),
value: (_typeAnnotation$typeA = typeAnnotation == null ? void 0 : typeAnnotation.typeAnnotation) != null ? _typeAnnotation$typeA : {
type: 'AnyTypeAnnotation',
loc: param.local.loc,
range: param.local.range,
parent: EMPTY_PARENT
},
kind: 'init',
optional,
method: false,
static: false,
proto: false,
variance: null,
loc: param.local.loc,
range: param.local.range,
parent: EMPTY_PARENT
};
}
function mapComponentParameterRestElementType(param) {
var _param$argument$typeA, _param$argument$typeA2;
if (param.argument.type !== 'Identifier' && param.argument.type !== 'ObjectPattern') {
throw (0, _createSyntaxError.createSyntaxError)(param, `Invalid ${param.argument.type} encountered in restParameter`);
}
return {
type: 'ObjectTypeSpreadProperty',
argument: (_param$argument$typeA = (_param$argument$typeA2 = param.argument.typeAnnotation) == null ? void 0 : _param$argument$typeA2.typeAnnotation) != null ? _param$argument$typeA : {
type: 'AnyTypeAnnotation',
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
},
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
};
}
function mapComponentParameter(param) {
switch (param.type) {
case 'RestElement':
{
switch (param.argument.type) {
case 'Identifier':
{
const a = nodeWith(param, {
typeAnnotation: null,
argument: nodeWith(param.argument, {
typeAnnotation: null
})
});
return [a];
}
case 'ObjectPattern':
{
return param.argument.properties.map(property => {
return nodeWith(property, {
typeAnnotation: null
});
});
}
default:
{
throw (0, _createSyntaxError.createSyntaxError)(param, `Unhandled ${param.argument.type} encountered in restParameter`);
}
}
}
case 'ComponentParameter':
{
let value;
if (param.local.type === 'AssignmentPattern') {
value = nodeWith(param.local, {
left: nodeWith(param.local.left, {
typeAnnotation: null,
optional: false
})
});
} else {
value = nodeWith(param.local, {
typeAnnotation: null,
optional: false
});
}
if (param.name.type === 'Identifier' && param.shorthand && (value.type === 'Identifier' || value.type === 'AssignmentPattern')) {
return [{
type: 'Property',
key: param.name,
kind: 'init',
value,
method: false,
shorthand: true,
computed: false,
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
}];
}
return [{
type: 'Property',
key: param.name,
kind: 'init',
value,
method: false,
shorthand: false,
computed: false,
loc: param.loc,
range: param.range,
parent: EMPTY_PARENT
}];
}
default:
{
throw (0, _createSyntaxError.createSyntaxError)(param, `Unknown Component parameter type of "${param.type}"`);
}
}
}
function createForwardRefWrapper(originalComponent) {
const internalCompId = {
type: 'Identifier',
name: `${originalComponent.id.name}_withRef`,
optional: false,
typeAnnotation: null,
loc: originalComponent.id.loc,
range: originalComponent.id.range,
parent: EMPTY_PARENT
};
return {
forwardRefStatement: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: (0, _astNodeMutationHelpers.shallowCloneNode)(originalComponent.id),
init: {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: {
type: 'Identifier',
name: 'React',
optional: false,
typeAnnotation: null,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
property: {
type: 'Identifier',
name: 'forwardRef',
optional: false,
typeAnnotation: null,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
computed: false,
optional: false,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
arguments: [(0, _astNodeMutationHelpers.shallowCloneNode)(internalCompId)],
typeArguments: null,
optional: false,
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
},
loc: originalComponent.loc,
range: originalComponent.range,
parent: EMPTY_PARENT
}],
loc: originalComponent.loc,
range: originalComponent.range,
parent: originalComponent.parent
},
internalCompId: internalCompId,
forwardRefCompId: originalComponent.id
};
}
function mapComponentDeclaration(node, options) {
var _node$async;
const createRendersTypeLoc = () => ({
loc: {
start: node.body.loc.end,
end: node.body.loc.end
},
range: [node.body.range[1], node.body.range[1]],
parent: EMPTY_PARENT
});
const returnType = {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'GenericTypeAnnotation',
id: {
type: 'QualifiedTypeIdentifier',
qualification: {
type: 'Identifier',
name: 'React',
optional: false,
typeAnnotation: null,
...createRendersTypeLoc()
},
id: {
type: 'Identifier',
name: 'Node',
optional: false,
typeAnnotation: null,
...createRendersTypeLoc()
},
...createRendersTypeLoc()
},
typeParameters: null,
...createRendersTypeLoc()
},
...createRendersTypeLoc()
};
const {
props,
ref
} = mapComponentParameters(node.params, options);
let forwardRefDetails = null;
if (ref != null) {
forwardRefDetails = createForwardRefWrapper(node);
}
const comp = {
type: 'FunctionDeclaration',
id: forwardRefDetails != null ? (0, _astNodeMutationHelpers.shallowCloneNode)(forwardRefDetails.internalCompId) : (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
__componentDeclaration: true,
typeParameters: node.typeParameters,
params: props == null ? [] : ref == null ? [props] : [props, ref],
returnType,
body: node.body,
async: (_node$async = node.async) != null ? _node$async : false,
generator: false,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
return {
comp,
forwardRefDetails
};
}
function mapDeclareHook(node) {
return {
type: 'DeclareFunction',
id: {
type: 'Identifier',
name: node.id.name,
optional: node.id.optional,
typeAnnotation: {
type: 'TypeAnnotation',
typeAnnotation: {
type: 'FunctionTypeAnnotation',
this: null,
params: node.id.typeAnnotation.typeAnnotation.params,
typeParameters: node.id.typeAnnotation.typeAnnotation.typeParameters,
rest: node.id.typeAnnotation.typeAnnotation.rest,
returnType: node.id.typeAnnotation.typeAnnotation.returnType,
loc: node.id.typeAnnotation.typeAnnotation.loc,
range: node.id.typeAnnotation.typeAnnotation.range,
parent: node.id.typeAnnotation.typeAnnotation.parent
},
loc: node.id.typeAnnotation.loc,
range: node.id.typeAnnotation.range,
parent: node.id.typeAnnotation.parent
},
loc: node.id.loc,
range: node.id.range,
parent: node.id.parent
},
loc: node.loc,
range: node.range,
parent: node.parent,
predicate: null
};
}
function mapHookDeclaration(node) {
var _node$async2;
const comp = {
type: 'FunctionDeclaration',
id: node.id && (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
__hookDeclaration: true,
typeParameters: node.typeParameters,
params: node.params,
returnType: node.returnType,
body: node.body,
async: (_node$async2 = node.async) != null ? _node$async2 : false,
generator: false,
predicate: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
return comp;
}
function scanForFirstComponentReference(compName, bodyList) {
for (let i = 0; i < bodyList.length; i++) {
const bodyNode = bodyList[i];
let referencePos = null;
_SimpleTraverser.SimpleTraverser.traverse(bodyNode, {
enter(node) {
switch (node.type) {
case 'Identifier':
{
if (node.name === compName) {
referencePos = i;
throw _SimpleTraverser.SimpleTraverser.Break;
}
}
}
},
leave(_node) {}
});
if (referencePos != null) {
return referencePos;
}
}
return null;
}
function mapComponentDeclarationIntoList(node, newBody, options, insertExport) {
const {
comp,
forwardRefDetails
} = mapComponentDeclaration(node, options);
if (forwardRefDetails != null) {
const referencePos = scanForFirstComponentReference(forwardRefDetails.forwardRefCompId.name, newBody);
if (referencePos != null) {
newBody.splice(referencePos, 0, forwardRefDetails.forwardRefStatement);
} else {
newBody.push(forwardRefDetails.forwardRefStatement);
}
newBody.push(comp);
if (insertExport != null) {
newBody.push(insertExport(forwardRefDetails.forwardRefCompId));
}
return;
}
newBody.push(insertExport != null ? insertExport(comp) : comp);
}
function mapStatementList(stmts, options) {
const newBody = [];
for (const node of stmts) {
switch (node.type) {
case 'ComponentDeclaration':
{
mapComponentDeclarationIntoList(node, newBody, options);
break;
}
case 'HookDeclaration':
{
const decl = mapHookDeclaration(node);
newBody.push(decl);
break;
}
case 'ExportNamedDeclaration':
{
var _node$declaration, _node$declaration2;
if (((_node$declaration = node.declaration) == null ? void 0 : _node$declaration.type) === 'ComponentDeclaration') {
mapComponentDeclarationIntoList(node.declaration, newBody, options, componentOrRef => {
switch (componentOrRef.type) {
case 'FunctionDeclaration':
{
return nodeWith(node, {
declaration: componentOrRef
});
}
case 'Identifier':
{
return {
type: 'ExportNamedDeclaration',
declaration: null,
specifiers: [{
type: 'ExportSpecifier',
exported: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
local: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
loc: node.loc,
range: node.range,
parent: EMPTY_PARENT
}],
exportKind: 'value',
source: null,
loc: node.loc,
range: node.range,
parent: node.parent
};
}
}
});
break;
}
if (((_node$declaration2 = node.declaration) == null ? void 0 : _node$declaration2.type) === 'HookDeclaration') {
const comp = mapHookDeclaration(node.declaration);
newBody.push(nodeWith(node, {
declaration: comp
}));
break;
}
newBody.push(node);
break;
}
case 'ExportDefaultDeclaration':
{
var _node$declaration3, _node$declaration4;
if (((_node$declaration3 = node.declaration) == null ? void 0 : _node$declaration3.type) === 'ComponentDeclaration') {
mapComponentDeclarationIntoList(node.declaration, newBody, options, componentOrRef => nodeWith(node, {
declaration: componentOrRef
}));
break;
}
if (((_node$declaration4 = node.declaration) == null ? void 0 : _node$declaration4.type) === 'HookDeclaration') {
const comp = mapHookDeclaration(node.declaration);
newBody.push(nodeWith(node, {
declaration: comp
}));
break;
}
newBody.push(node);
break;
}
default:
{
newBody.push(node);
}
}
}
return newBody;
}
function transformProgram(program, options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'DeclareComponent':
{
return mapDeclareComponent(node);
}
case 'DeclareHook':
{
return mapDeclareHook(node);
}
case 'Program':
case 'BlockStatement':
{
return nodeWith(node, {
body: mapStatementList(node.body, options)
});
}
case 'SwitchCase':
{
const consequent = mapStatementList(node.consequent, options);
return nodeWith(node, {
consequent
});
}
case 'ComponentDeclaration':
{
var _node$parent;
throw (0, _createSyntaxError.createSyntaxError)(node, `Components must be defined at the top level of a module or within a ` + `BlockStatement, instead got parent of "${(_node$parent = node.parent) == null ? void 0 : _node$parent.type}".`);
}
case 'HookDeclaration':
{
var _node$parent2;
throw (0, _createSyntaxError.createSyntaxError)(node, `Hooks must be defined at the top level of a module or within a ` + `BlockStatement, instead got parent of "${(_node$parent2 = node.parent) == null ? void 0 : _node$parent2.type}".`);
}
default:
{
return node;
}
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _flowEstree = require("flow-estree");
var _SimpleTransform = require("../transform/SimpleTransform");
var _Builders = require("../utils/Builders");
function mapEnumDeclaration(node, options) {
var _options$transformOpt, _options$transformOpt2;
const {
body
} = node;
const {
members
} = body;
const getRuntime = (_options$transformOpt = options.transformOptions) == null ? void 0 : (_options$transformOpt2 = _options$transformOpt.TransformEnumSyntax) == null ? void 0 : _options$transformOpt2.getRuntime;
const enumModule = typeof getRuntime === 'function' ? getRuntime() : (0, _Builders.callExpression)((0, _Builders.ident)('require'), [(0, _Builders.stringLiteral)('flow-enums-runtime')]);
const mirrored = body.type === 'EnumStringBody' && (!members.length || members[0].type === 'EnumDefaultedMember');
const enumExpression = mirrored ? (0, _Builders.callExpression)({
type: 'MemberExpression',
object: enumModule,
property: (0, _Builders.ident)('Mirrored'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [{
type: 'ArrayExpression',
elements: members.map(member => (0, _Builders.stringLiteral)(member.id.name)),
trailingComma: false,
...(0, _Builders.etc)()
}]) : (0, _Builders.callExpression)(enumModule, [{
type: 'ObjectExpression',
properties: members.map(member => ({
type: 'Property',
key: member.id,
value: member.type === 'EnumDefaultedMember' ? (0, _Builders.callExpression)((0, _Builders.ident)('Symbol'), [(0, _Builders.stringLiteral)(member.id.name)]) : member.init,
kind: 'init',
method: false,
shorthand: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
})),
...(0, _Builders.etc)()
}]);
return (0, _Builders.variableDeclaration)('const', node.id, enumExpression);
}
function transformProgram(program, options) {
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'EnumDeclaration':
{
return mapEnumDeclaration(node, options);
}
case 'ExportDefaultDeclaration':
{
const {
declaration
} = node;
if ((0, _flowEstree.isEnumDeclaration)(declaration)) {
const enumDeclaration = mapEnumDeclaration(declaration, options);
const exportDefault = _SimpleTransform.SimpleTransform.nodeWith(node, {
declaration: (0, _Builders.ident)(declaration.id.name)
});
return [enumDeclaration, exportDefault];
} else {
return node;
}
}
default:
{
return node;
}
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _createSyntaxError = require("../utils/createSyntaxError");
var _Builders = require("../utils/Builders");
var _GenID = _interopRequireDefault(require("../utils/GenID"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let genID = null;
function genIdent() {
if (genID == null) {
throw Error('GenID must be initialized at the start of the transform.');
}
return (0, _Builders.ident)(genID.id());
}
function objKeyToString(node) {
switch (node.type) {
case 'Identifier':
return node.name;
case 'Literal':
{
const {
value
} = node;
if (typeof value === 'number') {
return String(value);
} else if (typeof value === 'string') {
return value;
} else {
return node.raw;
}
}
}
}
function convertMemberPattern(pattern) {
const {
base,
property,
loc,
range
} = pattern;
const object = base.type === 'MatchIdentifierPattern' ? base.id : convertMemberPattern(base);
if (property.type === 'Identifier') {
return {
type: 'MemberExpression',
object,
property,
computed: false,
optional: false,
...(0, _Builders.etc)({
loc,
range
})
};
} else {
return {
type: 'MemberExpression',
object,
property,
computed: true,
optional: false,
...(0, _Builders.etc)({
loc,
range
})
};
}
}
function checkDuplicateBindingName(seenBindingNames, node, name) {
if (seenBindingNames.has(name)) {
throw (0, _createSyntaxError.createSyntaxError)(node, `Duplicate variable name '${name}' in match case pattern.`);
}
seenBindingNames.add(name);
}
function checkBindingKind(node, kind) {
if (kind === 'var') {
throw (0, _createSyntaxError.createSyntaxError)(node, `'var' bindings are not allowed. Use 'const' or 'let'.`);
}
}
function needsPropExistsCond(pattern) {
switch (pattern.type) {
case 'MatchWildcardPattern':
case 'MatchBindingPattern':
case 'MatchIdentifierPattern':
case 'MatchMemberPattern':
return true;
case 'MatchLiteralPattern':
case 'MatchUnaryPattern':
case 'MatchObjectPattern':
case 'MatchInstancePattern':
case 'MatchArrayPattern':
return false;
case 'MatchAsPattern':
{
const {
pattern: asPattern
} = pattern;
return needsPropExistsCond(asPattern);
}
case 'MatchOrPattern':
{
const {
patterns
} = pattern;
return patterns.some(needsPropExistsCond);
}
}
}
function analyzeProperties(key, pattern, seenBindingNames, properties, rest) {
const conditions = [];
const bindings = [];
const objKeys = [];
const seenNames = new Set();
properties.forEach(prop => {
const {
key: objKey,
pattern: propPattern
} = prop;
objKeys.push(objKey);
const name = objKeyToString(objKey);
if (seenNames.has(name)) {
throw (0, _createSyntaxError.createSyntaxError)(propPattern, `Duplicate property name '${name}' in match object pattern.`);
}
seenNames.add(name);
const propKey = key.concat(objKey);
if (needsPropExistsCond(propPattern)) {
conditions.push({
type: 'prop-exists',
key,
propName: name
});
}
const {
conditions: childConditions,
bindings: childBindings
} = analyzePattern(propPattern, propKey, seenBindingNames);
conditions.push(...childConditions);
bindings.push(...childBindings);
});
if (rest != null && rest.argument != null) {
const {
id,
kind
} = rest.argument;
checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
checkBindingKind(pattern, kind);
bindings.push({
type: 'object-rest',
key,
exclude: objKeys,
kind,
id
});
}
return {
conditions,
bindings
};
}
function constructorExpression(constructor) {
switch (constructor.type) {
case 'MatchIdentifierPattern':
return constructor.id;
case 'MatchMemberPattern':
return convertMemberPattern(constructor);
}
}
function analyzePattern(pattern, key, seenBindingNames) {
switch (pattern.type) {
case 'MatchWildcardPattern':
{
return {
conditions: [],
bindings: []
};
}
case 'MatchLiteralPattern':
{
const {
literal
} = pattern;
const condition = {
type: 'eq',
key,
arg: literal
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchUnaryPattern':
{
const {
operator,
argument,
loc,
range
} = pattern;
if (argument.value === 0) {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `'+0' and '-0' are not yet supported in match unary patterns.`);
}
const arg = {
type: 'UnaryExpression',
operator,
argument,
prefix: true,
...(0, _Builders.etc)({
loc,
range
})
};
const condition = {
type: 'eq',
key,
arg
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchIdentifierPattern':
{
const {
id
} = pattern;
const condition = id.name === 'NaN' ? {
type: 'is-nan',
key
} : {
type: 'eq',
key,
arg: id
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchMemberPattern':
{
const arg = convertMemberPattern(pattern);
const condition = {
type: 'eq',
key,
arg
};
return {
conditions: [condition],
bindings: []
};
}
case 'MatchBindingPattern':
{
const {
id,
kind
} = pattern;
checkDuplicateBindingName(seenBindingNames, pattern, id.name);
checkBindingKind(pattern, kind);
const binding = {
type: 'id',
key,
kind,
id
};
return {
conditions: [],
bindings: [binding]
};
}
case 'MatchAsPattern':
{
const {
pattern: asPattern,
target
} = pattern;
if (asPattern.type === 'MatchBindingPattern') {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `Match 'as' patterns are not allowed directly on binding patterns.`);
}
const {
conditions,
bindings
} = analyzePattern(asPattern, key, seenBindingNames);
const defaultKind = 'const';
const [id, kind] = target.type === 'MatchBindingPattern' ? [target.id, target.kind] : [target, defaultKind];
checkDuplicateBindingName(seenBindingNames, pattern, id.name);
checkBindingKind(pattern, kind);
const binding = {
type: 'id',
key,
kind,
id
};
return {
conditions,
bindings: bindings.concat(binding)
};
}
case 'MatchArrayPattern':
{
const {
elements,
rest
} = pattern;
const lengthOp = rest == null ? 'eq' : 'gte';
const conditions = [{
type: 'array',
key,
length: elements.length,
lengthOp
}];
const bindings = [];
elements.forEach((element, i) => {
const elementKey = key.concat((0, _Builders.numberLiteral)(i));
const {
conditions: childConditions,
bindings: childBindings
} = analyzePattern(element, elementKey, seenBindingNames);
conditions.push(...childConditions);
bindings.push(...childBindings);
});
if (rest != null && rest.argument != null) {
const {
id,
kind
} = rest.argument;
checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
checkBindingKind(pattern, kind);
bindings.push({
type: 'array-rest',
key,
exclude: elements.length,
kind,
id
});
}
return {
conditions,
bindings
};
}
case 'MatchObjectPattern':
{
const {
properties,
rest
} = pattern;
const {
conditions: propertyConditions,
bindings
} = analyzeProperties(key, pattern, seenBindingNames, properties, rest);
const conditions = [{
type: 'object',
key
}, ...propertyConditions];
return {
conditions,
bindings
};
}
case 'MatchInstancePattern':
{
const {
targetConstructor,
properties: {
properties,
rest
}
} = pattern;
const {
conditions: propertyConditions,
bindings
} = analyzeProperties(key, pattern, seenBindingNames, properties, rest);
const conditions = [{
type: 'instanceof',
key,
constructor: constructorExpression(targetConstructor)
}, ...propertyConditions];
return {
conditions,
bindings
};
}
case 'MatchOrPattern':
{
const {
patterns
} = pattern;
let hasWildcard = false;
const orConditions = patterns.map(subpattern => {
const {
conditions,
bindings
} = analyzePattern(subpattern, key, seenBindingNames);
if (bindings.length > 0) {
throw (0, _createSyntaxError.createSyntaxError)(pattern, `Bindings in match 'or' patterns are not yet supported.`);
}
if (conditions.length === 0) {
hasWildcard = true;
}
return conditions;
});
if (hasWildcard) {
return {
conditions: [],
bindings: []
};
}
return {
conditions: [{
type: 'or',
orConditions
}],
bindings: []
};
}
}
}
function expressionOfKey(root, key) {
return key.reduce((acc, prop) => prop.type === 'Identifier' ? {
type: 'MemberExpression',
object: acc,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
computed: false,
optional: false,
...(0, _Builders.etc)()
} : {
type: 'MemberExpression',
object: acc,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
computed: true,
optional: false,
...(0, _Builders.etc)()
}, (0, _astNodeMutationHelpers.deepCloneNode)(root));
}
function testsOfCondition(root, condition) {
switch (condition.type) {
case 'eq':
{
const {
key,
arg
} = condition;
return [{
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: arg,
operator: '===',
...(0, _Builders.etc)()
}];
}
case 'is-nan':
{
const {
key
} = condition;
const callee = {
type: 'MemberExpression',
object: (0, _Builders.ident)('Number'),
property: (0, _Builders.ident)('isNaN'),
computed: false,
optional: false,
...(0, _Builders.etc)()
};
return [(0, _Builders.callExpression)(callee, [expressionOfKey(root, key)])];
}
case 'array':
{
const {
key,
length,
lengthOp
} = condition;
const operator = lengthOp === 'eq' ? '===' : '>=';
const isArray = (0, _Builders.callExpression)({
type: 'MemberExpression',
object: (0, _Builders.ident)('Array'),
property: (0, _Builders.ident)('isArray'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [expressionOfKey(root, key)]);
const lengthCheck = {
type: 'BinaryExpression',
left: {
type: 'MemberExpression',
object: expressionOfKey(root, key),
property: (0, _Builders.ident)('length'),
computed: false,
optional: false,
...(0, _Builders.etc)()
},
right: (0, _Builders.numberLiteral)(length),
operator,
...(0, _Builders.etc)()
};
return [isArray, lengthCheck];
}
case 'object':
{
const {
key
} = condition;
const typeofObject = (0, _Builders.typeofExpression)(expressionOfKey(root, key), 'object');
const typeofFunction = (0, _Builders.typeofExpression)(expressionOfKey(root, key), 'function');
const notNull = {
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: (0, _Builders.nullLiteral)(),
operator: '!==',
...(0, _Builders.etc)()
};
return [(0, _Builders.disjunction)([(0, _Builders.conjunction)([typeofObject, notNull]), typeofFunction])];
}
case 'instanceof':
{
const {
key,
constructor
} = condition;
return [{
type: 'BinaryExpression',
left: expressionOfKey(root, key),
right: constructor,
operator: 'instanceof',
...(0, _Builders.etc)()
}];
}
case 'prop-exists':
{
const {
key,
propName
} = condition;
const inObject = {
type: 'BinaryExpression',
left: (0, _Builders.stringLiteral)(propName),
right: expressionOfKey(root, key),
operator: 'in',
...(0, _Builders.etc)()
};
return [inObject];
}
case 'or':
{
const {
orConditions
} = condition;
const tests = orConditions.map(conditions => (0, _Builders.conjunction)(testsOfConditions(root, conditions)));
return [(0, _Builders.disjunction)(tests)];
}
}
}
function testsOfConditions(root, conditions) {
return conditions.flatMap(condition => testsOfCondition(root, condition));
}
function statementsOfBindings(root, bindings) {
return bindings.map(binding => {
switch (binding.type) {
case 'id':
{
const {
key,
kind,
id
} = binding;
return (0, _Builders.variableDeclaration)(kind, id, expressionOfKey(root, key));
}
case 'array-rest':
{
const {
key,
kind,
id,
exclude
} = binding;
const init = (0, _Builders.callExpression)({
type: 'MemberExpression',
object: expressionOfKey(root, key),
property: (0, _Builders.ident)('slice'),
computed: false,
optional: false,
...(0, _Builders.etc)()
}, [(0, _Builders.numberLiteral)(exclude)]);
return (0, _Builders.variableDeclaration)(kind, id, init);
}
case 'object-rest':
{
const {
key,
kind,
id,
exclude
} = binding;
const destructuring = {
type: 'ObjectPattern',
properties: exclude.map(prop => prop.type === 'Identifier' ? {
type: 'Property',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
value: genIdent(),
kind: 'init',
computed: false,
method: false,
shorthand: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
} : {
type: 'Property',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop),
value: genIdent(),
kind: 'init',
computed: true,
method: false,
shorthand: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
}).concat({
type: 'RestElement',
argument: id,
...(0, _Builders.etc)()
}),
typeAnnotation: null,
...(0, _Builders.etc)()
};
return (0, _Builders.variableDeclaration)(kind, destructuring, expressionOfKey(root, key));
}
}
});
}
const fallthroughErrorMsgText = `Match: No case succesfully matched. Make exhaustive or add a wildcard case using '_'.`;
function fallthroughErrorMsg(value) {
return {
type: 'BinaryExpression',
operator: '+',
left: (0, _Builders.stringLiteral)(`${fallthroughErrorMsgText} Argument: `),
right: value,
...(0, _Builders.etc)()
};
}
function fallthroughError(value) {
return (0, _Builders.throwStatement)(fallthroughErrorMsg(value));
}
function calculateSimpleArgument(node) {
switch (node.type) {
case 'Identifier':
case 'Super':
return true;
case 'MemberExpression':
{
const {
object,
property,
computed
} = node;
if (computed && property.type !== 'Literal') {
return false;
}
return calculateSimpleArgument(object);
}
default:
return false;
}
}
function analyzeCases(cases) {
let hasBindings = false;
let hasWildcard = false;
const analyses = [];
for (let i = 0; i < cases.length; i++) {
const {
pattern,
guard,
body
} = cases[i];
const {
conditions,
bindings
} = analyzePattern(pattern, [], new Set());
hasBindings = hasBindings || bindings.length > 0;
analyses.push({
conditions,
bindings,
guard,
body
});
if (conditions.length === 0 && guard == null) {
hasWildcard = true;
break;
}
}
return {
hasBindings,
hasWildcard,
analyses
};
}
function mapMatchExpression(node) {
const {
argument,
cases
} = node;
const {
hasBindings,
hasWildcard,
analyses
} = analyzeCases(cases);
const isSimpleArgument = !hasBindings && calculateSimpleArgument(argument);
const genRoot = !isSimpleArgument ? genIdent() : null;
const root = genRoot == null ? argument : genRoot;
if (isSimpleArgument) {
const wildcardAnalaysis = hasWildcard ? analyses.pop() : null;
const lastBody = wildcardAnalaysis != null ? wildcardAnalaysis.body : (0, _Builders.iife)([fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root))]);
return analyses.reverse().reduce((acc, analysis) => {
const {
conditions,
guard,
body
} = analysis;
const tests = testsOfConditions(root, conditions);
if (guard != null) {
tests.push(guard);
}
return {
type: 'ConditionalExpression',
test: (0, _Builders.conjunction)(tests),
consequent: body,
alternate: acc,
...(0, _Builders.etc)()
};
}, lastBody);
}
const statements = analyses.map(({
conditions,
bindings,
guard,
body
}) => {
const returnNode = {
type: 'ReturnStatement',
argument: body,
...(0, _Builders.etc)()
};
const bodyNode = guard == null ? returnNode : {
type: 'IfStatement',
test: guard,
consequent: returnNode,
...(0, _Builders.etc)()
};
const bindingNodes = statementsOfBindings(root, bindings);
const caseBody = bindingNodes.concat(bodyNode);
if (conditions.length > 0) {
const tests = testsOfConditions(root, conditions);
return {
type: 'IfStatement',
test: (0, _Builders.conjunction)(tests),
consequent: {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
};
} else {
if (bindingNodes.length > 0) {
return {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
};
} else {
return bodyNode;
}
}
});
if (!hasWildcard) {
statements.push(fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root)));
}
const [params, args] = genRoot == null ? [[], []] : [[genRoot], [argument]];
return (0, _Builders.iife)(statements, params, args);
}
function mapMatchStatement(node) {
const {
argument,
cases
} = node;
const {
hasBindings,
hasWildcard,
analyses
} = analyzeCases(cases);
const topLabel = genIdent();
const isSimpleArgument = !hasBindings && calculateSimpleArgument(argument);
const genRoot = !isSimpleArgument ? genIdent() : null;
const root = genRoot == null ? argument : genRoot;
const statements = [];
if (genRoot != null) {
statements.push((0, _Builders.variableDeclaration)('const', genRoot, argument));
}
analyses.forEach(({
conditions,
bindings,
guard,
body
}) => {
const breakNode = {
type: 'BreakStatement',
label: (0, _astNodeMutationHelpers.shallowCloneNode)(topLabel),
...(0, _Builders.etc)()
};
const bodyStatements = body.body.concat(breakNode);
const guardedBodyStatements = guard == null ? bodyStatements : [{
type: 'IfStatement',
test: guard,
consequent: {
type: 'BlockStatement',
body: bodyStatements,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
}];
const bindingNodes = statementsOfBindings(root, bindings);
const caseBody = bindingNodes.concat(guardedBodyStatements);
if (conditions.length > 0) {
const tests = testsOfConditions(root, conditions);
statements.push({
type: 'IfStatement',
test: (0, _Builders.conjunction)(tests),
consequent: {
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
});
} else {
statements.push({
type: 'BlockStatement',
body: caseBody,
...(0, _Builders.etc)()
});
}
});
if (!hasWildcard) {
statements.push(fallthroughError((0, _astNodeMutationHelpers.shallowCloneNode)(root)));
}
return {
type: 'LabeledStatement',
label: topLabel,
body: {
type: 'BlockStatement',
body: statements,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)()
};
}
function transformProgram(program, _options) {
genID = new _GenID.default('m');
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'MatchExpression':
{
return mapMatchExpression(node);
}
case 'MatchStatement':
{
return mapMatchStatement(node);
}
case 'Identifier':
{
if (genID == null) {
throw Error('GenID must be initialized at the start of the transform.');
}
genID.addUsage(node.name);
return node;
}
default:
{
return node;
}
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformProgram = transformProgram;
var _flowEstree = require("flow-estree");
var _SimpleTransform = require("../transform/SimpleTransform");
var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
var _Builders = require("../utils/Builders");
var _isReservedWord = _interopRequireDefault(require("../utils/isReservedWord"));
var _GenID = _interopRequireDefault(require("../utils/GenID"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function nameOfKey(key) {
switch (key.type) {
case 'Identifier':
return key.name;
case 'Literal':
if ((0, _flowEstree.isBigIntLiteral)(key)) {
return key.bigint;
}
return String(key.value);
}
}
function mapRecordDeclaration(genID, node) {
const ownProperties = [];
const staticProperties = [];
const methods = [];
const staticMethods = [];
for (const element of node.body.elements) {
switch (element.type) {
case 'RecordDeclarationProperty':
ownProperties.push(element);
break;
case 'RecordDeclarationStaticProperty':
staticProperties.push(element);
break;
case 'MethodDefinition':
if (element.static) {
staticMethods.push(element);
} else {
methods.push(element);
}
break;
}
}
const reservedPropNames = new Map();
const constructorParam = {
type: 'ObjectPattern',
properties: ownProperties.map(prop => {
const {
key,
defaultValue
} = prop;
const keyName = nameOfKey(key);
const getValue = bindingIdent => defaultValue != null ? {
type: 'AssignmentPattern',
left: bindingIdent,
right: (0, _astNodeMutationHelpers.deepCloneNode)(defaultValue),
...(0, _Builders.etc)()
} : bindingIdent;
switch (key.type) {
case 'Identifier':
{
const needsNewBinding = (0, _isReservedWord.default)(keyName);
const bindingName = needsNewBinding ? genID.id() : keyName;
const bindingIdent = (0, _Builders.ident)(bindingName);
if (needsNewBinding) {
reservedPropNames.set(keyName, bindingName);
}
if (needsNewBinding) {
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: false,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
} else {
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: true,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
}
}
case 'Literal':
{
const bindingName = genID.id();
const bindingIdent = (0, _Builders.ident)(bindingName);
reservedPropNames.set(keyName, bindingName);
return {
type: 'Property',
kind: 'init',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
value: getValue(bindingIdent),
shorthand: false,
method: false,
computed: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
}
}
}),
typeAnnotation: null,
...(0, _Builders.etc)()
};
const constructor = {
type: 'MethodDefinition',
key: (0, _Builders.ident)('constructor'),
kind: 'constructor',
computed: false,
static: false,
decorators: [],
value: {
type: 'FunctionExpression',
id: null,
params: [constructorParam],
body: {
type: 'BlockStatement',
body: ownProperties.map(({
key
}) => {
var _reservedPropNames$ge;
const keyName = nameOfKey(key);
const bindingIdent = (0, _Builders.ident)((_reservedPropNames$ge = reservedPropNames.get(keyName)) != null ? _reservedPropNames$ge : keyName);
const object = {
type: 'ThisExpression',
...(0, _Builders.etc)()
};
const memberExpression = key.type === 'Identifier' ? {
type: 'MemberExpression',
object,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
computed: false,
optional: false,
...(0, _Builders.etc)()
} : {
type: 'MemberExpression',
object,
property: (0, _astNodeMutationHelpers.shallowCloneNode)(key),
computed: true,
optional: false,
...(0, _Builders.etc)()
};
return {
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: memberExpression,
right: bindingIdent,
...(0, _Builders.etc)()
},
directive: null,
...(0, _Builders.etc)()
};
}),
...(0, _Builders.etc)()
},
generator: false,
async: false,
predicate: null,
returnType: null,
typeParameters: null,
...(0, _Builders.etc)()
},
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
};
const classStaticProperties = staticProperties.map(prop => ({
type: 'PropertyDefinition',
key: (0, _astNodeMutationHelpers.shallowCloneNode)(prop.key),
value: (0, _astNodeMutationHelpers.deepCloneNode)(prop.value),
static: true,
decorators: [],
typeAnnotation: null,
variance: null,
computed: false,
declare: false,
optional: false,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
}));
const classBodyElements = [constructor, ...methods, ...classStaticProperties, ...staticMethods];
return {
type: 'ClassDeclaration',
id: (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
body: {
type: 'ClassBody',
body: classBodyElements,
...(0, _Builders.etc)(),
parent: _Builders.EMPTY_PARENT
},
superClass: null,
typeParameters: null,
superTypeArguments: null,
implements: [],
decorators: [],
...(0, _Builders.etc)()
};
}
function mapRecordExpression(node) {
const obj = {
type: 'ObjectExpression',
properties: node.properties.properties,
...(0, _Builders.etc)()
};
return {
type: 'NewExpression',
callee: node.recordConstructor,
arguments: [obj],
typeArguments: null,
...(0, _Builders.etc)()
};
}
function transformProgram(program, _options) {
const genID = new _GenID.default('r');
return _SimpleTransform.SimpleTransform.transformProgram(program, {
transform(node) {
switch (node.type) {
case 'RecordDeclaration':
{
return mapRecordDeclaration(genID, node);
}
case 'RecordExpression':
{
return mapRecordExpression(node);
}
case 'Identifier':
{
genID.addUsage(node.name);
return node;
}
default:
return node;
}
}
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse = parse;
var _FlowParserDeserializer = _interopRequireDefault(require("./FlowParserDeserializer"));
var _FlowParserWASM = _interopRequireDefault(require("./FlowParserWASM"));
var _getModuleDocblock = require("./getModuleDocblock");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let FlowParserWASM;
let flowParse;
let flowParseResult_free;
let flowParseResult_getError;
let flowParseResult_getErrorLine;
let flowParseResult_getErrorColumn;
let flowParseResult_getProgramBuffer;
let flowParseResult_getPositionBuffer;
let flowParseResult_getPositionBufferSize;
let flowParseResult_getStringBuffer;
function initFlowParserWASM() {
if (FlowParserWASM != null) {
return;
}
FlowParserWASM = (0, _FlowParserWASM.default)({
quit(_status, toThrow) {
throw toThrow;
}
});
flowParse = FlowParserWASM.cwrap('hermesParse', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']);
flowParseResult_free = FlowParserWASM.cwrap('hermesParseResult_free', 'void', ['number']);
flowParseResult_getError = FlowParserWASM.cwrap('hermesParseResult_getError', 'string', ['number']);
flowParseResult_getErrorLine = FlowParserWASM.cwrap('hermesParseResult_getErrorLine', 'number', ['number']);
flowParseResult_getErrorColumn = FlowParserWASM.cwrap('hermesParseResult_getErrorColumn', 'number', ['number']);
flowParseResult_getProgramBuffer = FlowParserWASM.cwrap('hermesParseResult_getProgramBuffer', 'number', ['number']);
flowParseResult_getPositionBuffer = FlowParserWASM.cwrap('hermesParseResult_getPositionBuffer', 'number', ['number']);
flowParseResult_getPositionBufferSize = FlowParserWASM.cwrap('hermesParseResult_getPositionBufferSize', 'number', ['number']);
flowParseResult_getStringBuffer = FlowParserWASM.cwrap('hermesParseResult_getStringBuffer', 'number', ['number']);
}
function copyToHeap(buffer, addr) {
FlowParserWASM.HEAP8.set(buffer, addr);
FlowParserWASM.HEAP8[addr + buffer.length] = 0;
}
function flag(v) {
return v === true ? 1 : 0;
}
function parse(source, options) {
initFlowParserWASM();
const sourceBuffer = Buffer.from(source, 'utf8');
const filename = typeof options.sourceFilename === 'string' ? options.sourceFilename : '';
const filenameBuffer = filename.length > 0 ? Buffer.from(filename, 'utf8') : null;
let sourceAddr = 0;
let filenameAddr = 0;
let filenameLen = 0;
let parseResult = 0;
try {
sourceAddr = FlowParserWASM._malloc(sourceBuffer.length + 1);
if (!sourceAddr) {
throw new Error('Parser out of memory');
}
if (filenameBuffer != null) {
filenameAddr = FlowParserWASM._malloc(filenameBuffer.length + 1);
if (!filenameAddr) {
throw new Error('Parser out of memory');
}
copyToHeap(filenameBuffer, filenameAddr);
filenameLen = filenameBuffer.length + 1;
}
copyToHeap(sourceBuffer, sourceAddr);
const enableTypes = options.enableTypes === false ? 0 : 1;
const sourceTypeCode = options.sourceType === 'script' ? 1 : options.sourceType === 'module' ? 2 : 0;
parseResult = flowParse(sourceAddr, sourceBuffer.length + 1, filenameAddr, filenameLen, flag(options.enableExperimentalComponentSyntax), flag(options.enableExperimentalFlowMatchSyntax), flag(options.enableExperimentalDecorators), flag(options.tokens), flag(options.allowReturnOutsideFunction), flag(options.assertOperator), flag(options.enableEnums), flag(options.enableRecords), enableTypes, sourceTypeCode, flag(options.enableTypesPragmaDetection), 0);
const programBuffer = flowParseResult_getProgramBuffer(parseResult);
if (!programBuffer) {
const err = flowParseResult_getError(parseResult);
const syntaxError = new SyntaxError(err || 'unknown parse error');
syntaxError.loc = {
line: flowParseResult_getErrorLine(parseResult),
column: flowParseResult_getErrorColumn(parseResult)
};
throw syntaxError;
}
const deserializer = new _FlowParserDeserializer.default(programBuffer, flowParseResult_getPositionBuffer(parseResult), flowParseResult_getPositionBufferSize(parseResult), flowParseResult_getStringBuffer(parseResult), FlowParserWASM, options);
const ast = deserializer.deserialize();
if (ast.type !== 'Program') {
throw new Error(`Expected Program, got ${ast.type}`);
}
const sourceFilename = typeof options.sourceFilename === 'string' ? options.sourceFilename : null;
const visitedNodes = new WeakSet();
const locRanges = new WeakMap();
function fixLocs(node) {
if (node == null || typeof node !== 'object') {
return;
}
const wireNode = node;
if (visitedNodes.has(wireNode)) {
return;
}
visitedNodes.add(wireNode);
if (wireNode.loc != null) {
const loc = wireNode.loc;
let range = locRanges.get(loc);
if (range == null) {
const rangeStart = loc.rangeStart;
const rangeEnd = loc.rangeEnd;
if (rangeStart == null || rangeEnd == null) {
throw new Error('Expected serialized source range');
}
loc.source = sourceFilename;
range = [rangeStart, rangeEnd];
locRanges.set(loc, range);
delete loc.rangeStart;
delete loc.rangeEnd;
}
wireNode.range = range;
}
for (const key of Object.keys(wireNode)) {
const val = wireNode[key];
if (Array.isArray(val)) {
for (const child of val) {
fixLocs(child);
}
} else {
fixLocs(val);
}
}
}
fixLocs(ast);
if (options.throwOnParseErrors !== false) {
const errors = ast.errors;
if (errors != null && errors.length > 0) {
const first = errors[0];
const start = first.loc.start;
if (start == null) {
throw new Error('Expected serialized parser error start location');
}
const line = start.line;
const column = start.column;
const syntaxError = new SyntaxError(`${first.message} (${line}:${column})`);
syntaxError.loc = {
line,
column
};
throw syntaxError;
}
}
if (options.sourceType === 'script' || options.sourceType === 'module') {
ast.sourceType = options.sourceType;
} else {
ast.sourceType = detectSourceType(ast);
}
ast.docblock = (0, _getModuleDocblock.getModuleDocblock)(ast);
return asProgram(ast);
} finally {
if (parseResult !== 0) {
flowParseResult_free(parseResult);
}
if (sourceAddr !== 0) {
FlowParserWASM._free(sourceAddr);
}
if (filenameAddr !== 0) {
FlowParserWASM._free(filenameAddr);
}
}
}
function asProgram(ast) {
const program = ast;
return program;
}
function detectSourceType(program) {
if (!Array.isArray(program.body)) {
return 'script';
}
for (const stmt of program.body) {
if (stmt == null) {
continue;
}
switch (stmt.type) {
case 'ImportDeclaration':
if (stmt.importKind === 'value' || stmt.importKind == null) {
return 'module';
}
break;
case 'ExportDefaultDeclaration':
return 'module';
case 'ExportNamedDeclaration':
case 'ExportAllDeclaration':
if (stmt.exportKind === 'value' || stmt.exportKind == null) {
return 'module';
}
break;
}
}
return 'script';
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _HermesParserDecodeUTF8String = _interopRequireDefault(require("./HermesParserDecodeUTF8String"));
var _FlowParserNodeDeserializers = _interopRequireDefault(require("./FlowParserNodeDeserializers"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class FlowParserDeserializer {
constructor(programBuffer, positionBuffer, positionBufferSize, stringBufferBase, wasmParser, options) {
this.programBufferIdx = void 0;
this.positionBufferIdx = void 0;
this.positionBufferSize = void 0;
this.stringBufferBase = void 0;
this.locMap = void 0;
this.HEAPU8 = void 0;
this.HEAPU32 = void 0;
this.HEAPF64 = void 0;
this.options = void 0;
this.commentTypes = ['Block', 'Line'];
this.tokenTypes = ['Boolean', 'Identifier', 'Keyword', 'Null', 'Numeric', 'BigInt', 'Punctuator', 'String', 'RegularExpression', 'Template', 'JSXText'];
this.programBufferIdx = programBuffer / 4;
this.positionBufferIdx = positionBuffer / 4;
this.positionBufferSize = positionBufferSize;
this.stringBufferBase = stringBufferBase;
this.locMap = {};
this.HEAPU8 = wasmParser.HEAPU8;
this.HEAPU32 = wasmParser.HEAPU32;
this.HEAPF64 = wasmParser.HEAPF64;
this.options = options;
}
next() {
const num = this.HEAPU32[this.programBufferIdx++];
return num;
}
deserialize() {
const program = {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList(),
comments: this.deserializeComments()
};
program.interpreter = this.deserializeNode();
if (this.options.tokens === true) {
program.tokens = this.deserializeTokens();
} else {
this.deserializeTokens();
}
program.errors = this.deserializeErrors();
this.fillLocs();
return program;
}
deserializeErrors() {
const size = this.next();
const errors = [];
for (let i = 0; i < size; i++) {
const loc = this.addEmptyLoc();
const message = this.deserializeString();
if (message == null) {
throw new Error('Expected serialized parser error message');
}
errors.push({
loc,
message
});
}
return errors;
}
deserializeBoolean() {
return Boolean(this.next());
}
deserializeNumber() {
let floatIdx;
if (this.programBufferIdx % 2 === 0) {
floatIdx = this.programBufferIdx / 2;
this.programBufferIdx += 2;
} else {
floatIdx = (this.programBufferIdx + 1) / 2;
this.programBufferIdx += 3;
}
return this.HEAPF64[floatIdx];
}
deserializeString() {
const offsetPlusOne = this.next();
if (offsetPlusOne === 0) {
return null;
}
const size = this.next();
return (0, _HermesParserDecodeUTF8String.default)(this.stringBufferBase + offsetPlusOne - 1, size, this.HEAPU8);
}
deserializeNode() {
const nodeType = this.next();
if (nodeType === 0) {
return null;
}
const nodeDeserializer = _FlowParserNodeDeserializers.default[nodeType - 1].bind(this);
return nodeDeserializer();
}
deserializeNodeList() {
const size = this.next();
const nodeList = [];
for (let i = 0; i < size; i++) {
nodeList.push(this.deserializeNode());
}
return nodeList;
}
deserializeComments() {
const size = this.next();
const comments = [];
for (let i = 0; i < size; i++) {
const commentType = this.commentTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
comments.push({
type: commentType,
loc,
value
});
}
return comments;
}
deserializeTokens() {
const size = this.next();
const tokens = [];
for (let i = 0; i < size; i++) {
const tokenType = this.tokenTypes[this.next()];
const loc = this.addEmptyLoc();
const value = this.deserializeString();
tokens.push({
type: tokenType,
loc,
value
});
}
return tokens;
}
addEmptyLoc() {
const loc = {};
this.locMap[this.next()] = loc;
return loc;
}
fillLocs() {
for (let i = 0; i < this.positionBufferSize; i++) {
const locId = this.HEAPU32[this.positionBufferIdx++];
const kind = this.HEAPU32[this.positionBufferIdx++];
const line = this.HEAPU32[this.positionBufferIdx++];
const column = this.HEAPU32[this.positionBufferIdx++];
const offset = this.HEAPU32[this.positionBufferIdx++];
const loc = this.locMap[locId];
if (kind === 0) {
loc.start = {
line,
column
};
loc.rangeStart = offset;
} else {
loc.end = {
line,
column
};
loc.rangeEnd = offset;
}
}
}
}
exports.default = FlowParserDeserializer;
'use strict';
module.exports = [function () {
return {
type: 'EmptyStatement',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ExpressionStatement',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
directive: this.deserializeString()
};
}, function () {
return {
type: 'BlockStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'IfStatement',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
consequent: this.deserializeNode(),
alternate: this.deserializeNode()
};
}, function () {
return {
type: 'LabeledStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'BreakStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode()
};
}, function () {
return {
type: 'ContinueStatement',
loc: this.addEmptyLoc(),
label: this.deserializeNode()
};
}, function () {
return {
type: 'WithStatement',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'SwitchStatement',
loc: this.addEmptyLoc(),
discriminant: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'ReturnStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ThrowStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TryStatement',
loc: this.addEmptyLoc(),
block: this.deserializeNode(),
handler: this.deserializeNode(),
finalizer: this.deserializeNode()
};
}, function () {
return {
type: 'WhileStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
test: this.deserializeNode()
};
}, function () {
return {
type: 'DoWhileStatement',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
test: this.deserializeNode()
};
}, function () {
return {
type: 'ForStatement',
loc: this.addEmptyLoc(),
init: this.deserializeNode(),
test: this.deserializeNode(),
update: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ForInStatement',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ForOfStatement',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
body: this.deserializeNode(),
await: this.deserializeBoolean()
};
}, function () {
return {
type: 'DebuggerStatement',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MatchStatement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'FunctionDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
generator: this.deserializeBoolean(),
async: this.deserializeBoolean(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'VariableDeclaration',
loc: this.addEmptyLoc(),
kind: this.deserializeString(),
declarations: this.deserializeNodeList()
};
}, function () {
return {
type: 'VariableDeclarator',
loc: this.addEmptyLoc(),
init: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'ClassDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
superClass: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode(),
superTypeArguments: this.deserializeNode(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'ComponentDeclaration',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'HookDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
returnType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeAlias',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ImportDeclaration',
loc: this.addEmptyLoc(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode(),
importKind: this.deserializeString(),
attributes: this.deserializeNodeList()
};
}, function () {
return {
type: 'ImportDefaultSpecifier',
loc: this.addEmptyLoc(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ImportNamespaceSpecifier',
loc: this.addEmptyLoc(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ImportSpecifier',
loc: this.addEmptyLoc(),
imported: this.deserializeNode(),
local: this.deserializeNode(),
importKind: this.deserializeString()
};
}, function () {
return {
type: 'ImportAttribute',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'ImportEqualsDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
moduleReference: this.deserializeNode(),
importKind: this.deserializeString(),
isExport: this.deserializeBoolean()
};
}, function () {
return {
type: 'ExternalModuleReference',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ExportNamedDeclaration',
loc: this.addEmptyLoc(),
declaration: this.deserializeNode(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode(),
exportKind: this.deserializeString()
};
}, function () {
return {
type: 'ExportDefaultDeclaration',
loc: this.addEmptyLoc(),
declaration: this.deserializeNode()
};
}, function () {
return {
type: 'ExportAllDeclaration',
loc: this.addEmptyLoc(),
source: this.deserializeNode(),
exported: this.deserializeNode(),
exportKind: this.deserializeString()
};
}, function () {
return {
type: 'ExportSpecifier',
loc: this.addEmptyLoc(),
exported: this.deserializeNode(),
local: this.deserializeNode()
};
}, function () {
return {
type: 'ExportNamespaceSpecifier',
loc: this.addEmptyLoc(),
exported: this.deserializeNode()
};
}, function () {
return {
type: 'ExportAssignment',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ThisExpression',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'Super',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ArrayExpression',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
trailingComma: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectExpression',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList()
};
}, function () {
return {
type: 'FunctionExpression',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
generator: this.deserializeBoolean(),
async: this.deserializeBoolean(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'ArrowFunctionExpression',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
body: this.deserializeNode(),
typeParameters: this.deserializeNode(),
returnType: this.deserializeNode(),
async: this.deserializeBoolean(),
id: this.deserializeNode(),
predicate: this.deserializeNode(),
expression: this.deserializeBoolean()
};
}, function () {
return {
type: 'SequenceExpression',
loc: this.addEmptyLoc(),
expressions: this.deserializeNodeList()
};
}, function () {
return {
type: 'UnaryExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode(),
prefix: this.deserializeBoolean()
};
}, function () {
return {
type: 'BinaryExpression',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
operator: this.deserializeString()
};
}, function () {
return {
type: 'LogicalExpression',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode(),
operator: this.deserializeString()
};
}, function () {
return {
type: 'ConditionalExpression',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
alternate: this.deserializeNode(),
consequent: this.deserializeNode()
};
}, function () {
return {
type: 'UpdateExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode(),
prefix: this.deserializeBoolean()
};
}, function () {
return {
type: 'AssignmentExpression',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
left: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'MemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode(),
computed: this.deserializeBoolean(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'OptionalMemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode(),
computed: this.deserializeBoolean(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'CallExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'OptionalCallExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'NewExpression',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
typeArguments: this.deserializeNode(),
arguments: this.deserializeNodeList()
};
}, function () {
return {
type: 'YieldExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
delegate: this.deserializeBoolean()
};
}, function () {
return {
type: 'AwaitExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ImportExpression',
loc: this.addEmptyLoc(),
source: this.deserializeNode(),
options: this.deserializeNode()
};
}, function () {
return {
type: 'MetaProperty',
loc: this.addEmptyLoc(),
meta: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'TaggedTemplateExpression',
loc: this.addEmptyLoc(),
tag: this.deserializeNode(),
quasi: this.deserializeNode()
};
}, function () {
return {
type: 'TemplateLiteral',
loc: this.addEmptyLoc(),
quasis: this.deserializeNodeList(),
expressions: this.deserializeNodeList()
};
}, function () {
return {
type: 'TemplateElement',
loc: this.addEmptyLoc(),
tail: this.deserializeBoolean(),
value: {
cooked: this.deserializeString(),
raw: this.deserializeString()
}
};
}, function () {
return {
type: 'TypeCastExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'AsExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'SatisfiesExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'AsConstExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'NonNullExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
chain: this.deserializeBoolean()
};
}, function () {
return {
type: 'MatchExpression',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
cases: this.deserializeNodeList()
};
}, function () {
return {
type: 'RecordExpression',
loc: this.addEmptyLoc(),
recordConstructor: this.deserializeNode(),
typeArguments: this.deserializeNode(),
properties: this.deserializeNode()
};
}, function () {
return {
type: 'RecordExpressionProperties',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList()
};
}, function () {
const loc = this.addEmptyLoc();
const valueKind = this.next();
let value = null;
if (valueKind === 1) value = this.deserializeBoolean();else if (valueKind === 2) value = this.deserializeNumber();else if (valueKind === 3) value = this.deserializeString();
const literalType = this.deserializeString();
const raw = this.deserializeString();
const bigint = this.deserializeString();
const regexPattern = this.deserializeString();
const regexFlags = this.deserializeString();
const node = {
type: 'Literal',
loc,
value,
raw,
literalType
};
if (bigint != null) {
node.bigint = bigint;
try {
node.value = typeof BigInt === 'function' ? BigInt(bigint) : null;
} catch (e) {
node.value = null;
}
}
if (regexPattern != null) {
const flags = regexFlags != null ? regexFlags : '';
node.regex = {
pattern: regexPattern,
flags
};
try {
node.value = new RegExp(regexPattern, flags);
} catch (e) {
node.value = null;
}
}
return node;
}, function () {
return {
type: 'Identifier',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'PrivateIdentifier',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ArrayPattern',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'RestElement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'AssignmentPattern',
loc: this.addEmptyLoc(),
left: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'Property',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
kind: this.deserializeString(),
method: this.deserializeBoolean(),
shorthand: this.deserializeBoolean(),
computed: this.deserializeBoolean()
};
}, function () {
return {
type: 'SpreadElement',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ClassExpression',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
superClass: this.deserializeNode(),
implements: this.deserializeNodeList(),
body: this.deserializeNode(),
superTypeArguments: this.deserializeNode(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'ClassBody',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'ClassImplements',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'MethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
kind: this.deserializeString(),
static: this.deserializeBoolean(),
computed: this.deserializeBoolean(),
decorators: this.deserializeNodeList(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'PropertyDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
computed: this.deserializeBoolean(),
static: this.deserializeBoolean(),
variance: this.deserializeNode(),
tsAccessibility: this.deserializeString(),
declare: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
override: this.deserializeBoolean(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'StaticBlock',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'Decorator',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'ParameterProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
computed: this.deserializeBoolean(),
static: this.deserializeBoolean(),
variance: this.deserializeNode(),
tsAccessibility: this.deserializeString(),
declare: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
decorators: this.deserializeNodeList()
};
}, function () {
return {
type: 'DeclareMethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
static: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
computed: this.deserializeBoolean(),
kind: this.deserializeString(),
override: this.deserializeBoolean()
};
}, function () {
return {
type: 'AbstractMethodDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
computed: this.deserializeBoolean(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'AbstractPropertyDefinition',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
computed: this.deserializeBoolean(),
variance: this.deserializeNode(),
override: this.deserializeBoolean(),
tsAccessibility: this.deserializeString()
};
}, function () {
return {
type: 'SwitchCase',
loc: this.addEmptyLoc(),
test: this.deserializeNode(),
consequent: this.deserializeNodeList()
};
}, function () {
return {
type: 'CatchClause',
loc: this.addEmptyLoc(),
param: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'ComponentParameter',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
local: this.deserializeNode(),
shorthand: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclareVariable',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'DeclareFunction',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
predicate: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareClass',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
extends: this.deserializeNodeList(),
implements: this.deserializeNodeList(),
mixins: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareComponent',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareHook',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareModule',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareModuleExports',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareExportDeclaration',
loc: this.addEmptyLoc(),
default: this.deserializeBoolean(),
declaration: this.deserializeNode(),
specifiers: this.deserializeNodeList(),
source: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareExportAllDeclaration',
loc: this.addEmptyLoc(),
source: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareNamespace',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareInterface',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
body: this.deserializeNode(),
extends: this.deserializeNodeList()
};
}, function () {
return {
type: 'DeclareTypeAlias',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
right: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareEnum',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeAnnotation',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'Variance',
loc: this.addEmptyLoc(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'AnyTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MixedTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'EmptyTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'VoidTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NullLiteralTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'SymbolTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NumberTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'BigIntTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'StringTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'BooleanTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NullableTypeAnnotation',
loc: this.addEmptyLoc(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ArrayTypeAnnotation',
loc: this.addEmptyLoc(),
elementType: this.deserializeNode()
};
}, function () {
return {
type: 'IndexedAccessType',
loc: this.addEmptyLoc(),
objectType: this.deserializeNode(),
indexType: this.deserializeNode()
};
}, function () {
return {
type: 'OptionalIndexedAccessType',
loc: this.addEmptyLoc(),
objectType: this.deserializeNode(),
indexType: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'UnionTypeAnnotation',
loc: this.addEmptyLoc(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'IntersectionTypeAnnotation',
loc: this.addEmptyLoc(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'KeyofTypeAnnotation',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TypeOperator',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'StringLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeString(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'NumberLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeNumber(),
raw: this.deserializeString()
};
}, function () {
const loc = this.addEmptyLoc();
this.deserializeNode();
const raw = this.deserializeString();
const bigint = this.deserializeString();
let value = null;
if (bigint != null && typeof BigInt === 'function') {
try {
value = BigInt(bigint);
} catch (e) {
value = null;
}
}
return {
type: 'BigIntLiteralTypeAnnotation',
loc,
value,
raw,
bigint
};
}, function () {
return {
type: 'BooleanLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
value: this.deserializeBoolean(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'ExistsTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'UnknownTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'NeverTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'UndefinedTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'GenericTypeAnnotation',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'QualifiedTypeIdentifier',
loc: this.addEmptyLoc(),
qualification: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'QualifiedTypeofIdentifier',
loc: this.addEmptyLoc(),
qualification: this.deserializeNode(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'TypeofTypeAnnotation',
loc: this.addEmptyLoc(),
argument: this.deserializeNode(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'ImportType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TupleTypeAnnotation',
loc: this.addEmptyLoc(),
elementTypes: this.deserializeNodeList(),
inexact: this.deserializeBoolean()
};
}, function () {
return {
type: 'TupleTypeLabeledElement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
elementType: this.deserializeNode(),
variance: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'TupleTypeSpreadElement',
loc: this.addEmptyLoc(),
label: this.deserializeNode(),
typeAnnotation: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeAnnotation',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
indexers: this.deserializeNodeList(),
callProperties: this.deserializeNodeList(),
internalSlots: this.deserializeNodeList(),
inexact: this.deserializeBoolean(),
exact: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectTypeProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
value: this.deserializeNode(),
method: this.deserializeBoolean(),
optional: this.deserializeBoolean(),
static: this.deserializeBoolean(),
proto: this.deserializeBoolean(),
variance: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'ObjectTypeSpreadProperty',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeIndexer',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
key: this.deserializeNode(),
value: this.deserializeNode(),
static: this.deserializeBoolean(),
variance: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypeCallProperty',
loc: this.addEmptyLoc(),
value: this.deserializeNode(),
static: this.deserializeBoolean()
};
}, function () {
return {
type: 'ObjectTypeMappedTypeProperty',
loc: this.addEmptyLoc(),
keyTparam: this.deserializeNode(),
propType: this.deserializeNode(),
sourceType: this.deserializeNode(),
variance: this.deserializeNode(),
optional: this.deserializeString()
};
}, function () {
return {
type: 'ObjectTypeInternalSlot',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
optional: this.deserializeBoolean(),
static: this.deserializeBoolean(),
method: this.deserializeBoolean(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'FunctionTypeParam',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'TypePredicate',
loc: this.addEmptyLoc(),
parameterName: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'ConditionalTypeAnnotation',
loc: this.addEmptyLoc(),
checkType: this.deserializeNode(),
extendsType: this.deserializeNode(),
trueType: this.deserializeNode(),
falseType: this.deserializeNode()
};
}, function () {
return {
type: 'InferTypeAnnotation',
loc: this.addEmptyLoc(),
typeParameter: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceExtends',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'InterfaceTypeAnnotation',
loc: this.addEmptyLoc(),
extends: this.deserializeNodeList(),
body: this.deserializeNode()
};
}, function () {
return {
type: 'TypeParameterDeclaration',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList()
};
}, function () {
return {
type: 'TypeParameter',
loc: this.addEmptyLoc(),
name: this.deserializeString(),
const: this.deserializeBoolean(),
bound: this.deserializeNode(),
variance: this.deserializeNode(),
default: this.deserializeNode(),
usesExtendsBound: this.deserializeBoolean()
};
}, function () {
return {
type: 'TypeParameterInstantiation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList()
};
}, function () {
return {
type: 'ComponentTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ComponentTypeParameter',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclaredPredicate',
loc: this.addEmptyLoc(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'InferredPredicate',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXElement',
loc: this.addEmptyLoc(),
openingElement: this.deserializeNode(),
children: this.deserializeNodeList(),
closingElement: this.deserializeNode()
};
}, function () {
return {
type: 'JSXFragment',
loc: this.addEmptyLoc(),
openingFragment: this.deserializeNode(),
children: this.deserializeNodeList(),
closingFragment: this.deserializeNode()
};
}, function () {
return {
type: 'JSXOpeningElement',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
attributes: this.deserializeNodeList(),
selfClosing: this.deserializeBoolean(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'JSXOpeningFragment',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXClosingElement',
loc: this.addEmptyLoc(),
name: this.deserializeNode()
};
}, function () {
return {
type: 'JSXClosingFragment',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXAttribute',
loc: this.addEmptyLoc(),
name: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'JSXSpreadAttribute',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'JSXEmptyExpression',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'JSXExpressionContainer',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'JSXSpreadChild',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}, function () {
return {
type: 'JSXText',
loc: this.addEmptyLoc(),
value: this.deserializeString(),
raw: this.deserializeString()
};
}, function () {
return {
type: 'JSXMemberExpression',
loc: this.addEmptyLoc(),
object: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'JSXNamespacedName',
loc: this.addEmptyLoc(),
namespace: this.deserializeNode(),
name: this.deserializeNode()
};
}, function () {
return {
type: 'JSXIdentifier',
loc: this.addEmptyLoc(),
name: this.deserializeString()
};
}, function () {
return {
type: 'EnumBooleanBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumBooleanMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumNumberBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumNumberMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumStringBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumStringMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'EnumSymbolBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumDefaultedMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'EnumBigIntBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeBoolean(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'EnumBigIntMember',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
init: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationBody',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList()
};
}, function () {
return {
type: 'RecordDeclarationProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
defaultValue: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationStaticProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
typeAnnotation: this.deserializeNode(),
value: this.deserializeNode()
};
}, function () {
return {
type: 'RecordDeclarationImplements',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeArguments: this.deserializeNode()
};
}, function () {
return {
type: 'MatchExpressionCase',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
body: this.deserializeNode(),
guard: this.deserializeNode()
};
}, function () {
return {
type: 'MatchStatementCase',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
body: this.deserializeNode(),
guard: this.deserializeNode()
};
}, function () {
return {
type: 'MatchWildcardPattern',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'MatchLiteralPattern',
loc: this.addEmptyLoc(),
literal: this.deserializeNode()
};
}, function () {
return {
type: 'MatchUnaryPattern',
loc: this.addEmptyLoc(),
operator: this.deserializeString(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'MatchObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchInstancePattern',
loc: this.addEmptyLoc(),
targetConstructor: this.deserializeNode(),
properties: this.deserializeNode()
};
}, function () {
return {
type: 'MatchInstanceObjectPattern',
loc: this.addEmptyLoc(),
properties: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchOrPattern',
loc: this.addEmptyLoc(),
patterns: this.deserializeNodeList()
};
}, function () {
return {
type: 'MatchAsPattern',
loc: this.addEmptyLoc(),
pattern: this.deserializeNode(),
target: this.deserializeNode()
};
}, function () {
return {
type: 'MatchIdentifierPattern',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'MatchMemberPattern',
loc: this.addEmptyLoc(),
base: this.deserializeNode(),
property: this.deserializeNode()
};
}, function () {
return {
type: 'MatchBindingPattern',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
kind: this.deserializeString()
};
}, function () {
return {
type: 'MatchArrayPattern',
loc: this.addEmptyLoc(),
elements: this.deserializeNodeList(),
rest: this.deserializeNode()
};
}, function () {
return {
type: 'MatchObjectPatternProperty',
loc: this.addEmptyLoc(),
key: this.deserializeNode(),
pattern: this.deserializeNode(),
shorthand: this.deserializeBoolean()
};
}, function () {
return {
type: 'MatchRestPattern',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'Program',
loc: this.addEmptyLoc(),
body: this.deserializeNodeList()
};
}, function () {
return {
type: 'InterpreterDirective',
loc: this.addEmptyLoc(),
value: this.deserializeString()
};
}, function () {
return {
type: 'FunctionTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
this: this.deserializeNode(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'RendersType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'RendersMaybeType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'RendersStarType',
loc: this.addEmptyLoc(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'TemplateLiteralTypeAnnotation',
loc: this.addEmptyLoc(),
quasis: this.deserializeNodeList(),
types: this.deserializeNodeList()
};
}, function () {
return {
type: 'NamespaceExportDeclaration',
loc: this.addEmptyLoc(),
id: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareClassExtendsCall',
loc: this.addEmptyLoc(),
callee: this.deserializeNode(),
argument: this.deserializeNode()
};
}, function () {
return {
type: 'OpaqueType',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
impltype: this.deserializeNode(),
lowerBound: this.deserializeNode(),
upperBound: this.deserializeNode(),
supertype: this.deserializeNode()
};
}, function () {
return {
type: 'DeclareOpaqueType',
loc: this.addEmptyLoc(),
id: this.deserializeNode(),
typeParameters: this.deserializeNode(),
impltype: this.deserializeNode(),
lowerBound: this.deserializeNode(),
upperBound: this.deserializeNode(),
supertype: this.deserializeNode()
};
}, function () {
return {
type: 'EnumBody',
loc: this.addEmptyLoc(),
members: this.deserializeNodeList(),
explicitType: this.deserializeString(),
hasUnknownMembers: this.deserializeBoolean()
};
}, function () {
return {
type: 'HookTypeAnnotation',
loc: this.addEmptyLoc(),
params: this.deserializeNodeList(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ConstructorTypeAnnotation',
loc: this.addEmptyLoc(),
abstract: this.deserializeBoolean(),
params: this.deserializeNodeList(),
returnType: this.deserializeNode(),
rest: this.deserializeNode(),
typeParameters: this.deserializeNode()
};
}, function () {
return {
type: 'ObjectTypePrivateField',
loc: this.addEmptyLoc(),
key: this.deserializeNode()
};
}, function () {
return {
type: 'TupleTypeElement',
loc: this.addEmptyLoc(),
elementType: this.deserializeNode(),
optional: this.deserializeBoolean()
};
}, function () {
return {
type: 'DeclareComponent',
loc: this.addEmptyLoc(),
body: this.deserializeNode(),
id: this.deserializeNode(),
implicitDeclare: this.deserializeBoolean(),
params: this.deserializeNodeList(),
rest: this.deserializeNode(),
rendersType: this.deserializeNode(),
typeParameters: this.deserializeNode(),
async: this.deserializeBoolean()
};
}, function () {
return {
type: 'ThisTypeAnnotation',
loc: this.addEmptyLoc()
};
}, function () {
return {
type: 'ChainExpression',
loc: this.addEmptyLoc(),
expression: this.deserializeNode()
};
}];
'use strict';
module.exports = {
AbstractMethodDefinition: ['key', 'value'],
AbstractPropertyDefinition: ['key', 'value', 'variance'],
AnyTypeAnnotation: [],
ArrayExpression: ['elements'],
ArrayPattern: ['elements', 'typeAnnotation'],
ArrayTypeAnnotation: ['elementType'],
ArrowFunctionExpression: ['params', 'body', 'typeParameters', 'returnType', 'predicate'],
AsConstExpression: ['expression'],
AsExpression: ['expression', 'typeAnnotation'],
AssignmentExpression: ['left', 'right'],
AssignmentPattern: ['left', 'right'],
AwaitExpression: ['argument'],
BigIntLiteralTypeAnnotation: [],
BigIntTypeAnnotation: [],
BinaryExpression: ['left', 'right'],
BlockStatement: ['body'],
BooleanLiteralTypeAnnotation: [],
BooleanTypeAnnotation: [],
BreakStatement: ['label'],
CallExpression: ['callee', 'typeArguments', 'arguments'],
CatchClause: ['param', 'body'],
ChainExpression: ['expression'],
ClassBody: ['body'],
ClassDeclaration: ['id', 'typeParameters', 'superClass', 'superTypeArguments', 'implements', 'decorators', 'body'],
ClassExpression: ['id', 'typeParameters', 'superClass', 'superTypeArguments', 'implements', 'decorators', 'body'],
ClassImplements: ['id', 'typeParameters'],
ComponentDeclaration: ['id', 'params', 'body', 'typeParameters', 'rendersType'],
ComponentParameter: ['name', 'local'],
ComponentTypeAnnotation: ['params', 'rest', 'typeParameters', 'rendersType'],
ComponentTypeParameter: ['name', 'typeAnnotation'],
ConditionalExpression: ['test', 'consequent', 'alternate'],
ConditionalTypeAnnotation: ['checkType', 'extendsType', 'trueType', 'falseType'],
ConstructorTypeAnnotation: ['params', 'returnType', 'rest', 'typeParameters'],
ContinueStatement: ['label'],
DebuggerStatement: [],
DeclareClass: ['id', 'typeParameters', 'extends', 'implements', 'mixins', 'body'],
DeclareClassExtendsCall: ['callee', 'argument'],
DeclareComponent: ['id', 'params', 'rest', 'typeParameters', 'rendersType'],
DeclareEnum: ['id', 'body'],
DeclareExportAllDeclaration: ['source'],
DeclareExportDeclaration: ['declaration', 'specifiers', 'source'],
DeclareFunction: ['id', 'predicate'],
DeclareHook: ['id'],
DeclareInterface: ['id', 'typeParameters', 'extends', 'body'],
DeclareMethodDefinition: ['key', 'value'],
DeclareModule: ['id', 'body'],
DeclareModuleExports: ['typeAnnotation'],
DeclareNamespace: ['id', 'body'],
DeclareOpaqueType: ['id', 'typeParameters', 'impltype', 'lowerBound', 'upperBound', 'supertype'],
DeclareTypeAlias: ['id', 'typeParameters', 'right'],
DeclareVariable: ['id'],
DeclaredPredicate: ['value'],
Decorator: ['expression'],
DoWhileStatement: ['body', 'test'],
EmptyStatement: [],
EmptyTypeAnnotation: [],
EnumBigIntBody: ['members'],
EnumBigIntMember: ['id', 'init'],
EnumBody: ['members'],
EnumBooleanBody: ['members'],
EnumBooleanMember: ['id', 'init'],
EnumDeclaration: ['id', 'body'],
EnumDefaultedMember: ['id'],
EnumNumberBody: ['members'],
EnumNumberMember: ['id', 'init'],
EnumStringBody: ['members'],
EnumStringMember: ['id', 'init'],
EnumSymbolBody: ['members'],
ExistsTypeAnnotation: [],
ExportAllDeclaration: ['exported', 'source'],
ExportAssignment: ['expression'],
ExportDefaultDeclaration: ['declaration'],
ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
ExportNamespaceSpecifier: ['exported'],
ExportSpecifier: ['exported', 'local'],
ExpressionStatement: ['expression'],
ExternalModuleReference: ['expression'],
ForInStatement: ['left', 'right', 'body'],
ForOfStatement: ['left', 'right', 'body'],
ForStatement: ['init', 'test', 'update', 'body'],
FunctionDeclaration: ['id', 'params', 'body', 'typeParameters', 'returnType', 'predicate'],
FunctionExpression: ['id', 'params', 'body', 'typeParameters', 'returnType', 'predicate'],
FunctionTypeAnnotation: ['params', 'this', 'returnType', 'rest', 'typeParameters'],
FunctionTypeParam: ['name', 'typeAnnotation'],
GenericTypeAnnotation: ['id', 'typeParameters'],
HookDeclaration: ['id', 'params', 'body', 'typeParameters', 'returnType'],
HookTypeAnnotation: ['params', 'returnType', 'rest', 'typeParameters'],
Identifier: ['typeAnnotation'],
IfStatement: ['test', 'consequent', 'alternate'],
ImportAttribute: ['key', 'value'],
ImportDeclaration: ['specifiers', 'source', 'attributes'],
ImportDefaultSpecifier: ['local'],
ImportEqualsDeclaration: ['id', 'moduleReference'],
ImportExpression: ['source', 'options'],
ImportNamespaceSpecifier: ['local'],
ImportSpecifier: ['imported', 'local'],
ImportType: ['argument'],
IndexedAccessType: ['objectType', 'indexType'],
InferTypeAnnotation: ['typeParameter'],
InferredPredicate: [],
InterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'],
InterfaceExtends: ['id', 'typeParameters'],
InterfaceTypeAnnotation: ['extends', 'body'],
InterpreterDirective: [],
IntersectionTypeAnnotation: ['types'],
JSXAttribute: ['name', 'value'],
JSXClosingElement: ['name'],
JSXClosingFragment: [],
JSXElement: ['openingElement', 'children', 'closingElement'],
JSXEmptyExpression: [],
JSXExpressionContainer: ['expression'],
JSXFragment: ['openingFragment', 'children', 'closingFragment'],
JSXIdentifier: [],
JSXMemberExpression: ['object', 'property'],
JSXNamespacedName: ['namespace', 'name'],
JSXOpeningElement: ['name', 'attributes', 'typeArguments'],
JSXOpeningFragment: [],
JSXSpreadAttribute: ['argument'],
JSXSpreadChild: ['expression'],
JSXText: [],
KeyofTypeAnnotation: ['argument'],
LabeledStatement: ['label', 'body'],
LogicalExpression: ['left', 'right'],
MatchArrayPattern: ['elements', 'rest'],
MatchAsPattern: ['pattern', 'target'],
MatchBindingPattern: ['id'],
MatchExpression: ['argument', 'cases'],
MatchExpressionCase: ['pattern', 'body', 'guard'],
MatchIdentifierPattern: ['id'],
MatchInstanceObjectPattern: ['properties', 'rest'],
MatchInstancePattern: ['targetConstructor', 'properties'],
MatchLiteralPattern: ['literal'],
MatchMemberPattern: ['base', 'property'],
MatchObjectPattern: ['properties', 'rest'],
MatchObjectPatternProperty: ['key', 'pattern'],
MatchOrPattern: ['patterns'],
MatchRestPattern: ['argument'],
MatchStatement: ['argument', 'cases'],
MatchStatementCase: ['pattern', 'body', 'guard'],
MatchUnaryPattern: ['argument'],
MatchWildcardPattern: [],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', 'property'],
MethodDefinition: ['key', 'value', 'decorators'],
MixedTypeAnnotation: [],
NamespaceExportDeclaration: ['id'],
NeverTypeAnnotation: [],
NewExpression: ['callee', 'typeArguments', 'arguments'],
NonNullExpression: ['argument'],
NullLiteralTypeAnnotation: [],
NullableTypeAnnotation: ['typeAnnotation'],
NumberLiteralTypeAnnotation: [],
NumberTypeAnnotation: [],
ObjectExpression: ['properties'],
ObjectPattern: ['properties', 'typeAnnotation'],
ObjectTypeAnnotation: ['properties', 'indexers', 'callProperties', 'internalSlots'],
ObjectTypeCallProperty: ['value'],
ObjectTypeIndexer: ['id', 'key', 'value', 'variance'],
ObjectTypeInternalSlot: ['id', 'value'],
ObjectTypeMappedTypeProperty: ['keyTparam', 'propType', 'sourceType', 'variance'],
ObjectTypePrivateField: ['key'],
ObjectTypeProperty: ['key', 'value', 'variance'],
ObjectTypeSpreadProperty: ['argument'],
OpaqueType: ['id', 'typeParameters', 'impltype', 'lowerBound', 'upperBound', 'supertype'],
OptionalIndexedAccessType: ['objectType', 'indexType'],
ParameterProperty: ['key', 'value', 'typeAnnotation', 'variance', 'decorators'],
PrivateIdentifier: [],
Program: ['body'],
Property: ['key', 'value'],
PropertyDefinition: ['key', 'value', 'decorators', 'variance', 'typeAnnotation'],
QualifiedTypeIdentifier: ['qualification', 'id'],
QualifiedTypeofIdentifier: ['qualification', 'id'],
RecordDeclaration: ['id', 'typeParameters', 'implements', 'body'],
RecordDeclarationBody: ['elements'],
RecordDeclarationImplements: ['id', 'typeArguments'],
RecordDeclarationProperty: ['key', 'typeAnnotation', 'defaultValue'],
RecordDeclarationStaticProperty: ['key', 'typeAnnotation', 'value'],
RecordExpression: ['recordConstructor', 'typeArguments', 'properties'],
RecordExpressionProperties: ['properties'],
RendersMaybeType: ['argument'],
RendersStarType: ['argument'],
RendersType: ['argument'],
RestElement: ['argument'],
ReturnStatement: ['argument'],
SatisfiesExpression: ['expression', 'typeAnnotation'],
SequenceExpression: ['expressions'],
SpreadElement: ['argument'],
StaticBlock: ['body'],
StringLiteralTypeAnnotation: [],
StringTypeAnnotation: [],
Super: [],
SwitchCase: ['test', 'consequent'],
SwitchStatement: ['discriminant', 'cases'],
SymbolTypeAnnotation: [],
TaggedTemplateExpression: ['tag', 'quasi'],
TemplateElement: [],
TemplateLiteral: ['quasis', 'expressions'],
TemplateLiteralTypeAnnotation: ['quasis', 'types'],
ThisExpression: [],
ThisTypeAnnotation: [],
ThrowStatement: ['argument'],
TryStatement: ['block', 'handler', 'finalizer'],
TupleTypeAnnotation: ['elementTypes'],
TupleTypeElement: ['elementType'],
TupleTypeLabeledElement: ['label', 'elementType', 'variance'],
TupleTypeSpreadElement: ['label', 'typeAnnotation'],
TypeAlias: ['id', 'typeParameters', 'right'],
TypeAnnotation: ['typeAnnotation'],
TypeCastExpression: ['expression', 'typeAnnotation'],
TypeOperator: ['typeAnnotation'],
TypeParameter: ['bound', 'variance', 'default'],
TypeParameterDeclaration: ['params'],
TypeParameterInstantiation: ['params'],
TypePredicate: ['parameterName', 'typeAnnotation'],
TypeofTypeAnnotation: ['argument', 'typeArguments'],
UnaryExpression: ['argument'],
UndefinedTypeAnnotation: [],
UnionTypeAnnotation: ['types'],
UnknownTypeAnnotation: [],
UpdateExpression: ['argument'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
Variance: [],
VoidTypeAnnotation: [],
WhileStatement: ['test', 'body'],
WithStatement: ['object', 'body'],
YieldExpression: ['argument'],
OptionalMemberExpression: ['object', 'property'],
OptionalCallExpression: ['callee', 'typeArguments', 'arguments'],
Literal: []
};
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getModuleDocblock = getModuleDocblock;
exports.parseDocblockString = parseDocblockString;
const DIRECTIVE_REGEX = /^\s*@([a-zA-Z0-9_-]+)( +.+)?$/;
function parseDocblockString(docblock) {
const directiveLines = docblock.split('\n').map(line => line.trimStart().replace(/^\* ?/, '').trim()).filter(line => line.startsWith('@'));
const directives = Object.create(null);
for (const line of directiveLines) {
var _match$;
const match = DIRECTIVE_REGEX.exec(line);
if (match == null) {
continue;
}
const name = match[1];
const value = ((_match$ = match[2]) != null ? _match$ : '').trim();
if (directives[name]) {
directives[name].push(value);
} else {
directives[name] = [value];
}
}
return directives;
}
function getModuleDocblock(hermesProgram) {
const docblockNode = (() => {
if (hermesProgram.type !== 'Program') {
return null;
}
const program = hermesProgram;
if (program.comments.length === 0) {
return null;
}
const firstComment = (() => {
const first = program.comments[0];
if (first.type === 'Block') {
return first;
}
if (program.comments.length === 1) {
return null;
}
const second = program.comments[1];
if (first.type === 'Line' && first.range[0] === 0 && second.type === 'Block') {
return second;
}
return null;
})();
if (firstComment == null) {
return null;
}
if (program.body.length > 0 && program.body[0].range[0] < firstComment.range[0]) {
return null;
}
return firstComment;
})();
if (docblockNode == null) {
return null;
}
return {
directives: parseDocblockString(docblockNode.value),
comment: docblockNode
};
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = HermesParserDecodeUTF8String;
function HermesParserDecodeUTF8String(ptrIn, length, heap) {
let ptr = ptrIn;
const endPtr = ptr + length;
let str = '';
while (ptr < endPtr) {
let u0 = heap[ptr++];
if (!(u0 & 0x80)) {
str += String.fromCharCode(u0);
continue;
}
const u1 = heap[ptr++] & 0x3f;
if ((u0 & 0xe0) === 0xc0) {
str += String.fromCharCode((u0 & 0x1f) << 6 | u1);
continue;
}
const u2 = heap[ptr++] & 0x3f;
if ((u0 & 0xf0) === 0xe0) {
u0 = (u0 & 0x0f) << 12 | u1 << 6 | u2;
} else {
u0 = (u0 & 0x07) << 18 | u1 << 12 | u2 << 6 | heap[ptr++] & 0x3f;
}
if (u0 < 0x10000) {
str += String.fromCharCode(u0);
} else {
u0 -= 0x10000;
str += String.fromCharCode(0xd800 | u0 >> 10, 0xdc00 | u0 & 0x3ff);
}
}
return str;
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
parse: true,
mutateESTreeASTForPrettier: true,
Transforms: true,
FlowVisitorKeys: true,
astArrayMutationHelpers: true,
astNodeMutationHelpers: true
};
exports.mutateESTreeASTForPrettier = exports.astNodeMutationHelpers = exports.astArrayMutationHelpers = exports.Transforms = void 0;
exports.parse = parse;
var FlowParser = _interopRequireWildcard(require("./FlowParser"));
var _ESTreeVisitorKeys = _interopRequireDefault(require("./generated/ESTreeVisitorKeys"));
exports.FlowVisitorKeys = _ESTreeVisitorKeys.default;
var TransformComponentSyntax = _interopRequireWildcard(require("./estree/TransformComponentSyntax"));
var TransformEnumSyntax = _interopRequireWildcard(require("./estree/TransformEnumSyntax"));
var TransformMatchSyntax = _interopRequireWildcard(require("./estree/TransformMatchSyntax"));
var TransformRecordSyntax = _interopRequireWildcard(require("./estree/TransformRecordSyntax"));
var StripFlowTypesForBabel = _interopRequireWildcard(require("./estree/StripFlowTypesForBabel"));
var TransformESTreeToBabel = _interopRequireWildcard(require("./babel/TransformESTreeToBabel"));
var StripFlowTypes = _interopRequireWildcard(require("./estree/StripFlowTypes"));
var _ParserOptions = require("./ParserOptions");
Object.keys(_ParserOptions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _ParserOptions[key]) return;
exports[key] = _ParserOptions[key];
});
var _SimpleTraverser = require("./traverse/SimpleTraverser");
Object.keys(_SimpleTraverser).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _SimpleTraverser[key]) return;
exports[key] = _SimpleTraverser[key];
});
var _SimpleTransform = require("./transform/SimpleTransform");
Object.keys(_SimpleTransform).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _SimpleTransform[key]) return;
exports[key] = _SimpleTransform[key];
});
var _getVisitorKeys = require("./traverse/getVisitorKeys");
Object.keys(_getVisitorKeys).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _getVisitorKeys[key]) return;
exports[key] = _getVisitorKeys[key];
});
var _astArrayMutationHelpers = _interopRequireWildcard(require("./transform/astArrayMutationHelpers"));
exports.astArrayMutationHelpers = _astArrayMutationHelpers;
var _astNodeMutationHelpers = _interopRequireWildcard(require("./transform/astNodeMutationHelpers"));
exports.astNodeMutationHelpers = _astNodeMutationHelpers;
var _mutateESTreeASTForPrettier = _interopRequireDefault(require("./utils/mutateESTreeASTForPrettier"));
exports.mutateESTreeASTForPrettier = _mutateESTreeASTForPrettier.default;
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const DEFAULTS = {
flow: 'detect'
};
function getOptions(opts) {
const options = { ...DEFAULTS,
...(opts != null ? opts : {})
};
if (options.flow !== 'all' && options.flow !== 'detect') {
throw new Error('flow option must be "all" or "detect"');
}
if (options.sourceType === 'unambiguous') {
delete options.sourceType;
} else if (options.sourceType != null && options.sourceType !== 'script' && options.sourceType !== 'module') {
throw new Error('sourceType option must be "script", "module", or "unambiguous" if set');
}
if (options.enableExperimentalComponentSyntax == null) {
options.enableExperimentalComponentSyntax = true;
}
if (options.enableExperimentalFlowMatchSyntax == null) {
options.enableExperimentalFlowMatchSyntax = true;
}
if (options.enableExperimentalFlowRecordSyntax == null) {
options.enableExperimentalFlowRecordSyntax = true;
}
options.enableRecords = options.enableExperimentalFlowRecordSyntax;
if (options.enableEnums == null) {
options.enableEnums = true;
}
if (options.enableExperimentalDecorators == null) {
options.enableExperimentalDecorators = true;
}
options.tokens = options.tokens === true;
options.allowReturnOutsideFunction = options.allowReturnOutsideFunction === true;
return options;
}
function parse(code, opts) {
var _options$transformOpt, _options$transformOpt2;
const options = getOptions(opts);
if (options.flow === 'all') {
options.enableTypes = true;
} else {
options.enableTypesPragmaDetection = true;
}
const estreeAST = FlowParser.parse(code, options);
if (options.babel !== true) {
return estreeAST;
}
const loweredESTreeAST = [(_options$transformOpt = options.transformOptions) != null && (_options$transformOpt2 = _options$transformOpt.TransformEnumSyntax) != null && _options$transformOpt2.enable ? TransformEnumSyntax.transformProgram : null, TransformMatchSyntax.transformProgram, TransformComponentSyntax.transformProgram, TransformRecordSyntax.transformProgram, StripFlowTypesForBabel.transformProgram].reduce((ast, transform) => {
var _transform;
return (_transform = transform == null ? void 0 : transform(ast, options)) != null ? _transform : ast;
}, estreeAST);
return TransformESTreeToBabel.transformProgram(loweredESTreeAST, options);
}
const Transforms = {
transformEnumSyntax: TransformEnumSyntax.transformProgram,
transformMatchSyntax: TransformMatchSyntax.transformProgram,
transformComponentSyntax: TransformComponentSyntax.transformProgram,
transformRecordSyntax: TransformRecordSyntax.transformProgram,
stripFlowTypesForBabel: StripFlowTypesForBabel.transformProgram,
stripFlowTypes: StripFlowTypes.transformProgram
};
exports.Transforms = Transforms;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ParserOptionsKeys = void 0;
const ParserOptionsKeys = new Set(['allowReturnOutsideFunction', 'assertOperator', 'babel', 'flow', 'enableExperimentalComponentSyntax', 'enableExperimentalFlowMatchSyntax', 'enableExperimentalFlowRecordSyntax', 'reactRuntimeTarget', 'sourceFilename', 'sourceType', 'throwOnParseErrors', 'tokens', 'transformOptions']);
exports.ParserOptionsKeys = ParserOptionsKeys;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrayIsEqual = arrayIsEqual;
exports.insertInArray = insertInArray;
exports.removeFromArray = removeFromArray;
exports.replaceInArray = replaceInArray;
function assertArrayBounds(array, index) {
if (index < 0 || index >= array.length) {
throw new Error(`Invalid Mutation: Tried to mutate an elements array with an out of bounds index. Index: ${index}, Array Size: ${array.length}`);
}
}
function arrayIsEqual(a1, a2) {
if (a1 === a2) {
return true;
}
if (a1.length !== a2.length) {
return false;
}
for (let i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
function insertInArray(array, index, elements) {
if (index === array.length) {
return array.concat(elements);
}
assertArrayBounds(array, index);
return array.slice(0, index).concat(elements).concat(array.slice(index));
}
function removeFromArray(array, index) {
assertArrayBounds(array, index);
return [...array.slice(0, index), ...array.slice(index + 1)];
}
function replaceInArray(array, index, elements) {
assertArrayBounds(array, index);
return array.slice(0, index).concat(elements).concat(array.slice(index + 1));
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.deepCloneNode = deepCloneNode;
exports.nodeWith = nodeWith;
exports.removeNodeOnParent = removeNodeOnParent;
exports.replaceNodeOnParent = replaceNodeOnParent;
exports.setParentPointersInDirectChildren = setParentPointersInDirectChildren;
exports.shallowCloneNode = shallowCloneNode;
exports.updateAllParentPointers = updateAllParentPointers;
var _astArrayMutationHelpers = require("./astArrayMutationHelpers");
var _getVisitorKeys = require("../traverse/getVisitorKeys");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
function getParentKey(target, parent, visitorKeys) {
if (parent == null) {
throw new Error(`Expected parent node to be set on "${target.type}"`);
}
for (const key of (0, _getVisitorKeys.getVisitorKeys)(parent, visitorKeys)) {
if ((0, _getVisitorKeys.isNode)(parent[key])) {
if (parent[key] === target) {
return {
type: 'single',
node: parent,
key
};
}
} else if (Array.isArray(parent[key])) {
for (let i = 0; i < parent[key].length; i += 1) {
const current = parent[key][i];
if (current === target) {
return {
type: 'array',
node: parent,
key,
targetIndex: i
};
}
}
}
}
throw new Error(`Expected to find the ${target.type} as a direct child of the ${parent.type}.`);
}
function replaceNodeOnParent(originalNode, originalNodeParent, nodeToReplaceWith, visitorKeys) {
const replacementParent = getParentKey(originalNode, originalNodeParent, visitorKeys);
const parent = replacementParent.node;
if (replacementParent.type === 'array') {
parent[replacementParent.key] = (0, _astArrayMutationHelpers.replaceInArray)(parent[replacementParent.key], replacementParent.targetIndex, Array.isArray(nodeToReplaceWith) ? nodeToReplaceWith : [nodeToReplaceWith]);
} else {
if (Array.isArray(nodeToReplaceWith)) {
throw new Error(`Cannot insert array into non-array parent type: ${parent.type}`);
}
parent[replacementParent.key] = nodeToReplaceWith;
}
}
function removeNodeOnParent(originalNode, originalNodeParent, visitorKeys) {
const replacementParent = getParentKey(originalNode, originalNodeParent, visitorKeys);
const parent = replacementParent.node;
if (replacementParent.type === 'array') {
parent[replacementParent.key] = (0, _astArrayMutationHelpers.removeFromArray)(parent[replacementParent.key], replacementParent.targetIndex);
} else {
parent[replacementParent.key] = null;
}
}
function setParentPointersInDirectChildren(node, visitorKeys) {
for (const key of (0, _getVisitorKeys.getVisitorKeys)(node, visitorKeys)) {
if ((0, _getVisitorKeys.isNode)(node[key])) {
node[key].parent = node;
} else if (Array.isArray(node[key])) {
for (const child of node[key]) {
child.parent = node;
}
}
}
}
function updateAllParentPointers(node, visitorKeys) {
_SimpleTraverser.SimpleTraverser.traverse(node, {
enter(node, parent) {
node.parent = parent;
},
leave() {},
visitorKeys
});
}
function nodeWith(node, overrideProps, visitorKeys) {
const willBeUnchanged = Object.entries(overrideProps).every(([key, value]) => {
const node_ = node;
if (Array.isArray(value)) {
return Array.isArray(node_[key]) ? (0, _astArrayMutationHelpers.arrayIsEqual)(node_[key], value) : false;
}
return node_[key] === value;
});
if (willBeUnchanged) {
return node;
}
const newNode = { ...node,
...overrideProps
};
setParentPointersInDirectChildren(newNode, visitorKeys);
return newNode;
}
function shallowCloneNode(node, visitorKeys) {
const newNode = { ...node
};
setParentPointersInDirectChildren(newNode, visitorKeys);
return newNode;
}
function deepCloneNode(node, visitorKeys) {
const clone = JSON.parse(JSON.stringify(node, (key, value) => {
if (key === 'parent') {
return undefined;
}
return value;
}));
updateAllParentPointers(clone, visitorKeys);
return clone;
}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CommentPlacement = void 0;
exports.addComment = addComment;
exports.appendCommentToSource = appendCommentToSource;
exports.attachComments = attachComments;
exports.cloneComment = cloneComment;
exports.cloneCommentWithMarkers = cloneCommentWithMarkers;
exports.cloneCommentsToNewNode = cloneCommentsToNewNode;
exports.cloneJSDocCommentsToNewNode = cloneJSDocCommentsToNewNode;
exports.getCommentsForNode = getCommentsForNode;
exports.getLeadingCommentsForNode = getLeadingCommentsForNode;
exports.getTrailingCommentsForNode = getTrailingCommentsForNode;
exports.isAttachedComment = isAttachedComment;
exports.isLeadingComment = isLeadingComment;
exports.isTrailingComment = isTrailingComment;
exports.makeCommentOwnLine = makeCommentOwnLine;
exports.moveCommentsToNewNode = moveCommentsToNewNode;
exports.mutateESTreeASTCommentsForPrettier = mutateESTreeASTCommentsForPrettier;
exports.setCommentsOnNode = setCommentsOnNode;
var _comments = require("./prettier/main/comments");
var _loc = require("./prettier/language-js/loc");
var _printerEstree = _interopRequireDefault(require("./prettier/language-js/printer-estree"));
var _util = require("./prettier/common/util");
var _flowEstree = require("flow-estree");
var _os = require("os");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const CommentPlacement = require("flow-enums-runtime").Mirrored(["LEADING_OWN_LINE", "LEADING_INLINE", "TRAILING_OWN_LINE", "TRAILING_INLINE"]);
exports.CommentPlacement = CommentPlacement;
function attachComments(comments, ast, text) {
(0, _comments.attach)(comments, ast, text, {
locStart: _loc.locStart,
locEnd: _loc.locEnd,
printer: _printerEstree.default
});
}
function mutateESTreeASTCommentsForPrettier(program, text) {
let code = text;
delete program.comments;
if (program.docblock != null && program.docblock.comment != null) {
const docblockComment = program.docblock.comment;
const isDocblockCommentNew = !isAttachedComment(docblockComment);
if (isDocblockCommentNew) {
docblockComment.printed = false;
docblockComment.leading = true;
docblockComment.trailing = false;
}
if (program.body.length > 0) {
const firstStatement = program.body[0];
const leadingComments = getLeadingCommentsForNode(firstStatement);
if (!leadingComments.includes(docblockComment)) {
setCommentsOnNode(firstStatement, [docblockComment, ...getCommentsForNode(firstStatement)]);
if (isDocblockCommentNew) {
code = makeCommentOwnLine(code, docblockComment);
}
}
} else {
setCommentsOnNode(program, [docblockComment]);
}
}
delete program.docblock;
return code;
}
function moveCommentsToNewNode(oldNode, newNode) {
setCommentsOnNode(newNode, getCommentsForNode(oldNode));
setCommentsOnNode(oldNode, []);
}
function cloneCommentsToNewNode(oldNode, newNode) {
setCommentsOnNode(newNode, getCommentsForNode(oldNode).map(comment => cloneCommentWithMarkers(comment)));
}
function cloneJSDocCommentsToNewNode(oldNode, newNode) {
const comments = getCommentsForNode(oldNode).filter(comment => {
return (0, _flowEstree.isBlockComment)(comment) && comment.value.startsWith('*');
});
setCommentsOnNode(newNode, [...getCommentsForNode(newNode), ...comments.map(cloneCommentWithMarkers)]);
}
function setCommentsOnNode(node, comments) {
node.comments = comments;
}
function getCommentsForNode(node) {
var _node$comments;
return (_node$comments = node.comments) != null ? _node$comments : [];
}
function isAttachedComment(comment) {
return comment.printed === false;
}
function isLeadingComment(comment) {
return comment.leading === true;
}
function isTrailingComment(comment) {
return comment.trailing === true;
}
function getLeadingCommentsForNode(node) {
return getCommentsForNode(node).filter(isLeadingComment);
}
function getTrailingCommentsForNode(node) {
return getCommentsForNode(node).filter(isTrailingComment);
}
function addComment(node, comment, placement) {
switch (placement) {
case CommentPlacement.LEADING_OWN_LINE:
case CommentPlacement.LEADING_INLINE:
{
(0, _util.addLeadingComment)(node, comment);
break;
}
case CommentPlacement.TRAILING_OWN_LINE:
case CommentPlacement.TRAILING_INLINE:
{
(0, _util.addTrailingComment)(node, comment);
break;
}
}
}
function cloneComment(comment) {
return {
type: comment.type,
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
function cloneCommentWithMarkers(comment) {
return {
type: comment.type,
value: comment.value,
loc: comment.loc,
range: comment.range,
leading: isLeadingComment(comment),
trailing: isTrailingComment(comment)
};
}
function getFirstNewlineIndex(code) {
return code.search(/\r\n|\n|\r/);
}
function getFirstNonWhitespaceIndex(code) {
return code.search(/\S/);
}
function makeCommentOwnLine(code, comment) {
let newCode = code;
let firstNewline = getFirstNewlineIndex(code);
if (firstNewline === -1) {
newCode += _os.EOL;
firstNewline = newCode.length;
}
comment.range = [firstNewline + 1, firstNewline];
return newCode;
}
function appendCommentToSource(code, comment, placement) {
let newCode = code;
switch (comment.type) {
case 'Block':
{
switch (placement) {
case CommentPlacement.LEADING_OWN_LINE:
case CommentPlacement.TRAILING_OWN_LINE:
{
newCode = makeCommentOwnLine(code, comment);
break;
}
case CommentPlacement.LEADING_INLINE:
case CommentPlacement.TRAILING_INLINE:
{
let firstNonWhitespace = getFirstNonWhitespaceIndex(code);
if (firstNonWhitespace === -1) {
newCode += '$FORCE_INLINE_ON_EMPTY_FILE_TOKEN$;';
firstNonWhitespace = newCode.length;
break;
}
comment.range = [firstNonWhitespace + 1, firstNonWhitespace];
break;
}
}
break;
}
case 'Line':
{
const commentText = `//${comment.value}`;
const lastChar = newCode[newCode.length - 1];
if (lastChar !== '\n' && lastChar !== '\r') {
newCode += _os.EOL;
}
if (placement === CommentPlacement.TRAILING_INLINE) {
newCode += '$FORCE_END_OF_LINE_COMMENT_TOKEN$;';
}
const start = newCode.length;
newCode += commentText;
const end = newCode.length;
comment.range = [start, end];
break;
}
}
return newCode;
}
'use strict';
const stringWidth = require('string-width');
const getLast = require('../utils/get-last.js');
const notAsciiRegex = /[^\x20-\x7F]/;
function skip(chars) {
return (text, index, opts) => {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const {
length
} = text;
let cursor = index;
while (cursor >= 0 && cursor < length) {
const c = text.charAt(cursor);
if (chars instanceof RegExp) {
if (!chars.test(c)) {
return cursor;
}
} else if (!chars.includes(c)) {
return cursor;
}
backwards ? cursor-- : cursor++;
}
if (cursor === -1 || cursor === length) {
return cursor;
}
return false;
};
}
const skipWhitespace = skip(/\s/);
const skipSpaces = skip(' \t');
const skipToLineEnd = skip(',; \t');
const skipEverythingButNewLine = skip(/[^\n\r]/);
function skipInlineComment(text, index) {
if (index === false) {
return false;
}
if (text.charAt(index) === '/' && text.charAt(index + 1) === '*') {
for (let i = index + 2; i < text.length; ++i) {
if (text.charAt(i) === '*' && text.charAt(i + 1) === '/') {
return i + 2;
}
}
}
return index;
}
function skipTrailingComment(text, index) {
if (index === false) {
return false;
}
if (text.charAt(index) === '/' && text.charAt(index + 1) === '/') {
return skipEverythingButNewLine(text, index);
}
return index;
}
function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const atIndex = text.charAt(index);
if (backwards) {
if (text.charAt(index - 1) === '\r' && atIndex === '\n') {
return index - 2;
}
if (atIndex === '\n' || atIndex === '\r' || atIndex === '\u2028' || atIndex === '\u2029') {
return index - 1;
}
} else {
if (atIndex === '\r' && text.charAt(index + 1) === '\n') {
return index + 2;
}
if (atIndex === '\n' || atIndex === '\r' || atIndex === '\u2028' || atIndex === '\u2029') {
return index + 1;
}
}
return index;
}
function hasNewline(text, index, opts = {}) {
const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
const idx2 = skipNewline(text, idx, opts);
return idx !== idx2;
}
function hasNewlineInRange(text, start, end) {
for (let i = start; i < end; ++i) {
if (text.charAt(i) === '\n') {
return true;
}
}
return false;
}
function isNextLineEmptyAfterIndex(text, index) {
let oldIdx = null;
let idx = index;
while (idx !== oldIdx) {
oldIdx = idx;
idx = skipToLineEnd(text, idx);
idx = skipInlineComment(text, idx);
idx = skipSpaces(text, idx);
}
idx = skipTrailingComment(text, idx);
idx = skipNewline(text, idx);
return idx !== false && hasNewline(text, idx);
}
function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
let oldIdx = null;
let nextIdx = idx;
while (nextIdx !== oldIdx) {
oldIdx = nextIdx;
nextIdx = skipSpaces(text, nextIdx);
nextIdx = skipInlineComment(text, nextIdx);
nextIdx = skipTrailingComment(text, nextIdx);
nextIdx = skipNewline(text, nextIdx);
}
return nextIdx;
}
function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
}
function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
return text.charAt(getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
}
function getStringWidth(text) {
if (!text) {
return 0;
}
if (!notAsciiRegex.test(text)) {
return text.length;
}
return stringWidth(text);
}
function addCommentHelper(node, comment) {
const comments = node.comments || (node.comments = []);
comments.push(comment);
comment.printed = false;
comment.nodeDescription = describeNodeForDebugging(node);
}
function addLeadingComment(node, comment) {
comment.leading = true;
comment.trailing = false;
addCommentHelper(node, comment);
}
function addDanglingComment(node, comment, marker) {
comment.leading = false;
comment.trailing = false;
if (marker) {
comment.marker = marker;
}
addCommentHelper(node, comment);
}
function addTrailingComment(node, comment) {
comment.leading = false;
comment.trailing = true;
addCommentHelper(node, comment);
}
function isNonEmptyArray(object) {
return Array.isArray(object) && object.length > 0;
}
function describeNodeForDebugging(node) {
const nodeType = node.type || node.kind || '(unknown type)';
let nodeName = String(node.name || node.id && (typeof node.id === 'object' ? node.id.name : node.id) || node.key && (typeof node.key === 'object' ? node.key.name : node.key) || node.value && (typeof node.value === 'object' ? '' : String(node.value)) || node.operator || '');
if (nodeName.length > 20) {
nodeName = nodeName.slice(0, 19) + '…';
}
return nodeType + (nodeName ? ' ' + nodeName : '');
}
module.exports = {
getStringWidth,
getLast,
getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
getNextNonSpaceNonCommentCharacterIndex,
getNextNonSpaceNonCommentCharacter,
skipWhitespace,
skipSpaces,
skipNewline,
isNextLineEmptyAfterIndex,
hasNewline,
hasNewlineInRange,
addLeadingComment,
addDanglingComment,
addTrailingComment,
isNonEmptyArray
};
'use strict';
const {
getLast,
hasNewline,
addLeadingComment,
getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
getNextNonSpaceNonCommentCharacterIndex,
hasNewlineInRange,
addTrailingComment,
addDanglingComment,
getNextNonSpaceNonCommentCharacter,
isNonEmptyArray
} = require('../common/util.js');
const {
isBlockComment,
getFunctionParameters,
isPrettierIgnoreComment,
isCallLikeExpression,
getCallArguments,
isCallExpression,
isMemberExpression,
isObjectProperty
} = require('./utils.js');
const {
locStart,
locEnd
} = require('./loc.js');
function handleOwnLineComment(context) {
return [handleIgnoreComments, handleLastFunctionArgComments, handleMemberExpressionComments, handleIfStatementComments, handleWhileComments, handleTryStatementComments, handleClassComments, handleImportSpecifierComments, handleForComments, handleUnionTypeComments, handleMatchOrPatternComments, handleOnlyComments, handleImportDeclarationComments, handleAssignmentPatternComments, handleMethodNameComments, handleLabeledStatementComments].some(fn => fn(context));
}
function handleEndOfLineComment(context) {
return [handleClosureTypeCastComments, handleLastFunctionArgComments, handleConditionalExpressionComments, handleImportSpecifierComments, handleIfStatementComments, handleWhileComments, handleTryStatementComments, handleClassComments, handleLabeledStatementComments, handleCallExpressionComments, handlePropertyComments, handleOnlyComments, handleTypeAliasComments, handleVariableDeclaratorComments].some(fn => fn(context));
}
function handleRemainingComment(context) {
return [handleIgnoreComments, handleIfStatementComments, handleWhileComments, handleObjectPropertyAssignment, handleCommentInEmptyParens, handleMethodNameComments, handleOnlyComments, handleCommentAfterArrowParams, handleFunctionNameComments, handleTSMappedTypeComments, handleBreakAndContinueStatementComments, handleTSFunctionTrailingComments].some(fn => fn(context));
}
function addBlockStatementFirstComment(node, comment) {
const firstNonEmptyNode = (node.body || node.properties).find(({
type
}) => type !== 'EmptyStatement');
if (firstNonEmptyNode) {
addLeadingComment(firstNonEmptyNode, comment);
} else {
addDanglingComment(node, comment);
}
}
function addBlockOrNotComment(node, comment) {
if (node.type === 'BlockStatement') {
addBlockStatementFirstComment(node, comment);
} else {
addLeadingComment(node, comment);
}
}
function handleClosureTypeCastComments({
comment,
followingNode
}) {
if (followingNode && isTypeCastComment(comment)) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleIfStatementComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (!enclosingNode || enclosingNode.type !== 'IfStatement' || !followingNode) {
return false;
}
const nextCharacter = getNextNonSpaceNonCommentCharacter(text, comment, locEnd);
if (nextCharacter === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
if (precedingNode.type === 'BlockStatement') {
addTrailingComment(precedingNode, comment);
} else {
addDanglingComment(enclosingNode, comment);
}
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (followingNode.type === 'IfStatement') {
addBlockOrNotComment(followingNode.consequent, comment);
return true;
}
if (enclosingNode.consequent === followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleWhileComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (!enclosingNode || enclosingNode.type !== 'WhileStatement' || !followingNode) {
return false;
}
const nextCharacter = getNextNonSpaceNonCommentCharacter(text, comment, locEnd);
if (nextCharacter === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (enclosingNode.body === followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleTryStatementComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (!enclosingNode || enclosingNode.type !== 'TryStatement' && enclosingNode.type !== 'CatchClause' || !followingNode) {
return false;
}
if (enclosingNode.type === 'CatchClause' && precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (followingNode.type === 'TryStatement') {
addBlockOrNotComment(followingNode.finalizer, comment);
return true;
}
if (followingNode.type === 'CatchClause') {
addBlockOrNotComment(followingNode.body, comment);
return true;
}
return false;
}
function handleMemberExpressionComments({
comment,
enclosingNode,
followingNode
}) {
if (isMemberExpression(enclosingNode) && followingNode && followingNode.type === 'Identifier') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleConditionalExpressionComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
const isSameLineAsPrecedingNode = precedingNode && !hasNewlineInRange(text, locEnd(precedingNode), locStart(comment));
if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && (enclosingNode.type === 'ConditionalExpression' || enclosingNode.type === 'TSConditionalType') && followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleObjectPropertyAssignment({
comment,
precedingNode,
enclosingNode
}) {
if (isObjectProperty(enclosingNode) && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === 'AssignmentPattern') {
addTrailingComment(enclosingNode.value.left, comment);
return true;
}
return false;
}
function handleClassComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ClassDeclaration' || enclosingNode.type === 'ClassExpression' || enclosingNode.type === 'DeclareClass' || enclosingNode.type === 'DeclareInterface' || enclosingNode.type === 'InterfaceDeclaration' || enclosingNode.type === 'TSInterfaceDeclaration')) {
if (isNonEmptyArray(enclosingNode.decorators) && !(followingNode && followingNode.type === 'Decorator')) {
addTrailingComment(getLast(enclosingNode.decorators), comment);
return true;
}
if (enclosingNode.body && followingNode === enclosingNode.body) {
addBlockStatementFirstComment(enclosingNode.body, comment);
return true;
}
if (followingNode) {
for (const prop of ['implements', 'extends', 'mixins']) {
if (enclosingNode[prop] && followingNode === enclosingNode[prop][0]) {
if (precedingNode && (precedingNode === enclosingNode.id || precedingNode === enclosingNode.typeParameters || precedingNode === enclosingNode.superClass)) {
addTrailingComment(precedingNode, comment);
} else {
addDanglingComment(enclosingNode, comment, prop);
}
return true;
}
}
}
}
return false;
}
function handleMethodNameComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (enclosingNode && precedingNode && (enclosingNode.type === 'Property' || enclosingNode.type === 'TSDeclareMethod' || enclosingNode.type === 'TSAbstractMethodDefinition') && precedingNode.type === 'Identifier' && enclosingNode.key === precedingNode && getNextNonSpaceNonCommentCharacter(text, precedingNode, locEnd) !== ':') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode && enclosingNode && precedingNode.type === 'Decorator' && (enclosingNode.type === 'ClassMethod' || enclosingNode.type === 'ClassProperty' || enclosingNode.type === 'PropertyDefinition' || enclosingNode.type === 'TSAbstractPropertyDefinition' || enclosingNode.type === 'TSAbstractMethodDefinition' || enclosingNode.type === 'TSDeclareMethod' || enclosingNode.type === 'MethodDefinition')) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleFunctionNameComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (getNextNonSpaceNonCommentCharacter(text, comment, locEnd) !== '(') {
return false;
}
if (precedingNode && enclosingNode && (enclosingNode.type === 'FunctionDeclaration' || enclosingNode.type === 'FunctionExpression' || enclosingNode.type === 'ClassMethod' || enclosingNode.type === 'MethodDefinition' || enclosingNode.type === 'ObjectMethod')) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleCommentAfterArrowParams({
comment,
enclosingNode,
text
}) {
if (!(enclosingNode && enclosingNode.type === 'ArrowFunctionExpression')) {
return false;
}
const index = getNextNonSpaceNonCommentCharacterIndex(text, comment, locEnd);
if (index !== false && text.slice(index, index + 2) === '=>') {
addDanglingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleCommentInEmptyParens({
comment,
enclosingNode,
text
}) {
if (getNextNonSpaceNonCommentCharacter(text, comment, locEnd) !== ')') {
return false;
}
if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && getFunctionParameters(enclosingNode).length === 0 || isCallLikeExpression(enclosingNode) && getCallArguments(enclosingNode).length === 0)) {
addDanglingComment(enclosingNode, comment);
return true;
}
if (enclosingNode && (enclosingNode.type === 'MethodDefinition' || enclosingNode.type === 'TSAbstractMethodDefinition') && getFunctionParameters(enclosingNode.value).length === 0) {
addDanglingComment(enclosingNode.value, comment);
return true;
}
return false;
}
function handleLastFunctionArgComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (precedingNode && precedingNode.type === 'FunctionTypeParam' && enclosingNode && enclosingNode.type === 'FunctionTypeAnnotation' && followingNode && followingNode.type !== 'FunctionTypeParam') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode && (precedingNode.type === 'Identifier' || precedingNode.type === 'AssignmentPattern') && enclosingNode && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (enclosingNode && enclosingNode.type === 'FunctionDeclaration' && followingNode && followingNode.type === 'BlockStatement') {
const functionParamRightParenIndex = (() => {
const parameters = getFunctionParameters(enclosingNode);
if (parameters.length > 0) {
return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(getLast(parameters)));
}
const functionParamLeftParenIndex = getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(enclosingNode.id));
return functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
})();
if (locStart(comment) > functionParamRightParenIndex) {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
}
return false;
}
function handleImportSpecifierComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'ImportSpecifier') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleLabeledStatementComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'LabeledStatement') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleBreakAndContinueStatementComments({
comment,
enclosingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ContinueStatement' || enclosingNode.type === 'BreakStatement') && !enclosingNode.label) {
addTrailingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleCallExpressionComments({
comment,
precedingNode,
enclosingNode
}) {
if (isCallExpression(enclosingNode) && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
addLeadingComment(enclosingNode.arguments[0], comment);
return true;
}
return false;
}
function handleUnionTypeComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'UnionTypeAnnotation' || enclosingNode.type === 'TSUnionType')) {
if (isPrettierIgnoreComment(comment)) {
followingNode.prettierIgnore = true;
comment.unignore = true;
}
if (precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
if (followingNode && (followingNode.type === 'UnionTypeAnnotation' || followingNode.type === 'TSUnionType') && isPrettierIgnoreComment(comment)) {
followingNode.types[0].prettierIgnore = true;
comment.unignore = true;
}
return false;
}
function handleMatchOrPatternComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && enclosingNode.type === 'MatchOrPattern') {
if (isPrettierIgnoreComment(comment)) {
followingNode.prettierIgnore = true;
comment.unignore = true;
}
if (precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
if (followingNode && followingNode.type === 'MatchOrPattern' && isPrettierIgnoreComment(comment)) {
followingNode.types[0].prettierIgnore = true;
comment.unignore = true;
}
return false;
}
function handlePropertyComments({
comment,
enclosingNode
}) {
if (isObjectProperty(enclosingNode)) {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleOnlyComments({
comment,
enclosingNode,
followingNode,
ast,
isLastComment
}) {
if (ast && ast.body && ast.body.length === 0) {
if (isLastComment) {
addDanglingComment(ast, comment);
} else {
addLeadingComment(ast, comment);
}
return true;
}
if (enclosingNode && enclosingNode.type === 'Program' && enclosingNode.body.length === 0 && !isNonEmptyArray(enclosingNode.directives)) {
if (isLastComment) {
addDanglingComment(enclosingNode, comment);
} else {
addLeadingComment(enclosingNode, comment);
}
return true;
}
if (followingNode && followingNode.type === 'Program' && followingNode.body.length === 0 && enclosingNode && enclosingNode.type === 'ModuleExpression') {
addDanglingComment(followingNode, comment);
return true;
}
return false;
}
function handleForComments({
comment,
enclosingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ForInStatement' || enclosingNode.type === 'ForOfStatement')) {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleImportDeclarationComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (precedingNode && precedingNode.type === 'ImportSpecifier' && enclosingNode && enclosingNode.type === 'ImportDeclaration' && hasNewline(text, locEnd(comment))) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleAssignmentPatternComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'AssignmentPattern') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleTypeAliasComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'TypeAlias') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleVariableDeclaratorComments({
comment,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'VariableDeclarator' || enclosingNode.type === 'AssignmentExpression') && followingNode && (followingNode.type === 'ObjectExpression' || followingNode.type === 'ArrayExpression' || followingNode.type === 'TemplateLiteral' || followingNode.type === 'TaggedTemplateExpression' || isBlockComment(comment))) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleTSFunctionTrailingComments({
comment,
enclosingNode,
followingNode,
text
}) {
if (!followingNode && enclosingNode && (enclosingNode.type === 'TSMethodSignature' || enclosingNode.type === 'TSDeclareFunction' || enclosingNode.type === 'TSAbstractMethodDefinition') && getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === ';') {
addTrailingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleIgnoreComments({
comment,
enclosingNode,
followingNode
}) {
if (isPrettierIgnoreComment(comment) && enclosingNode && enclosingNode.type === 'TSMappedType' && followingNode && followingNode.type === 'TSTypeParameter' && followingNode.constraint) {
enclosingNode.prettierIgnore = true;
comment.unignore = true;
return true;
}
}
function handleTSMappedTypeComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (!enclosingNode || enclosingNode.type !== 'TSMappedType') {
return false;
}
if (followingNode && followingNode.type === 'TSTypeParameter' && followingNode.name) {
addLeadingComment(followingNode.name, comment);
return true;
}
if (precedingNode && precedingNode.type === 'TSTypeParameter' && precedingNode.constraint) {
addTrailingComment(precedingNode.constraint, comment);
return true;
}
return false;
}
function isRealFunctionLikeNode(node) {
return node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ObjectMethod' || node.type === 'ClassMethod' || node.type === 'TSDeclareFunction' || node.type === 'TSCallSignatureDeclaration' || node.type === 'TSConstructSignatureDeclaration' || node.type === 'TSMethodSignature' || node.type === 'TSConstructorType' || node.type === 'TSFunctionType' || node.type === 'TSDeclareMethod';
}
function getCommentChildNodes(node, options) {
if ((options.parser === 'typescript' || options.parser === 'flow' || options.parser === 'espree' || options.parser === 'meriyah' || options.parser === '__babel_estree') && node.type === 'MethodDefinition' && node.value && node.value.type === 'FunctionExpression' && getFunctionParameters(node.value).length === 0 && !node.value.returnType && !isNonEmptyArray(node.value.typeParameters) && node.value.body) {
return [...(node.decorators || []), node.key, node.value.body];
}
}
function isTypeCastComment(comment) {
return isBlockComment(comment) && comment.value[0] === '*' && /@type\b/.test(comment.value);
}
module.exports = {
handleOwnLineComment,
handleEndOfLineComment,
handleRemainingComment,
getCommentChildNodes
};
'use strict';
const {
isNonEmptyArray
} = require('../common/util.js');
function locStart(node, opts) {
const {
ignoreDecorators
} = opts || {};
if (!ignoreDecorators) {
const decorators = node.declaration && node.declaration.decorators || node.decorators;
if (isNonEmptyArray(decorators)) {
return locStart(decorators[0]);
}
}
return node.range ? node.range[0] : node.start;
}
function locEnd(node) {
return node.range ? node.range[1] : node.end;
}
module.exports = {
locStart,
locEnd
};
'use strict';
const handleComments = require('./comments.js');
const {
isBlockComment,
isLineComment
} = require('./utils.js');
function canAttachComment(node) {
return node.type && !isBlockComment(node) && !isLineComment(node) && node.type !== 'EmptyStatement' && node.type !== 'TemplateElement' && node.type !== 'Import' && node.type !== 'TSEmptyBodyFunctionExpression';
}
module.exports = {
canAttachComment,
handleComments: {
avoidAstMutation: true,
ownLine: handleComments.handleOwnLineComment,
endOfLine: handleComments.handleEndOfLineComment,
remaining: handleComments.handleRemainingComment
},
getCommentChildNodes: handleComments.getCommentChildNodes
};
'use strict';
function isBlockComment(comment) {
return comment.type === 'Block' || comment.type === 'CommentBlock' || comment.type === 'MultiLine';
}
function isLineComment(comment) {
return comment.type === 'Line' || comment.type === 'CommentLine' || comment.type === 'SingleLine' || comment.type === 'HashbangComment' || comment.type === 'HTMLOpen' || comment.type === 'HTMLClose';
}
function isCallExpression(node) {
return node && (node.type === 'CallExpression' || node.type === 'OptionalCallExpression');
}
function isMemberExpression(node) {
return node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression');
}
const functionParametersCache = new WeakMap();
function getFunctionParameters(node) {
if (functionParametersCache.has(node)) {
return functionParametersCache.get(node);
}
const parameters = [];
if (node.this) {
parameters.push(node.this);
}
if (Array.isArray(node.parameters)) {
parameters.push(...node.parameters);
} else if (Array.isArray(node.params)) {
parameters.push(...node.params);
}
if (node.rest) {
parameters.push(node.rest);
}
functionParametersCache.set(node, parameters);
return parameters;
}
const callArgumentsCache = new WeakMap();
function getCallArguments(node) {
if (callArgumentsCache.has(node)) {
return callArgumentsCache.get(node);
}
let args = node.arguments;
if (node.type === 'ImportExpression') {
args = [node.source];
if (node.attributes) {
args.push(node.attributes);
}
}
callArgumentsCache.set(node, args);
return args;
}
function isPrettierIgnoreComment(comment) {
return comment.value.trim() === 'prettier-ignore' && !comment.unignore;
}
function isCallLikeExpression(node) {
return isCallExpression(node) || node.type === 'NewExpression' || node.type === 'ImportExpression';
}
function isObjectProperty(node) {
return node && (node.type === 'ObjectProperty' || node.type === 'Property' && !node.method && node.kind === 'init');
}
module.exports = {
getFunctionParameters,
getCallArguments,
isBlockComment,
isCallLikeExpression,
isLineComment,
isPrettierIgnoreComment,
isCallExpression,
isMemberExpression,
isObjectProperty
};
'use strict';
const assert = require('assert');
const {
hasNewline,
addLeadingComment,
addDanglingComment,
addTrailingComment
} = require('../common/util.js');
const childNodesCache = new WeakMap();
function getSortedChildNodes(node, options, resultArray) {
if (!node) {
return;
}
const {
printer,
locStart,
locEnd
} = options;
if (resultArray) {
if (printer.canAttachComment && printer.canAttachComment(node)) {
let i;
for (i = resultArray.length - 1; i >= 0; --i) {
if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
break;
}
}
resultArray.splice(i + 1, 0, node);
return;
}
} else if (childNodesCache.has(node)) {
return childNodesCache.get(node);
}
const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === 'object' && Object.entries(node).filter(([key]) => key !== 'enclosingNode' && key !== 'precedingNode' && key !== 'followingNode' && key !== 'tokens' && key !== 'comments' && key !== 'parent').map(([, value]) => value);
if (!childNodes) {
return;
}
if (!resultArray) {
resultArray = [];
childNodesCache.set(node, resultArray);
}
for (const childNode of childNodes) {
getSortedChildNodes(childNode, options, resultArray);
}
return resultArray;
}
function decorateComment(node, comment, options, enclosingNode) {
const {
locStart,
locEnd
} = options;
const commentStart = locStart(comment);
const commentEnd = locEnd(comment);
const childNodes = getSortedChildNodes(node, options);
let precedingNode;
let followingNode;
let left = 0;
let right = childNodes.length;
while (left < right) {
const middle = left + right >> 1;
const child = childNodes[middle];
const start = locStart(child);
const end = locEnd(child);
if (start <= commentStart && commentEnd <= end) {
return decorateComment(child, comment, options, child);
}
if (end <= commentStart) {
precedingNode = child;
left = middle + 1;
continue;
}
if (commentEnd <= start) {
followingNode = child;
right = middle;
continue;
}
throw new Error('Comment location overlaps with node location');
}
if (enclosingNode && enclosingNode.type === 'TemplateLiteral') {
const {
quasis
} = enclosingNode;
const commentIndex = findExpressionIndexForComment(quasis, comment, options);
if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
precedingNode = null;
}
if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
followingNode = null;
}
}
return {
enclosingNode,
precedingNode,
followingNode
};
}
const returnFalse = () => false;
function attach(comments, ast, text, options) {
if (!Array.isArray(comments)) {
return;
}
const tiesToBreak = [];
const {
locStart,
locEnd,
printer: {
handleComments = {}
}
} = options;
const {
avoidAstMutation,
ownLine: handleOwnLineComment = returnFalse,
endOfLine: handleEndOfLineComment = returnFalse,
remaining: handleRemainingComment = returnFalse
} = handleComments;
const decoratedComments = comments.map((comment, index) => ({ ...decorateComment(ast, comment, options),
comment,
text,
options,
ast,
isLastComment: comments.length - 1 === index
}));
for (const [index, context] of decoratedComments.entries()) {
const {
comment,
precedingNode,
enclosingNode,
followingNode,
text,
options,
ast,
isLastComment
} = context;
if (options.parser === 'json' || options.parser === 'json5' || options.parser === '__js_expression' || options.parser === '__vue_expression') {
if (locStart(comment) - locStart(ast) <= 0) {
addLeadingComment(ast, comment);
continue;
}
if (locEnd(comment) - locEnd(ast) >= 0) {
addTrailingComment(ast, comment);
continue;
}
}
let args;
if (avoidAstMutation) {
args = [context];
} else {
comment.enclosingNode = enclosingNode;
comment.precedingNode = precedingNode;
comment.followingNode = followingNode;
args = [comment, text, options, ast, isLastComment];
}
if (isOwnLineComment(text, options, decoratedComments, index)) {
comment.placement = 'ownLine';
if (handleOwnLineComment(...args)) {} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
} else if (isEndOfLineComment(text, options, decoratedComments, index)) {
comment.placement = 'endOfLine';
if (handleEndOfLineComment(...args)) {} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
} else {
comment.placement = 'remaining';
if (handleRemainingComment(...args)) {} else if (precedingNode && followingNode) {
const tieCount = tiesToBreak.length;
if (tieCount > 0) {
const lastTie = tiesToBreak[tieCount - 1];
if (lastTie.followingNode !== followingNode) {
breakTies(tiesToBreak, text, options);
}
}
tiesToBreak.push(context);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
}
}
breakTies(tiesToBreak, text, options);
if (!avoidAstMutation) {
for (const comment of comments) {
delete comment.precedingNode;
delete comment.enclosingNode;
delete comment.followingNode;
}
}
}
const isAllEmptyAndNoLineBreak = text => !/[\S\n\u2028\u2029]/.test(text);
function isOwnLineComment(text, options, decoratedComments, commentIndex) {
const {
comment,
precedingNode
} = decoratedComments[commentIndex];
const {
locStart,
locEnd
} = options;
let start = locStart(comment);
if (precedingNode) {
for (let index = commentIndex - 1; index >= 0; index--) {
const {
comment,
precedingNode: currentCommentPrecedingNode
} = decoratedComments[index];
if (currentCommentPrecedingNode !== precedingNode || !isAllEmptyAndNoLineBreak(text.slice(locEnd(comment), start))) {
break;
}
start = locStart(comment);
}
}
return hasNewline(text, start, {
backwards: true
});
}
function isEndOfLineComment(text, options, decoratedComments, commentIndex) {
const {
comment,
followingNode
} = decoratedComments[commentIndex];
const {
locStart,
locEnd
} = options;
let end = locEnd(comment);
if (followingNode) {
for (let index = commentIndex + 1; index < decoratedComments.length; index++) {
const {
comment,
followingNode: currentCommentFollowingNode
} = decoratedComments[index];
if (currentCommentFollowingNode !== followingNode || !isAllEmptyAndNoLineBreak(text.slice(end, locStart(comment)))) {
break;
}
end = locEnd(comment);
}
}
return hasNewline(text, end);
}
function breakTies(tiesToBreak, text, options) {
const tieCount = tiesToBreak.length;
if (tieCount === 0) {
return;
}
const {
precedingNode,
followingNode,
enclosingNode
} = tiesToBreak[0];
const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
let gapEndPos = options.locStart(followingNode);
let indexOfFirstLeadingComment;
for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
const {
comment,
precedingNode: currentCommentPrecedingNode,
followingNode: currentCommentFollowingNode
} = tiesToBreak[indexOfFirstLeadingComment - 1];
assert.strictEqual(currentCommentPrecedingNode, precedingNode);
assert.strictEqual(currentCommentFollowingNode, followingNode);
const gap = text.slice(options.locEnd(comment), gapEndPos);
if (gapRegExp.test(gap)) {
gapEndPos = options.locStart(comment);
} else {
break;
}
}
for (const [i, {
comment
}] of tiesToBreak.entries()) {
if (i < indexOfFirstLeadingComment) {
addTrailingComment(precedingNode, comment);
} else {
addLeadingComment(followingNode, comment);
}
}
for (const node of [precedingNode, followingNode]) {
if (node.comments && node.comments.length > 1) {
node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
}
}
tiesToBreak.length = 0;
}
function findExpressionIndexForComment(quasis, comment, options) {
const startPos = options.locStart(comment) - 1;
for (let i = 1; i < quasis.length; ++i) {
if (startPos < options.locStart(quasis[i])) {
return i - 1;
}
}
return 0;
}
module.exports = {
attach
};
'use strict';
const getLast = arr => arr[arr.length - 1];
module.exports = getLast;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.print = print;
var _mutateESTreeASTForPrettier = _interopRequireDefault(require("../../utils/mutateESTreeASTForPrettier"));
var prettier = _interopRequireWildcard(require("prettier"));
var _comments = require("./comments/comments");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
async function print(ast, originalCode, prettierOptions = {}, visitorKeys) {
const program = ast;
if (program.body.length === 0) {
var _program$docblock;
const docblockComment = (_program$docblock = program.docblock) == null ? void 0 : _program$docblock.comment;
if (docblockComment != null) {
return '/*' + docblockComment.value + '*/\n';
}
return '';
}
const codeForPrinting = (0, _comments.mutateESTreeASTCommentsForPrettier)(program, originalCode);
(0, _mutateESTreeASTForPrettier.default)(program, visitorKeys);
let pluginParserName = 'flow';
let pluginParser;
let pluginPrinter;
try {
const prettierHermesPlugin = await Promise.resolve().then(() => _interopRequireWildcard(require('prettier-plugin-hermes-parser')));
pluginParser = prettierHermesPlugin.parsers.hermes;
pluginPrinter = prettierHermesPlugin.printers;
pluginParserName = 'hermes';
} catch {
const prettierFlowPlugin = require('prettier/plugins/flow');
pluginParser = prettierFlowPlugin.parsers.flow;
}
return prettier.format(codeForPrinting, { ...prettierOptions,
parser: pluginParserName,
requirePragma: false,
plugins: [{
parsers: {
[pluginParserName]: { ...pluginParser,
parse() {
return program;
}
}
},
printers: pluginPrinter
}]
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SimpleTransform = void 0;
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _astNodeMutationHelpers = require("./astNodeMutationHelpers");
function setParentPointer(node, parent) {
if (parent != null) {
if (Array.isArray(node)) {
for (const item of node) {
item.parent = parent;
}
} else {
node.parent = parent;
}
}
}
class SimpleTransform {
transform(rootNode, options) {
let resultRootNode = rootNode;
_SimpleTraverser.SimpleTraverser.traverse(rootNode, {
enter: (node, parent) => {
setParentPointer(node, parent);
const resultNode = options.transform(node);
if (resultNode !== node) {
let traversedResultNode = null;
if (resultNode != null) {
setParentPointer(resultNode, parent);
if (Array.isArray(resultNode)) {
traversedResultNode = resultNode.map(item => this.transform(item, options)).filter(item => item != null);
} else {
traversedResultNode = this.transform(resultNode, options);
}
}
if (parent == null) {
if (node !== rootNode) {
throw new Error('SimpleTransform infra error: Parent not set on non root node, this should not be possible');
}
if (Array.isArray(traversedResultNode)) {
throw new Error('SimpleTransform: invalid array result for root node');
} else {
resultRootNode = traversedResultNode;
}
} else if (traversedResultNode == null) {
(0, _astNodeMutationHelpers.removeNodeOnParent)(node, parent, options.visitorKeys);
} else {
(0, _astNodeMutationHelpers.replaceNodeOnParent)(node, parent, traversedResultNode, options.visitorKeys);
setParentPointer(traversedResultNode, parent);
}
throw _SimpleTraverser.SimpleTraverser.Skip;
}
},
leave(_node) {},
visitorKeys: options.visitorKeys
});
return resultRootNode;
}
static transform(node, options) {
return new SimpleTransform().transform(node, options);
}
static transformProgram(program, options) {
const result = SimpleTransform.transform(program, options);
if ((result == null ? void 0 : result.type) === 'Program') {
return result;
}
throw new Error('SimpleTransform.transformProgram: Expected program node.');
}
static nodeWith(node, overrideProps, visitorKeys) {
return (0, _astNodeMutationHelpers.nodeWith)(node, overrideProps, visitorKeys);
}
}
exports.SimpleTransform = SimpleTransform;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getVisitorKeys = getVisitorKeys;
exports.isNode = isNode;
var _ESTreeVisitorKeys = _interopRequireDefault(require("../generated/ESTreeVisitorKeys"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isNode(thing) {
return typeof thing === 'object' && thing != null && typeof thing.type === 'string';
}
function getVisitorKeys(node, visitorKeys) {
const keys = (visitorKeys != null ? visitorKeys : _ESTreeVisitorKeys.default)[node.type];
if (keys == null) {
throw new Error(`No visitor keys found for node type "${node.type}".`);
}
return keys;
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SimpleTraverserSkip = exports.SimpleTraverserBreak = exports.SimpleTraverser = void 0;
var _getVisitorKeys = require("./getVisitorKeys");
const SimpleTraverserSkip = new Error();
exports.SimpleTraverserSkip = SimpleTraverserSkip;
const SimpleTraverserBreak = new Error();
exports.SimpleTraverserBreak = SimpleTraverserBreak;
class SimpleTraverser {
traverse(node, options) {
try {
this._traverse(node, null, options);
} catch (ex) {
if (ex === SimpleTraverserBreak) {
return;
}
throw ex;
}
}
_traverse(node, parent, options) {
if (!(0, _getVisitorKeys.isNode)(node)) {
return;
}
try {
options.enter(node, parent);
} catch (ex) {
if (ex === SimpleTraverserSkip) {
return;
}
this._setErrorContext(ex, node);
throw ex;
}
const keys = (0, _getVisitorKeys.getVisitorKeys)(node, options.visitorKeys);
for (const key of keys) {
const lookupKey = key;
const childAny = node[lookupKey];
const child = childAny;
if (Array.isArray(child)) {
for (let j = 0; j < child.length; ++j) {
this._traverse(child[j], node, options);
}
} else {
this._traverse(child, node, options);
}
}
try {
options.leave(node, parent);
} catch (ex) {
if (ex === SimpleTraverserSkip) {
return;
}
this._setErrorContext(ex, node);
throw ex;
}
}
_setErrorContext(ex, node) {
ex.currentNode = {
type: node.type,
range: node.range,
loc: node.loc
};
}
static traverse(node, options) {
new SimpleTraverser().traverse(node, options);
}
}
exports.SimpleTraverser = SimpleTraverser;
SimpleTraverser.Break = SimpleTraverserBreak;
SimpleTraverser.Skip = SimpleTraverserSkip;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EMPTY_PARENT = void 0;
exports.callExpression = callExpression;
exports.conjunction = conjunction;
exports.createDefaultPosition = createDefaultPosition;
exports.disjunction = disjunction;
exports.etc = etc;
exports.ident = ident;
exports.iife = iife;
exports.nullLiteral = nullLiteral;
exports.numberLiteral = numberLiteral;
exports.stringLiteral = stringLiteral;
exports.throwStatement = throwStatement;
exports.typeofExpression = typeofExpression;
exports.variableDeclaration = variableDeclaration;
const EMPTY_PARENT = null;
exports.EMPTY_PARENT = EMPTY_PARENT;
function createDefaultPosition() {
return {
line: 1,
column: 0
};
}
function etc({
loc,
range,
parent
} = {}) {
return {
loc: {
start: (loc == null ? void 0 : loc.start) != null ? loc.start : createDefaultPosition(),
end: (loc == null ? void 0 : loc.end) != null ? loc.end : createDefaultPosition()
},
range: range != null ? range : [0, 0],
parent: parent != null ? parent : EMPTY_PARENT
};
}
function ident(name, info) {
return {
type: 'Identifier',
name,
optional: false,
typeAnnotation: null,
...etc(info)
};
}
function stringLiteral(value, info) {
return {
type: 'Literal',
value,
raw: `"${value}"`,
literalType: 'string',
...etc(info)
};
}
function numberLiteral(value, info) {
return {
type: 'Literal',
value,
raw: String(value),
literalType: 'numeric',
...etc(info)
};
}
function nullLiteral(info) {
return {
type: 'Literal',
value: null,
raw: 'null',
literalType: 'null',
...etc(info)
};
}
function conjunction(tests) {
if (tests.length === 0) {
throw new Error('Must have at least one test.');
}
return tests.reduce((acc, test) => ({
type: 'LogicalExpression',
left: acc,
right: test,
operator: '&&',
...etc()
}));
}
function disjunction(tests) {
if (tests.length === 0) {
throw new Error('Must have at least one test.');
}
return tests.reduce((acc, test) => ({
type: 'LogicalExpression',
left: acc,
right: test,
operator: '||',
...etc()
}));
}
function variableDeclaration(kind, id, init, info) {
return {
type: 'VariableDeclaration',
kind,
declarations: [{
type: 'VariableDeclarator',
init,
id,
...etc(),
parent: EMPTY_PARENT
}],
...etc(info)
};
}
function callExpression(callee, args, info) {
return {
type: 'CallExpression',
callee,
arguments: args,
typeArguments: null,
optional: false,
...etc(info)
};
}
function throwStatement(arg, info) {
return {
type: 'ThrowStatement',
argument: callExpression(ident('Error'), [arg]),
...etc(info)
};
}
function iife(statements, params = [], args = []) {
const callee = {
type: 'ArrowFunctionExpression',
params,
expression: false,
async: false,
predicate: null,
returnType: null,
typeParameters: null,
id: null,
body: {
type: 'BlockStatement',
body: statements,
...etc()
},
...etc()
};
return callExpression(callee, args);
}
function typeofExpression(arg, kind) {
return {
type: 'BinaryExpression',
left: {
type: 'UnaryExpression',
operator: 'typeof',
argument: arg,
prefix: true,
...etc()
},
right: stringLiteral(kind),
operator: '===',
...etc()
};
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSyntaxError = createSyntaxError;
function createSyntaxError(node, err) {
const syntaxError = new SyntaxError(err);
syntaxError.loc = {
line: node.loc.start.line,
column: node.loc.start.column
};
return syntaxError;
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const genPrefix = '$$gen$';
class GenID {
constructor(uniqueTransformPrefix) {
this.genN = 0;
this.used = new Set();
this.prefix = void 0;
this.prefix = `${genPrefix}${uniqueTransformPrefix}`;
}
id() {
let name;
do {
name = `${this.prefix}${this.genN}`;
this.genN++;
} while (this.used.has(name));
this.used.add(name);
return name;
}
addUsage(name) {
if (name.startsWith(this.prefix)) {
this.used.add(name);
}
}
}
exports.default = GenID;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isReservedWord;
function isReservedWord(name) {
switch (name) {
case 'await':
case 'break':
case 'case':
case 'catch':
case 'class':
case 'const':
case 'continue':
case 'debugger':
case 'default':
case 'delete':
case 'do':
case 'else':
case 'enum':
case 'export':
case 'extends':
case 'false':
case 'finally':
case 'for':
case 'function':
case 'if':
case 'import':
case 'in':
case 'instanceof':
case 'new':
case 'null':
case 'return':
case 'super':
case 'switch':
case 'this':
case 'throw':
case 'true':
case 'try':
case 'typeof':
case 'var':
case 'void':
case 'while':
case 'with':
case 'yield':
return true;
default:
return false;
}
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mutate;
var _SimpleTransform = require("../transform/SimpleTransform");
function transformChainExpression(node, comments) {
if (comments != null) {
var _node$comments;
const joinedComments = comments.concat((_node$comments = node.comments) != null ? _node$comments : []);
node.comments = joinedComments;
}
switch (node.type) {
case 'CallExpression':
return { ...node,
type: 'OptionalCallExpression',
callee: transformChainExpression(node.callee)
};
case 'MemberExpression':
return { ...node,
type: 'OptionalMemberExpression',
object: transformChainExpression(node.object)
};
}
return node;
}
function mutate(rootNode, visitorKeys) {
_SimpleTransform.SimpleTransform.transform(rootNode, {
transform(node) {
if (node.parent) {
delete node.parent;
}
if (node.type === 'ChainExpression') {
return transformChainExpression(node.expression, node == null ? void 0 : node.comments);
}
if (node.type === 'ObjectTypeProperty') {
if (node.method === false && node.kind === 'init' && node.range[0] === 1 && node.value.range[0] === 1) {
node.value = { ...node.value,
range: [2, node.value.range[1]]
};
}
return node;
}
if (node.type === 'ImportSpecifier') {
if (node.local.name === node.imported.name) {
if (node.local.range == null) {
node.local.range = [0, 0];
}
node.imported.range = [...node.local.range];
}
return node;
}
if (node.type === 'ExportSpecifier') {
if (node.local.name === node.exported.name) {
if (node.local.range == null) {
node.local.range = [0, 0];
}
node.exported.range = [...node.local.range];
}
return node;
}
return node;
},
visitorKeys
});
}
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ParserOptionsKeys = void 0;
const ParserOptionsKeys = new Set(['allowReturnOutsideFunction', 'assertOperator', 'babel', 'flow', 'enableExperimentalComponentSyntax', 'enableExperimentalFlowMatchSyntax', 'enableExperimentalFlowRecordSyntax', 'reactRuntimeTarget', 'sourceFilename', 'sourceType', 'throwOnParseErrors', 'tokens', 'transformOptions']);
exports.ParserOptionsKeys = ParserOptionsKeys;

Sorry, the diff of this file is not supported yet

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrayIsEqual = arrayIsEqual;
exports.insertInArray = insertInArray;
exports.removeFromArray = removeFromArray;
exports.replaceInArray = replaceInArray;
function assertArrayBounds(array, index) {
if (index < 0 || index >= array.length) {
throw new Error(`Invalid Mutation: Tried to mutate an elements array with an out of bounds index. Index: ${index}, Array Size: ${array.length}`);
}
}
function arrayIsEqual(a1, a2) {
if (a1 === a2) {
return true;
}
if (a1.length !== a2.length) {
return false;
}
for (let i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
function insertInArray(array, index, elements) {
if (index === array.length) {
return array.concat(elements);
}
assertArrayBounds(array, index);
return array.slice(0, index).concat(elements).concat(array.slice(index));
}
function removeFromArray(array, index) {
assertArrayBounds(array, index);
return [...array.slice(0, index), ...array.slice(index + 1)];
}
function replaceInArray(array, index, elements) {
assertArrayBounds(array, index);
return array.slice(0, index).concat(elements).concat(array.slice(index + 1));
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.deepCloneNode = deepCloneNode;
exports.nodeWith = nodeWith;
exports.removeNodeOnParent = removeNodeOnParent;
exports.replaceNodeOnParent = replaceNodeOnParent;
exports.setParentPointersInDirectChildren = setParentPointersInDirectChildren;
exports.shallowCloneNode = shallowCloneNode;
exports.updateAllParentPointers = updateAllParentPointers;
var _astArrayMutationHelpers = require("./astArrayMutationHelpers");
var _getVisitorKeys = require("../traverse/getVisitorKeys");
var _SimpleTraverser = require("../traverse/SimpleTraverser");
function getParentKey(target, parent, visitorKeys) {
if (parent == null) {
throw new Error(`Expected parent node to be set on "${target.type}"`);
}
for (const key of (0, _getVisitorKeys.getVisitorKeys)(parent, visitorKeys)) {
if ((0, _getVisitorKeys.isNode)(parent[key])) {
if (parent[key] === target) {
return {
type: 'single',
node: parent,
key
};
}
} else if (Array.isArray(parent[key])) {
for (let i = 0; i < parent[key].length; i += 1) {
const current = parent[key][i];
if (current === target) {
return {
type: 'array',
node: parent,
key,
targetIndex: i
};
}
}
}
}
throw new Error(`Expected to find the ${target.type} as a direct child of the ${parent.type}.`);
}
function replaceNodeOnParent(originalNode, originalNodeParent, nodeToReplaceWith, visitorKeys) {
const replacementParent = getParentKey(originalNode, originalNodeParent, visitorKeys);
const parent = replacementParent.node;
if (replacementParent.type === 'array') {
parent[replacementParent.key] = (0, _astArrayMutationHelpers.replaceInArray)(parent[replacementParent.key], replacementParent.targetIndex, Array.isArray(nodeToReplaceWith) ? nodeToReplaceWith : [nodeToReplaceWith]);
} else {
if (Array.isArray(nodeToReplaceWith)) {
throw new Error(`Cannot insert array into non-array parent type: ${parent.type}`);
}
parent[replacementParent.key] = nodeToReplaceWith;
}
}
function removeNodeOnParent(originalNode, originalNodeParent, visitorKeys) {
const replacementParent = getParentKey(originalNode, originalNodeParent, visitorKeys);
const parent = replacementParent.node;
if (replacementParent.type === 'array') {
parent[replacementParent.key] = (0, _astArrayMutationHelpers.removeFromArray)(parent[replacementParent.key], replacementParent.targetIndex);
} else {
parent[replacementParent.key] = null;
}
}
function setParentPointersInDirectChildren(node, visitorKeys) {
for (const key of (0, _getVisitorKeys.getVisitorKeys)(node, visitorKeys)) {
if ((0, _getVisitorKeys.isNode)(node[key])) {
node[key].parent = node;
} else if (Array.isArray(node[key])) {
for (const child of node[key]) {
child.parent = node;
}
}
}
}
function updateAllParentPointers(node, visitorKeys) {
_SimpleTraverser.SimpleTraverser.traverse(node, {
enter(node, parent) {
node.parent = parent;
},
leave() {},
visitorKeys
});
}
function nodeWith(node, overrideProps, visitorKeys) {
const willBeUnchanged = Object.entries(overrideProps).every(([key, value]) => {
const node_ = node;
if (Array.isArray(value)) {
return Array.isArray(node_[key]) ? (0, _astArrayMutationHelpers.arrayIsEqual)(node_[key], value) : false;
}
return node_[key] === value;
});
if (willBeUnchanged) {
return node;
}
const newNode = { ...node,
...overrideProps
};
setParentPointersInDirectChildren(newNode, visitorKeys);
return newNode;
}
function shallowCloneNode(node, visitorKeys) {
const newNode = { ...node
};
setParentPointersInDirectChildren(newNode, visitorKeys);
return newNode;
}
function deepCloneNode(node, visitorKeys) {
const clone = JSON.parse(JSON.stringify(node, (key, value) => {
if (key === 'parent') {
return undefined;
}
return value;
}));
updateAllParentPointers(clone, visitorKeys);
return clone;
}

Sorry, the diff of this file is not supported yet

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CommentPlacement = void 0;
exports.addComment = addComment;
exports.appendCommentToSource = appendCommentToSource;
exports.attachComments = attachComments;
exports.cloneComment = cloneComment;
exports.cloneCommentWithMarkers = cloneCommentWithMarkers;
exports.cloneCommentsToNewNode = cloneCommentsToNewNode;
exports.cloneJSDocCommentsToNewNode = cloneJSDocCommentsToNewNode;
exports.getCommentsForNode = getCommentsForNode;
exports.getLeadingCommentsForNode = getLeadingCommentsForNode;
exports.getTrailingCommentsForNode = getTrailingCommentsForNode;
exports.isAttachedComment = isAttachedComment;
exports.isLeadingComment = isLeadingComment;
exports.isTrailingComment = isTrailingComment;
exports.makeCommentOwnLine = makeCommentOwnLine;
exports.moveCommentsToNewNode = moveCommentsToNewNode;
exports.mutateESTreeASTCommentsForPrettier = mutateESTreeASTCommentsForPrettier;
exports.setCommentsOnNode = setCommentsOnNode;
var _comments = require("./prettier/main/comments");
var _loc = require("./prettier/language-js/loc");
var _printerEstree = _interopRequireDefault(require("./prettier/language-js/printer-estree"));
var _util = require("./prettier/common/util");
var _flowEstree = require("flow-estree");
var _os = require("os");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const CommentPlacement = require("flow-enums-runtime").Mirrored(["LEADING_OWN_LINE", "LEADING_INLINE", "TRAILING_OWN_LINE", "TRAILING_INLINE"]);
exports.CommentPlacement = CommentPlacement;
function attachComments(comments, ast, text) {
(0, _comments.attach)(comments, ast, text, {
locStart: _loc.locStart,
locEnd: _loc.locEnd,
printer: _printerEstree.default
});
}
function mutateESTreeASTCommentsForPrettier(program, text) {
let code = text;
delete program.comments;
if (program.docblock != null && program.docblock.comment != null) {
const docblockComment = program.docblock.comment;
const isDocblockCommentNew = !isAttachedComment(docblockComment);
if (isDocblockCommentNew) {
docblockComment.printed = false;
docblockComment.leading = true;
docblockComment.trailing = false;
}
if (program.body.length > 0) {
const firstStatement = program.body[0];
const leadingComments = getLeadingCommentsForNode(firstStatement);
if (!leadingComments.includes(docblockComment)) {
setCommentsOnNode(firstStatement, [docblockComment, ...getCommentsForNode(firstStatement)]);
if (isDocblockCommentNew) {
code = makeCommentOwnLine(code, docblockComment);
}
}
} else {
setCommentsOnNode(program, [docblockComment]);
}
}
delete program.docblock;
return code;
}
function moveCommentsToNewNode(oldNode, newNode) {
setCommentsOnNode(newNode, getCommentsForNode(oldNode));
setCommentsOnNode(oldNode, []);
}
function cloneCommentsToNewNode(oldNode, newNode) {
setCommentsOnNode(newNode, getCommentsForNode(oldNode).map(comment => cloneCommentWithMarkers(comment)));
}
function cloneJSDocCommentsToNewNode(oldNode, newNode) {
const comments = getCommentsForNode(oldNode).filter(comment => {
return (0, _flowEstree.isBlockComment)(comment) && comment.value.startsWith('*');
});
setCommentsOnNode(newNode, [...getCommentsForNode(newNode), ...comments.map(cloneCommentWithMarkers)]);
}
function setCommentsOnNode(node, comments) {
node.comments = comments;
}
function getCommentsForNode(node) {
var _node$comments;
return (_node$comments = node.comments) != null ? _node$comments : [];
}
function isAttachedComment(comment) {
return comment.printed === false;
}
function isLeadingComment(comment) {
return comment.leading === true;
}
function isTrailingComment(comment) {
return comment.trailing === true;
}
function getLeadingCommentsForNode(node) {
return getCommentsForNode(node).filter(isLeadingComment);
}
function getTrailingCommentsForNode(node) {
return getCommentsForNode(node).filter(isTrailingComment);
}
function addComment(node, comment, placement) {
switch (placement) {
case CommentPlacement.LEADING_OWN_LINE:
case CommentPlacement.LEADING_INLINE:
{
(0, _util.addLeadingComment)(node, comment);
break;
}
case CommentPlacement.TRAILING_OWN_LINE:
case CommentPlacement.TRAILING_INLINE:
{
(0, _util.addTrailingComment)(node, comment);
break;
}
}
}
function cloneComment(comment) {
return {
type: comment.type,
value: comment.value,
loc: comment.loc,
range: comment.range
};
}
function cloneCommentWithMarkers(comment) {
return {
type: comment.type,
value: comment.value,
loc: comment.loc,
range: comment.range,
leading: isLeadingComment(comment),
trailing: isTrailingComment(comment)
};
}
function getFirstNewlineIndex(code) {
return code.search(/\r\n|\n|\r/);
}
function getFirstNonWhitespaceIndex(code) {
return code.search(/\S/);
}
function makeCommentOwnLine(code, comment) {
let newCode = code;
let firstNewline = getFirstNewlineIndex(code);
if (firstNewline === -1) {
newCode += _os.EOL;
firstNewline = newCode.length;
}
comment.range = [firstNewline + 1, firstNewline];
return newCode;
}
function appendCommentToSource(code, comment, placement) {
let newCode = code;
switch (comment.type) {
case 'Block':
{
switch (placement) {
case CommentPlacement.LEADING_OWN_LINE:
case CommentPlacement.TRAILING_OWN_LINE:
{
newCode = makeCommentOwnLine(code, comment);
break;
}
case CommentPlacement.LEADING_INLINE:
case CommentPlacement.TRAILING_INLINE:
{
let firstNonWhitespace = getFirstNonWhitespaceIndex(code);
if (firstNonWhitespace === -1) {
newCode += '$FORCE_INLINE_ON_EMPTY_FILE_TOKEN$;';
firstNonWhitespace = newCode.length;
break;
}
comment.range = [firstNonWhitespace + 1, firstNonWhitespace];
break;
}
}
break;
}
case 'Line':
{
const commentText = `//${comment.value}`;
const lastChar = newCode[newCode.length - 1];
if (lastChar !== '\n' && lastChar !== '\r') {
newCode += _os.EOL;
}
if (placement === CommentPlacement.TRAILING_INLINE) {
newCode += '$FORCE_END_OF_LINE_COMMENT_TOKEN$;';
}
const start = newCode.length;
newCode += commentText;
const end = newCode.length;
comment.range = [start, end];
break;
}
}
return newCode;
}

Sorry, the diff of this file is not supported yet

'use strict';
const stringWidth = require('string-width');
const getLast = require('../utils/get-last.js');
const notAsciiRegex = /[^\x20-\x7F]/;
function skip(chars) {
return (text, index, opts) => {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const {
length
} = text;
let cursor = index;
while (cursor >= 0 && cursor < length) {
const c = text.charAt(cursor);
if (chars instanceof RegExp) {
if (!chars.test(c)) {
return cursor;
}
} else if (!chars.includes(c)) {
return cursor;
}
backwards ? cursor-- : cursor++;
}
if (cursor === -1 || cursor === length) {
return cursor;
}
return false;
};
}
const skipWhitespace = skip(/\s/);
const skipSpaces = skip(' \t');
const skipToLineEnd = skip(',; \t');
const skipEverythingButNewLine = skip(/[^\n\r]/);
function skipInlineComment(text, index) {
if (index === false) {
return false;
}
if (text.charAt(index) === '/' && text.charAt(index + 1) === '*') {
for (let i = index + 2; i < text.length; ++i) {
if (text.charAt(i) === '*' && text.charAt(i + 1) === '/') {
return i + 2;
}
}
}
return index;
}
function skipTrailingComment(text, index) {
if (index === false) {
return false;
}
if (text.charAt(index) === '/' && text.charAt(index + 1) === '/') {
return skipEverythingButNewLine(text, index);
}
return index;
}
function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const atIndex = text.charAt(index);
if (backwards) {
if (text.charAt(index - 1) === '\r' && atIndex === '\n') {
return index - 2;
}
if (atIndex === '\n' || atIndex === '\r' || atIndex === '\u2028' || atIndex === '\u2029') {
return index - 1;
}
} else {
if (atIndex === '\r' && text.charAt(index + 1) === '\n') {
return index + 2;
}
if (atIndex === '\n' || atIndex === '\r' || atIndex === '\u2028' || atIndex === '\u2029') {
return index + 1;
}
}
return index;
}
function hasNewline(text, index, opts = {}) {
const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
const idx2 = skipNewline(text, idx, opts);
return idx !== idx2;
}
function hasNewlineInRange(text, start, end) {
for (let i = start; i < end; ++i) {
if (text.charAt(i) === '\n') {
return true;
}
}
return false;
}
function isNextLineEmptyAfterIndex(text, index) {
let oldIdx = null;
let idx = index;
while (idx !== oldIdx) {
oldIdx = idx;
idx = skipToLineEnd(text, idx);
idx = skipInlineComment(text, idx);
idx = skipSpaces(text, idx);
}
idx = skipTrailingComment(text, idx);
idx = skipNewline(text, idx);
return idx !== false && hasNewline(text, idx);
}
function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
let oldIdx = null;
let nextIdx = idx;
while (nextIdx !== oldIdx) {
oldIdx = nextIdx;
nextIdx = skipSpaces(text, nextIdx);
nextIdx = skipInlineComment(text, nextIdx);
nextIdx = skipTrailingComment(text, nextIdx);
nextIdx = skipNewline(text, nextIdx);
}
return nextIdx;
}
function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
}
function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
return text.charAt(getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
}
function getStringWidth(text) {
if (!text) {
return 0;
}
if (!notAsciiRegex.test(text)) {
return text.length;
}
return stringWidth(text);
}
function addCommentHelper(node, comment) {
const comments = node.comments || (node.comments = []);
comments.push(comment);
comment.printed = false;
comment.nodeDescription = describeNodeForDebugging(node);
}
function addLeadingComment(node, comment) {
comment.leading = true;
comment.trailing = false;
addCommentHelper(node, comment);
}
function addDanglingComment(node, comment, marker) {
comment.leading = false;
comment.trailing = false;
if (marker) {
comment.marker = marker;
}
addCommentHelper(node, comment);
}
function addTrailingComment(node, comment) {
comment.leading = false;
comment.trailing = true;
addCommentHelper(node, comment);
}
function isNonEmptyArray(object) {
return Array.isArray(object) && object.length > 0;
}
function describeNodeForDebugging(node) {
const nodeType = node.type || node.kind || '(unknown type)';
let nodeName = String(node.name || node.id && (typeof node.id === 'object' ? node.id.name : node.id) || node.key && (typeof node.key === 'object' ? node.key.name : node.key) || node.value && (typeof node.value === 'object' ? '' : String(node.value)) || node.operator || '');
if (nodeName.length > 20) {
nodeName = nodeName.slice(0, 19) + '…';
}
return nodeType + (nodeName ? ' ' + nodeName : '');
}
module.exports = {
getStringWidth,
getLast,
getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
getNextNonSpaceNonCommentCharacterIndex,
getNextNonSpaceNonCommentCharacter,
skipWhitespace,
skipSpaces,
skipNewline,
isNextLineEmptyAfterIndex,
hasNewline,
hasNewlineInRange,
addLeadingComment,
addDanglingComment,
addTrailingComment,
isNonEmptyArray
};
'use strict';
const {
getLast,
hasNewline,
addLeadingComment,
getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
getNextNonSpaceNonCommentCharacterIndex,
hasNewlineInRange,
addTrailingComment,
addDanglingComment,
getNextNonSpaceNonCommentCharacter,
isNonEmptyArray
} = require('../common/util.js');
const {
isBlockComment,
getFunctionParameters,
isPrettierIgnoreComment,
isCallLikeExpression,
getCallArguments,
isCallExpression,
isMemberExpression,
isObjectProperty
} = require('./utils.js');
const {
locStart,
locEnd
} = require('./loc.js');
function handleOwnLineComment(context) {
return [handleIgnoreComments, handleLastFunctionArgComments, handleMemberExpressionComments, handleIfStatementComments, handleWhileComments, handleTryStatementComments, handleClassComments, handleImportSpecifierComments, handleForComments, handleUnionTypeComments, handleMatchOrPatternComments, handleOnlyComments, handleImportDeclarationComments, handleAssignmentPatternComments, handleMethodNameComments, handleLabeledStatementComments].some(fn => fn(context));
}
function handleEndOfLineComment(context) {
return [handleClosureTypeCastComments, handleLastFunctionArgComments, handleConditionalExpressionComments, handleImportSpecifierComments, handleIfStatementComments, handleWhileComments, handleTryStatementComments, handleClassComments, handleLabeledStatementComments, handleCallExpressionComments, handlePropertyComments, handleOnlyComments, handleTypeAliasComments, handleVariableDeclaratorComments].some(fn => fn(context));
}
function handleRemainingComment(context) {
return [handleIgnoreComments, handleIfStatementComments, handleWhileComments, handleObjectPropertyAssignment, handleCommentInEmptyParens, handleMethodNameComments, handleOnlyComments, handleCommentAfterArrowParams, handleFunctionNameComments, handleTSMappedTypeComments, handleBreakAndContinueStatementComments, handleTSFunctionTrailingComments].some(fn => fn(context));
}
function addBlockStatementFirstComment(node, comment) {
const firstNonEmptyNode = (node.body || node.properties).find(({
type
}) => type !== 'EmptyStatement');
if (firstNonEmptyNode) {
addLeadingComment(firstNonEmptyNode, comment);
} else {
addDanglingComment(node, comment);
}
}
function addBlockOrNotComment(node, comment) {
if (node.type === 'BlockStatement') {
addBlockStatementFirstComment(node, comment);
} else {
addLeadingComment(node, comment);
}
}
function handleClosureTypeCastComments({
comment,
followingNode
}) {
if (followingNode && isTypeCastComment(comment)) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleIfStatementComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (!enclosingNode || enclosingNode.type !== 'IfStatement' || !followingNode) {
return false;
}
const nextCharacter = getNextNonSpaceNonCommentCharacter(text, comment, locEnd);
if (nextCharacter === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
if (precedingNode.type === 'BlockStatement') {
addTrailingComment(precedingNode, comment);
} else {
addDanglingComment(enclosingNode, comment);
}
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (followingNode.type === 'IfStatement') {
addBlockOrNotComment(followingNode.consequent, comment);
return true;
}
if (enclosingNode.consequent === followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleWhileComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (!enclosingNode || enclosingNode.type !== 'WhileStatement' || !followingNode) {
return false;
}
const nextCharacter = getNextNonSpaceNonCommentCharacter(text, comment, locEnd);
if (nextCharacter === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (enclosingNode.body === followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleTryStatementComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (!enclosingNode || enclosingNode.type !== 'TryStatement' && enclosingNode.type !== 'CatchClause' || !followingNode) {
return false;
}
if (enclosingNode.type === 'CatchClause' && precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
if (followingNode.type === 'BlockStatement') {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
if (followingNode.type === 'TryStatement') {
addBlockOrNotComment(followingNode.finalizer, comment);
return true;
}
if (followingNode.type === 'CatchClause') {
addBlockOrNotComment(followingNode.body, comment);
return true;
}
return false;
}
function handleMemberExpressionComments({
comment,
enclosingNode,
followingNode
}) {
if (isMemberExpression(enclosingNode) && followingNode && followingNode.type === 'Identifier') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleConditionalExpressionComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
const isSameLineAsPrecedingNode = precedingNode && !hasNewlineInRange(text, locEnd(precedingNode), locStart(comment));
if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && (enclosingNode.type === 'ConditionalExpression' || enclosingNode.type === 'TSConditionalType') && followingNode) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleObjectPropertyAssignment({
comment,
precedingNode,
enclosingNode
}) {
if (isObjectProperty(enclosingNode) && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === 'AssignmentPattern') {
addTrailingComment(enclosingNode.value.left, comment);
return true;
}
return false;
}
function handleClassComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ClassDeclaration' || enclosingNode.type === 'ClassExpression' || enclosingNode.type === 'DeclareClass' || enclosingNode.type === 'DeclareInterface' || enclosingNode.type === 'InterfaceDeclaration' || enclosingNode.type === 'TSInterfaceDeclaration')) {
if (isNonEmptyArray(enclosingNode.decorators) && !(followingNode && followingNode.type === 'Decorator')) {
addTrailingComment(getLast(enclosingNode.decorators), comment);
return true;
}
if (enclosingNode.body && followingNode === enclosingNode.body) {
addBlockStatementFirstComment(enclosingNode.body, comment);
return true;
}
if (followingNode) {
for (const prop of ['implements', 'extends', 'mixins']) {
if (enclosingNode[prop] && followingNode === enclosingNode[prop][0]) {
if (precedingNode && (precedingNode === enclosingNode.id || precedingNode === enclosingNode.typeParameters || precedingNode === enclosingNode.superClass)) {
addTrailingComment(precedingNode, comment);
} else {
addDanglingComment(enclosingNode, comment, prop);
}
return true;
}
}
}
}
return false;
}
function handleMethodNameComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (enclosingNode && precedingNode && (enclosingNode.type === 'Property' || enclosingNode.type === 'TSDeclareMethod' || enclosingNode.type === 'TSAbstractMethodDefinition') && precedingNode.type === 'Identifier' && enclosingNode.key === precedingNode && getNextNonSpaceNonCommentCharacter(text, precedingNode, locEnd) !== ':') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode && enclosingNode && precedingNode.type === 'Decorator' && (enclosingNode.type === 'ClassMethod' || enclosingNode.type === 'ClassProperty' || enclosingNode.type === 'PropertyDefinition' || enclosingNode.type === 'TSAbstractPropertyDefinition' || enclosingNode.type === 'TSAbstractMethodDefinition' || enclosingNode.type === 'TSDeclareMethod' || enclosingNode.type === 'MethodDefinition')) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleFunctionNameComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (getNextNonSpaceNonCommentCharacter(text, comment, locEnd) !== '(') {
return false;
}
if (precedingNode && enclosingNode && (enclosingNode.type === 'FunctionDeclaration' || enclosingNode.type === 'FunctionExpression' || enclosingNode.type === 'ClassMethod' || enclosingNode.type === 'MethodDefinition' || enclosingNode.type === 'ObjectMethod')) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleCommentAfterArrowParams({
comment,
enclosingNode,
text
}) {
if (!(enclosingNode && enclosingNode.type === 'ArrowFunctionExpression')) {
return false;
}
const index = getNextNonSpaceNonCommentCharacterIndex(text, comment, locEnd);
if (index !== false && text.slice(index, index + 2) === '=>') {
addDanglingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleCommentInEmptyParens({
comment,
enclosingNode,
text
}) {
if (getNextNonSpaceNonCommentCharacter(text, comment, locEnd) !== ')') {
return false;
}
if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && getFunctionParameters(enclosingNode).length === 0 || isCallLikeExpression(enclosingNode) && getCallArguments(enclosingNode).length === 0)) {
addDanglingComment(enclosingNode, comment);
return true;
}
if (enclosingNode && (enclosingNode.type === 'MethodDefinition' || enclosingNode.type === 'TSAbstractMethodDefinition') && getFunctionParameters(enclosingNode.value).length === 0) {
addDanglingComment(enclosingNode.value, comment);
return true;
}
return false;
}
function handleLastFunctionArgComments({
comment,
precedingNode,
enclosingNode,
followingNode,
text
}) {
if (precedingNode && precedingNode.type === 'FunctionTypeParam' && enclosingNode && enclosingNode.type === 'FunctionTypeAnnotation' && followingNode && followingNode.type !== 'FunctionTypeParam') {
addTrailingComment(precedingNode, comment);
return true;
}
if (precedingNode && (precedingNode.type === 'Identifier' || precedingNode.type === 'AssignmentPattern') && enclosingNode && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === ')') {
addTrailingComment(precedingNode, comment);
return true;
}
if (enclosingNode && enclosingNode.type === 'FunctionDeclaration' && followingNode && followingNode.type === 'BlockStatement') {
const functionParamRightParenIndex = (() => {
const parameters = getFunctionParameters(enclosingNode);
if (parameters.length > 0) {
return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(getLast(parameters)));
}
const functionParamLeftParenIndex = getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(enclosingNode.id));
return functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
})();
if (locStart(comment) > functionParamRightParenIndex) {
addBlockStatementFirstComment(followingNode, comment);
return true;
}
}
return false;
}
function handleImportSpecifierComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'ImportSpecifier') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleLabeledStatementComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'LabeledStatement') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleBreakAndContinueStatementComments({
comment,
enclosingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ContinueStatement' || enclosingNode.type === 'BreakStatement') && !enclosingNode.label) {
addTrailingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleCallExpressionComments({
comment,
precedingNode,
enclosingNode
}) {
if (isCallExpression(enclosingNode) && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
addLeadingComment(enclosingNode.arguments[0], comment);
return true;
}
return false;
}
function handleUnionTypeComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'UnionTypeAnnotation' || enclosingNode.type === 'TSUnionType')) {
if (isPrettierIgnoreComment(comment)) {
followingNode.prettierIgnore = true;
comment.unignore = true;
}
if (precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
if (followingNode && (followingNode.type === 'UnionTypeAnnotation' || followingNode.type === 'TSUnionType') && isPrettierIgnoreComment(comment)) {
followingNode.types[0].prettierIgnore = true;
comment.unignore = true;
}
return false;
}
function handleMatchOrPatternComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (enclosingNode && enclosingNode.type === 'MatchOrPattern') {
if (isPrettierIgnoreComment(comment)) {
followingNode.prettierIgnore = true;
comment.unignore = true;
}
if (precedingNode) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
if (followingNode && followingNode.type === 'MatchOrPattern' && isPrettierIgnoreComment(comment)) {
followingNode.types[0].prettierIgnore = true;
comment.unignore = true;
}
return false;
}
function handlePropertyComments({
comment,
enclosingNode
}) {
if (isObjectProperty(enclosingNode)) {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleOnlyComments({
comment,
enclosingNode,
followingNode,
ast,
isLastComment
}) {
if (ast && ast.body && ast.body.length === 0) {
if (isLastComment) {
addDanglingComment(ast, comment);
} else {
addLeadingComment(ast, comment);
}
return true;
}
if (enclosingNode && enclosingNode.type === 'Program' && enclosingNode.body.length === 0 && !isNonEmptyArray(enclosingNode.directives)) {
if (isLastComment) {
addDanglingComment(enclosingNode, comment);
} else {
addLeadingComment(enclosingNode, comment);
}
return true;
}
if (followingNode && followingNode.type === 'Program' && followingNode.body.length === 0 && enclosingNode && enclosingNode.type === 'ModuleExpression') {
addDanglingComment(followingNode, comment);
return true;
}
return false;
}
function handleForComments({
comment,
enclosingNode
}) {
if (enclosingNode && (enclosingNode.type === 'ForInStatement' || enclosingNode.type === 'ForOfStatement')) {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleImportDeclarationComments({
comment,
precedingNode,
enclosingNode,
text
}) {
if (precedingNode && precedingNode.type === 'ImportSpecifier' && enclosingNode && enclosingNode.type === 'ImportDeclaration' && hasNewline(text, locEnd(comment))) {
addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
function handleAssignmentPatternComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'AssignmentPattern') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleTypeAliasComments({
comment,
enclosingNode
}) {
if (enclosingNode && enclosingNode.type === 'TypeAlias') {
addLeadingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleVariableDeclaratorComments({
comment,
enclosingNode,
followingNode
}) {
if (enclosingNode && (enclosingNode.type === 'VariableDeclarator' || enclosingNode.type === 'AssignmentExpression') && followingNode && (followingNode.type === 'ObjectExpression' || followingNode.type === 'ArrayExpression' || followingNode.type === 'TemplateLiteral' || followingNode.type === 'TaggedTemplateExpression' || isBlockComment(comment))) {
addLeadingComment(followingNode, comment);
return true;
}
return false;
}
function handleTSFunctionTrailingComments({
comment,
enclosingNode,
followingNode,
text
}) {
if (!followingNode && enclosingNode && (enclosingNode.type === 'TSMethodSignature' || enclosingNode.type === 'TSDeclareFunction' || enclosingNode.type === 'TSAbstractMethodDefinition') && getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === ';') {
addTrailingComment(enclosingNode, comment);
return true;
}
return false;
}
function handleIgnoreComments({
comment,
enclosingNode,
followingNode
}) {
if (isPrettierIgnoreComment(comment) && enclosingNode && enclosingNode.type === 'TSMappedType' && followingNode && followingNode.type === 'TSTypeParameter' && followingNode.constraint) {
enclosingNode.prettierIgnore = true;
comment.unignore = true;
return true;
}
}
function handleTSMappedTypeComments({
comment,
precedingNode,
enclosingNode,
followingNode
}) {
if (!enclosingNode || enclosingNode.type !== 'TSMappedType') {
return false;
}
if (followingNode && followingNode.type === 'TSTypeParameter' && followingNode.name) {
addLeadingComment(followingNode.name, comment);
return true;
}
if (precedingNode && precedingNode.type === 'TSTypeParameter' && precedingNode.constraint) {
addTrailingComment(precedingNode.constraint, comment);
return true;
}
return false;
}
function isRealFunctionLikeNode(node) {
return node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ObjectMethod' || node.type === 'ClassMethod' || node.type === 'TSDeclareFunction' || node.type === 'TSCallSignatureDeclaration' || node.type === 'TSConstructSignatureDeclaration' || node.type === 'TSMethodSignature' || node.type === 'TSConstructorType' || node.type === 'TSFunctionType' || node.type === 'TSDeclareMethod';
}
function getCommentChildNodes(node, options) {
if ((options.parser === 'typescript' || options.parser === 'flow' || options.parser === 'espree' || options.parser === 'meriyah' || options.parser === '__babel_estree') && node.type === 'MethodDefinition' && node.value && node.value.type === 'FunctionExpression' && getFunctionParameters(node.value).length === 0 && !node.value.returnType && !isNonEmptyArray(node.value.typeParameters) && node.value.body) {
return [...(node.decorators || []), node.key, node.value.body];
}
}
function isTypeCastComment(comment) {
return isBlockComment(comment) && comment.value[0] === '*' && /@type\b/.test(comment.value);
}
module.exports = {
handleOwnLineComment,
handleEndOfLineComment,
handleRemainingComment,
getCommentChildNodes
};
'use strict';
const {
isNonEmptyArray
} = require('../common/util.js');
function locStart(node, opts) {
const {
ignoreDecorators
} = opts || {};
if (!ignoreDecorators) {
const decorators = node.declaration && node.declaration.decorators || node.decorators;
if (isNonEmptyArray(decorators)) {
return locStart(decorators[0]);
}
}
return node.range ? node.range[0] : node.start;
}
function locEnd(node) {
return node.range ? node.range[1] : node.end;
}
module.exports = {
locStart,
locEnd
};
'use strict';
const handleComments = require('./comments.js');
const {
isBlockComment,
isLineComment
} = require('./utils.js');
function canAttachComment(node) {
return node.type && !isBlockComment(node) && !isLineComment(node) && node.type !== 'EmptyStatement' && node.type !== 'TemplateElement' && node.type !== 'Import' && node.type !== 'TSEmptyBodyFunctionExpression';
}
module.exports = {
canAttachComment,
handleComments: {
avoidAstMutation: true,
ownLine: handleComments.handleOwnLineComment,
endOfLine: handleComments.handleEndOfLineComment,
remaining: handleComments.handleRemainingComment
},
getCommentChildNodes: handleComments.getCommentChildNodes
};
'use strict';
function isBlockComment(comment) {
return comment.type === 'Block' || comment.type === 'CommentBlock' || comment.type === 'MultiLine';
}
function isLineComment(comment) {
return comment.type === 'Line' || comment.type === 'CommentLine' || comment.type === 'SingleLine' || comment.type === 'HashbangComment' || comment.type === 'HTMLOpen' || comment.type === 'HTMLClose';
}
function isCallExpression(node) {
return node && (node.type === 'CallExpression' || node.type === 'OptionalCallExpression');
}
function isMemberExpression(node) {
return node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression');
}
const functionParametersCache = new WeakMap();
function getFunctionParameters(node) {
if (functionParametersCache.has(node)) {
return functionParametersCache.get(node);
}
const parameters = [];
if (node.this) {
parameters.push(node.this);
}
if (Array.isArray(node.parameters)) {
parameters.push(...node.parameters);
} else if (Array.isArray(node.params)) {
parameters.push(...node.params);
}
if (node.rest) {
parameters.push(node.rest);
}
functionParametersCache.set(node, parameters);
return parameters;
}
const callArgumentsCache = new WeakMap();
function getCallArguments(node) {
if (callArgumentsCache.has(node)) {
return callArgumentsCache.get(node);
}
let args = node.arguments;
if (node.type === 'ImportExpression') {
args = [node.source];
if (node.attributes) {
args.push(node.attributes);
}
}
callArgumentsCache.set(node, args);
return args;
}
function isPrettierIgnoreComment(comment) {
return comment.value.trim() === 'prettier-ignore' && !comment.unignore;
}
function isCallLikeExpression(node) {
return isCallExpression(node) || node.type === 'NewExpression' || node.type === 'ImportExpression';
}
function isObjectProperty(node) {
return node && (node.type === 'ObjectProperty' || node.type === 'Property' && !node.method && node.kind === 'init');
}
module.exports = {
getFunctionParameters,
getCallArguments,
isBlockComment,
isCallLikeExpression,
isLineComment,
isPrettierIgnoreComment,
isCallExpression,
isMemberExpression,
isObjectProperty
};
'use strict';
const assert = require('assert');
const {
hasNewline,
addLeadingComment,
addDanglingComment,
addTrailingComment
} = require('../common/util.js');
const childNodesCache = new WeakMap();
function getSortedChildNodes(node, options, resultArray) {
if (!node) {
return;
}
const {
printer,
locStart,
locEnd
} = options;
if (resultArray) {
if (printer.canAttachComment && printer.canAttachComment(node)) {
let i;
for (i = resultArray.length - 1; i >= 0; --i) {
if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
break;
}
}
resultArray.splice(i + 1, 0, node);
return;
}
} else if (childNodesCache.has(node)) {
return childNodesCache.get(node);
}
const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === 'object' && Object.entries(node).filter(([key]) => key !== 'enclosingNode' && key !== 'precedingNode' && key !== 'followingNode' && key !== 'tokens' && key !== 'comments' && key !== 'parent').map(([, value]) => value);
if (!childNodes) {
return;
}
if (!resultArray) {
resultArray = [];
childNodesCache.set(node, resultArray);
}
for (const childNode of childNodes) {
getSortedChildNodes(childNode, options, resultArray);
}
return resultArray;
}
function decorateComment(node, comment, options, enclosingNode) {
const {
locStart,
locEnd
} = options;
const commentStart = locStart(comment);
const commentEnd = locEnd(comment);
const childNodes = getSortedChildNodes(node, options);
let precedingNode;
let followingNode;
let left = 0;
let right = childNodes.length;
while (left < right) {
const middle = left + right >> 1;
const child = childNodes[middle];
const start = locStart(child);
const end = locEnd(child);
if (start <= commentStart && commentEnd <= end) {
return decorateComment(child, comment, options, child);
}
if (end <= commentStart) {
precedingNode = child;
left = middle + 1;
continue;
}
if (commentEnd <= start) {
followingNode = child;
right = middle;
continue;
}
throw new Error('Comment location overlaps with node location');
}
if (enclosingNode && enclosingNode.type === 'TemplateLiteral') {
const {
quasis
} = enclosingNode;
const commentIndex = findExpressionIndexForComment(quasis, comment, options);
if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
precedingNode = null;
}
if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
followingNode = null;
}
}
return {
enclosingNode,
precedingNode,
followingNode
};
}
const returnFalse = () => false;
function attach(comments, ast, text, options) {
if (!Array.isArray(comments)) {
return;
}
const tiesToBreak = [];
const {
locStart,
locEnd,
printer: {
handleComments = {}
}
} = options;
const {
avoidAstMutation,
ownLine: handleOwnLineComment = returnFalse,
endOfLine: handleEndOfLineComment = returnFalse,
remaining: handleRemainingComment = returnFalse
} = handleComments;
const decoratedComments = comments.map((comment, index) => ({ ...decorateComment(ast, comment, options),
comment,
text,
options,
ast,
isLastComment: comments.length - 1 === index
}));
for (const [index, context] of decoratedComments.entries()) {
const {
comment,
precedingNode,
enclosingNode,
followingNode,
text,
options,
ast,
isLastComment
} = context;
if (options.parser === 'json' || options.parser === 'json5' || options.parser === '__js_expression' || options.parser === '__vue_expression') {
if (locStart(comment) - locStart(ast) <= 0) {
addLeadingComment(ast, comment);
continue;
}
if (locEnd(comment) - locEnd(ast) >= 0) {
addTrailingComment(ast, comment);
continue;
}
}
let args;
if (avoidAstMutation) {
args = [context];
} else {
comment.enclosingNode = enclosingNode;
comment.precedingNode = precedingNode;
comment.followingNode = followingNode;
args = [comment, text, options, ast, isLastComment];
}
if (isOwnLineComment(text, options, decoratedComments, index)) {
comment.placement = 'ownLine';
if (handleOwnLineComment(...args)) {} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
} else if (isEndOfLineComment(text, options, decoratedComments, index)) {
comment.placement = 'endOfLine';
if (handleEndOfLineComment(...args)) {} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
} else {
comment.placement = 'remaining';
if (handleRemainingComment(...args)) {} else if (precedingNode && followingNode) {
const tieCount = tiesToBreak.length;
if (tieCount > 0) {
const lastTie = tiesToBreak[tieCount - 1];
if (lastTie.followingNode !== followingNode) {
breakTies(tiesToBreak, text, options);
}
}
tiesToBreak.push(context);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
addDanglingComment(ast, comment);
}
}
}
breakTies(tiesToBreak, text, options);
if (!avoidAstMutation) {
for (const comment of comments) {
delete comment.precedingNode;
delete comment.enclosingNode;
delete comment.followingNode;
}
}
}
const isAllEmptyAndNoLineBreak = text => !/[\S\n\u2028\u2029]/.test(text);
function isOwnLineComment(text, options, decoratedComments, commentIndex) {
const {
comment,
precedingNode
} = decoratedComments[commentIndex];
const {
locStart,
locEnd
} = options;
let start = locStart(comment);
if (precedingNode) {
for (let index = commentIndex - 1; index >= 0; index--) {
const {
comment,
precedingNode: currentCommentPrecedingNode
} = decoratedComments[index];
if (currentCommentPrecedingNode !== precedingNode || !isAllEmptyAndNoLineBreak(text.slice(locEnd(comment), start))) {
break;
}
start = locStart(comment);
}
}
return hasNewline(text, start, {
backwards: true
});
}
function isEndOfLineComment(text, options, decoratedComments, commentIndex) {
const {
comment,
followingNode
} = decoratedComments[commentIndex];
const {
locStart,
locEnd
} = options;
let end = locEnd(comment);
if (followingNode) {
for (let index = commentIndex + 1; index < decoratedComments.length; index++) {
const {
comment,
followingNode: currentCommentFollowingNode
} = decoratedComments[index];
if (currentCommentFollowingNode !== followingNode || !isAllEmptyAndNoLineBreak(text.slice(end, locStart(comment)))) {
break;
}
end = locEnd(comment);
}
}
return hasNewline(text, end);
}
function breakTies(tiesToBreak, text, options) {
const tieCount = tiesToBreak.length;
if (tieCount === 0) {
return;
}
const {
precedingNode,
followingNode,
enclosingNode
} = tiesToBreak[0];
const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
let gapEndPos = options.locStart(followingNode);
let indexOfFirstLeadingComment;
for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
const {
comment,
precedingNode: currentCommentPrecedingNode,
followingNode: currentCommentFollowingNode
} = tiesToBreak[indexOfFirstLeadingComment - 1];
assert.strictEqual(currentCommentPrecedingNode, precedingNode);
assert.strictEqual(currentCommentFollowingNode, followingNode);
const gap = text.slice(options.locEnd(comment), gapEndPos);
if (gapRegExp.test(gap)) {
gapEndPos = options.locStart(comment);
} else {
break;
}
}
for (const [i, {
comment
}] of tiesToBreak.entries()) {
if (i < indexOfFirstLeadingComment) {
addTrailingComment(precedingNode, comment);
} else {
addLeadingComment(followingNode, comment);
}
}
for (const node of [precedingNode, followingNode]) {
if (node.comments && node.comments.length > 1) {
node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
}
}
tiesToBreak.length = 0;
}
function findExpressionIndexForComment(quasis, comment, options) {
const startPos = options.locStart(comment) - 1;
for (let i = 1; i < quasis.length; ++i) {
if (startPos < options.locStart(quasis[i])) {
return i - 1;
}
}
return 0;
}
module.exports = {
attach
};
'use strict';
const getLast = arr => arr[arr.length - 1];
module.exports = getLast;

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.print = print;
var _mutateESTreeASTForPrettier = _interopRequireDefault(require("../../utils/mutateESTreeASTForPrettier"));
var prettier = _interopRequireWildcard(require("prettier"));
var _comments = require("./comments/comments");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
async function print(ast, originalCode, prettierOptions = {}, visitorKeys) {
const program = ast;
if (program.body.length === 0) {
var _program$docblock;
const docblockComment = (_program$docblock = program.docblock) == null ? void 0 : _program$docblock.comment;
if (docblockComment != null) {
return '/*' + docblockComment.value + '*/\n';
}
return '';
}
const codeForPrinting = (0, _comments.mutateESTreeASTCommentsForPrettier)(program, originalCode);
(0, _mutateESTreeASTForPrettier.default)(program, visitorKeys);
let pluginParserName = 'flow';
let pluginParser;
let pluginPrinter;
try {
const prettierHermesPlugin = await Promise.resolve().then(() => _interopRequireWildcard(require('prettier-plugin-hermes-parser')));
pluginParser = prettierHermesPlugin.parsers.hermes;
pluginPrinter = prettierHermesPlugin.printers;
pluginParserName = 'hermes';
} catch {
const prettierFlowPlugin = require('prettier/plugins/flow');
pluginParser = prettierFlowPlugin.parsers.flow;
}
return prettier.format(codeForPrinting, { ...prettierOptions,
parser: pluginParserName,
requirePragma: false,
plugins: [{
parsers: {
[pluginParserName]: { ...pluginParser,
parse() {
return program;
}
}
},
printers: pluginPrinter
}]
});
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SimpleTransform = void 0;
var _SimpleTraverser = require("../traverse/SimpleTraverser");
var _astNodeMutationHelpers = require("./astNodeMutationHelpers");
function setParentPointer(node, parent) {
if (parent != null) {
if (Array.isArray(node)) {
for (const item of node) {
item.parent = parent;
}
} else {
node.parent = parent;
}
}
}
class SimpleTransform {
transform(rootNode, options) {
let resultRootNode = rootNode;
_SimpleTraverser.SimpleTraverser.traverse(rootNode, {
enter: (node, parent) => {
setParentPointer(node, parent);
const resultNode = options.transform(node);
if (resultNode !== node) {
let traversedResultNode = null;
if (resultNode != null) {
setParentPointer(resultNode, parent);
if (Array.isArray(resultNode)) {
traversedResultNode = resultNode.map(item => this.transform(item, options)).filter(item => item != null);
} else {
traversedResultNode = this.transform(resultNode, options);
}
}
if (parent == null) {
if (node !== rootNode) {
throw new Error('SimpleTransform infra error: Parent not set on non root node, this should not be possible');
}
if (Array.isArray(traversedResultNode)) {
throw new Error('SimpleTransform: invalid array result for root node');
} else {
resultRootNode = traversedResultNode;
}
} else if (traversedResultNode == null) {
(0, _astNodeMutationHelpers.removeNodeOnParent)(node, parent, options.visitorKeys);
} else {
(0, _astNodeMutationHelpers.replaceNodeOnParent)(node, parent, traversedResultNode, options.visitorKeys);
setParentPointer(traversedResultNode, parent);
}
throw _SimpleTraverser.SimpleTraverser.Skip;
}
},
leave(_node) {},
visitorKeys: options.visitorKeys
});
return resultRootNode;
}
static transform(node, options) {
return new SimpleTransform().transform(node, options);
}
static transformProgram(program, options) {
const result = SimpleTransform.transform(program, options);
if ((result == null ? void 0 : result.type) === 'Program') {
return result;
}
throw new Error('SimpleTransform.transformProgram: Expected program node.');
}
static nodeWith(node, overrideProps, visitorKeys) {
return (0, _astNodeMutationHelpers.nodeWith)(node, overrideProps, visitorKeys);
}
}
exports.SimpleTransform = SimpleTransform;

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getVisitorKeys = getVisitorKeys;
exports.isNode = isNode;
var _ESTreeVisitorKeys = _interopRequireDefault(require("../generated/ESTreeVisitorKeys"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isNode(thing) {
return typeof thing === 'object' && thing != null && typeof thing.type === 'string';
}
function getVisitorKeys(node, visitorKeys) {
const keys = (visitorKeys != null ? visitorKeys : _ESTreeVisitorKeys.default)[node.type];
if (keys == null) {
throw new Error(`No visitor keys found for node type "${node.type}".`);
}
return keys;
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SimpleTraverserSkip = exports.SimpleTraverserBreak = exports.SimpleTraverser = void 0;
var _getVisitorKeys = require("./getVisitorKeys");
const SimpleTraverserSkip = new Error();
exports.SimpleTraverserSkip = SimpleTraverserSkip;
const SimpleTraverserBreak = new Error();
exports.SimpleTraverserBreak = SimpleTraverserBreak;
class SimpleTraverser {
traverse(node, options) {
try {
this._traverse(node, null, options);
} catch (ex) {
if (ex === SimpleTraverserBreak) {
return;
}
throw ex;
}
}
_traverse(node, parent, options) {
if (!(0, _getVisitorKeys.isNode)(node)) {
return;
}
try {
options.enter(node, parent);
} catch (ex) {
if (ex === SimpleTraverserSkip) {
return;
}
this._setErrorContext(ex, node);
throw ex;
}
const keys = (0, _getVisitorKeys.getVisitorKeys)(node, options.visitorKeys);
for (const key of keys) {
const lookupKey = key;
const childAny = node[lookupKey];
const child = childAny;
if (Array.isArray(child)) {
for (let j = 0; j < child.length; ++j) {
this._traverse(child[j], node, options);
}
} else {
this._traverse(child, node, options);
}
}
try {
options.leave(node, parent);
} catch (ex) {
if (ex === SimpleTraverserSkip) {
return;
}
this._setErrorContext(ex, node);
throw ex;
}
}
_setErrorContext(ex, node) {
ex.currentNode = {
type: node.type,
range: node.range,
loc: node.loc
};
}
static traverse(node, options) {
new SimpleTraverser().traverse(node, options);
}
}
exports.SimpleTraverser = SimpleTraverser;
SimpleTraverser.Break = SimpleTraverserBreak;
SimpleTraverser.Skip = SimpleTraverserSkip;

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EMPTY_PARENT = void 0;
exports.callExpression = callExpression;
exports.conjunction = conjunction;
exports.createDefaultPosition = createDefaultPosition;
exports.disjunction = disjunction;
exports.etc = etc;
exports.ident = ident;
exports.iife = iife;
exports.nullLiteral = nullLiteral;
exports.numberLiteral = numberLiteral;
exports.stringLiteral = stringLiteral;
exports.throwStatement = throwStatement;
exports.typeofExpression = typeofExpression;
exports.variableDeclaration = variableDeclaration;
const EMPTY_PARENT = null;
exports.EMPTY_PARENT = EMPTY_PARENT;
function createDefaultPosition() {
return {
line: 1,
column: 0
};
}
function etc({
loc,
range,
parent
} = {}) {
return {
loc: {
start: (loc == null ? void 0 : loc.start) != null ? loc.start : createDefaultPosition(),
end: (loc == null ? void 0 : loc.end) != null ? loc.end : createDefaultPosition()
},
range: range != null ? range : [0, 0],
parent: parent != null ? parent : EMPTY_PARENT
};
}
function ident(name, info) {
return {
type: 'Identifier',
name,
optional: false,
typeAnnotation: null,
...etc(info)
};
}
function stringLiteral(value, info) {
return {
type: 'Literal',
value,
raw: `"${value}"`,
literalType: 'string',
...etc(info)
};
}
function numberLiteral(value, info) {
return {
type: 'Literal',
value,
raw: String(value),
literalType: 'numeric',
...etc(info)
};
}
function nullLiteral(info) {
return {
type: 'Literal',
value: null,
raw: 'null',
literalType: 'null',
...etc(info)
};
}
function conjunction(tests) {
if (tests.length === 0) {
throw new Error('Must have at least one test.');
}
return tests.reduce((acc, test) => ({
type: 'LogicalExpression',
left: acc,
right: test,
operator: '&&',
...etc()
}));
}
function disjunction(tests) {
if (tests.length === 0) {
throw new Error('Must have at least one test.');
}
return tests.reduce((acc, test) => ({
type: 'LogicalExpression',
left: acc,
right: test,
operator: '||',
...etc()
}));
}
function variableDeclaration(kind, id, init, info) {
return {
type: 'VariableDeclaration',
kind,
declarations: [{
type: 'VariableDeclarator',
init,
id,
...etc(),
parent: EMPTY_PARENT
}],
...etc(info)
};
}
function callExpression(callee, args, info) {
return {
type: 'CallExpression',
callee,
arguments: args,
typeArguments: null,
optional: false,
...etc(info)
};
}
function throwStatement(arg, info) {
return {
type: 'ThrowStatement',
argument: callExpression(ident('Error'), [arg]),
...etc(info)
};
}
function iife(statements, params = [], args = []) {
const callee = {
type: 'ArrowFunctionExpression',
params,
expression: false,
async: false,
predicate: null,
returnType: null,
typeParameters: null,
id: null,
body: {
type: 'BlockStatement',
body: statements,
...etc()
},
...etc()
};
return callExpression(callee, args);
}
function typeofExpression(arg, kind) {
return {
type: 'BinaryExpression',
left: {
type: 'UnaryExpression',
operator: 'typeof',
argument: arg,
prefix: true,
...etc()
},
right: stringLiteral(kind),
operator: '===',
...etc()
};
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSyntaxError = createSyntaxError;
function createSyntaxError(node, err) {
const syntaxError = new SyntaxError(err);
syntaxError.loc = {
line: node.loc.start.line,
column: node.loc.start.column
};
return syntaxError;
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const genPrefix = '$$gen$';
class GenID {
constructor(uniqueTransformPrefix) {
this.genN = 0;
this.used = new Set();
this.prefix = void 0;
this.prefix = `${genPrefix}${uniqueTransformPrefix}`;
}
id() {
let name;
do {
name = `${this.prefix}${this.genN}`;
this.genN++;
} while (this.used.has(name));
this.used.add(name);
return name;
}
addUsage(name) {
if (name.startsWith(this.prefix)) {
this.used.add(name);
}
}
}
exports.default = GenID;

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isReservedWord;
function isReservedWord(name) {
switch (name) {
case 'await':
case 'break':
case 'case':
case 'catch':
case 'class':
case 'const':
case 'continue':
case 'debugger':
case 'default':
case 'delete':
case 'do':
case 'else':
case 'enum':
case 'export':
case 'extends':
case 'false':
case 'finally':
case 'for':
case 'function':
case 'if':
case 'import':
case 'in':
case 'instanceof':
case 'new':
case 'null':
case 'return':
case 'super':
case 'switch':
case 'this':
case 'throw':
case 'true':
case 'try':
case 'typeof':
case 'var':
case 'void':
case 'while':
case 'with':
case 'yield':
return true;
default:
return false;
}
}

Sorry, the diff of this file is not supported yet

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mutate;
var _SimpleTransform = require("../transform/SimpleTransform");
function transformChainExpression(node, comments) {
if (comments != null) {
var _node$comments;
const joinedComments = comments.concat((_node$comments = node.comments) != null ? _node$comments : []);
node.comments = joinedComments;
}
switch (node.type) {
case 'CallExpression':
return { ...node,
type: 'OptionalCallExpression',
callee: transformChainExpression(node.callee)
};
case 'MemberExpression':
return { ...node,
type: 'OptionalMemberExpression',
object: transformChainExpression(node.object)
};
}
return node;
}
function mutate(rootNode, visitorKeys) {
_SimpleTransform.SimpleTransform.transform(rootNode, {
transform(node) {
if (node.parent) {
delete node.parent;
}
if (node.type === 'ChainExpression') {
return transformChainExpression(node.expression, node == null ? void 0 : node.comments);
}
if (node.type === 'ObjectTypeProperty') {
if (node.method === false && node.kind === 'init' && node.range[0] === 1 && node.value.range[0] === 1) {
node.value = { ...node.value,
range: [2, node.value.range[1]]
};
}
return node;
}
if (node.type === 'ImportSpecifier') {
if (node.local.name === node.imported.name) {
if (node.local.range == null) {
node.local.range = [0, 0];
}
node.imported.range = [...node.local.range];
}
return node;
}
if (node.type === 'ExportSpecifier') {
if (node.local.name === node.exported.name) {
if (node.local.range == null) {
node.local.range = [0, 0];
}
node.exported.range = [...node.local.range];
}
return node;
}
return node;
},
visitorKeys
});
}

Sorry, the diff of this file is not supported yet

+6
-4
{
"name": "flow-parser",
"version": "0.318.0",
"version": "0.319.0",
"description": "JavaScript parser written in OCaml. Produces ESTree AST",

@@ -12,3 +12,4 @@ "homepage": "https://flow.org",

"files": [
"flow_parser.js"
"flow_parser.js",
"oxidized"
],

@@ -25,3 +26,5 @@ "main": "flow_parser.js",

},
"dependencies": {},
"dependencies": {
"flow-estree": "0.319.0"
},
"devDependencies": {

@@ -34,3 +37,2 @@ "@babel/generator": "7.7.4",

"flow-enums-runtime": "0.0.6",
"flow-estree": "0.0.1",
"hermes-estree": "0.36.1",

@@ -37,0 +39,0 @@ "hermes-parser": "0.36.1",