You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33965 lines
1.2 MiB

4 years ago
  1. /* Riot Compiler WIP, @license MIT */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path')) :
  4. typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path'], factory) :
  5. (global = global || self, factory(global.compiler = {}, global.fs, global.path));
  6. }(this, (function (exports, fs, path$1) { 'use strict';
  7. fs = fs && fs.hasOwnProperty('default') ? fs['default'] : fs;
  8. path$1 = path$1 && path$1.hasOwnProperty('default') ? path$1['default'] : path$1;
  9. const TAG_LOGIC_PROPERTY = 'exports';
  10. const TAG_CSS_PROPERTY = 'css';
  11. const TAG_TEMPLATE_PROPERTY = 'template';
  12. const TAG_NAME_PROPERTY = 'name';
  13. function unwrapExports (x) {
  14. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  15. }
  16. function createCommonjsModule(fn, module) {
  17. return module = { exports: {} }, fn(module, module.exports), module.exports;
  18. }
  19. function getCjsExportFromNamespace (n) {
  20. return n && n['default'] || n;
  21. }
  22. var types = createCommonjsModule(function (module, exports) {
  23. var __extends = (this && this.__extends) || (function () {
  24. var extendStatics = function (d, b) {
  25. extendStatics = Object.setPrototypeOf ||
  26. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  27. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  28. return extendStatics(d, b);
  29. };
  30. return function (d, b) {
  31. extendStatics(d, b);
  32. function __() { this.constructor = d; }
  33. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  34. };
  35. })();
  36. Object.defineProperty(exports, "__esModule", { value: true });
  37. var Op = Object.prototype;
  38. var objToStr = Op.toString;
  39. var hasOwn = Op.hasOwnProperty;
  40. var BaseType = /** @class */ (function () {
  41. function BaseType() {
  42. }
  43. BaseType.prototype.assert = function (value, deep) {
  44. if (!this.check(value, deep)) {
  45. var str = shallowStringify(value);
  46. throw new Error(str + " does not match type " + this);
  47. }
  48. return true;
  49. };
  50. BaseType.prototype.arrayOf = function () {
  51. var elemType = this;
  52. return new ArrayType(elemType);
  53. };
  54. return BaseType;
  55. }());
  56. var ArrayType = /** @class */ (function (_super) {
  57. __extends(ArrayType, _super);
  58. function ArrayType(elemType) {
  59. var _this = _super.call(this) || this;
  60. _this.elemType = elemType;
  61. _this.kind = "ArrayType";
  62. return _this;
  63. }
  64. ArrayType.prototype.toString = function () {
  65. return "[" + this.elemType + "]";
  66. };
  67. ArrayType.prototype.check = function (value, deep) {
  68. var _this = this;
  69. return Array.isArray(value) && value.every(function (elem) { return _this.elemType.check(elem, deep); });
  70. };
  71. return ArrayType;
  72. }(BaseType));
  73. var IdentityType = /** @class */ (function (_super) {
  74. __extends(IdentityType, _super);
  75. function IdentityType(value) {
  76. var _this = _super.call(this) || this;
  77. _this.value = value;
  78. _this.kind = "IdentityType";
  79. return _this;
  80. }
  81. IdentityType.prototype.toString = function () {
  82. return String(this.value);
  83. };
  84. IdentityType.prototype.check = function (value, deep) {
  85. var result = value === this.value;
  86. if (!result && typeof deep === "function") {
  87. deep(this, value);
  88. }
  89. return result;
  90. };
  91. return IdentityType;
  92. }(BaseType));
  93. var ObjectType = /** @class */ (function (_super) {
  94. __extends(ObjectType, _super);
  95. function ObjectType(fields) {
  96. var _this = _super.call(this) || this;
  97. _this.fields = fields;
  98. _this.kind = "ObjectType";
  99. return _this;
  100. }
  101. ObjectType.prototype.toString = function () {
  102. return "{ " + this.fields.join(", ") + " }";
  103. };
  104. ObjectType.prototype.check = function (value, deep) {
  105. return (objToStr.call(value) === objToStr.call({}) &&
  106. this.fields.every(function (field) {
  107. return field.type.check(value[field.name], deep);
  108. }));
  109. };
  110. return ObjectType;
  111. }(BaseType));
  112. var OrType = /** @class */ (function (_super) {
  113. __extends(OrType, _super);
  114. function OrType(types) {
  115. var _this = _super.call(this) || this;
  116. _this.types = types;
  117. _this.kind = "OrType";
  118. return _this;
  119. }
  120. OrType.prototype.toString = function () {
  121. return this.types.join(" | ");
  122. };
  123. OrType.prototype.check = function (value, deep) {
  124. return this.types.some(function (type) {
  125. return type.check(value, deep);
  126. });
  127. };
  128. return OrType;
  129. }(BaseType));
  130. var PredicateType = /** @class */ (function (_super) {
  131. __extends(PredicateType, _super);
  132. function PredicateType(name, predicate) {
  133. var _this = _super.call(this) || this;
  134. _this.name = name;
  135. _this.predicate = predicate;
  136. _this.kind = "PredicateType";
  137. return _this;
  138. }
  139. PredicateType.prototype.toString = function () {
  140. return this.name;
  141. };
  142. PredicateType.prototype.check = function (value, deep) {
  143. var result = this.predicate(value, deep);
  144. if (!result && typeof deep === "function") {
  145. deep(this, value);
  146. }
  147. return result;
  148. };
  149. return PredicateType;
  150. }(BaseType));
  151. var Def = /** @class */ (function () {
  152. function Def(type, typeName) {
  153. this.type = type;
  154. this.typeName = typeName;
  155. this.baseNames = [];
  156. this.ownFields = Object.create(null);
  157. // Includes own typeName. Populated during finalization.
  158. this.allSupertypes = Object.create(null);
  159. // Linear inheritance hierarchy. Populated during finalization.
  160. this.supertypeList = [];
  161. // Includes inherited fields.
  162. this.allFields = Object.create(null);
  163. // Non-hidden keys of allFields.
  164. this.fieldNames = [];
  165. // This property will be overridden as true by individual Def instances
  166. // when they are finalized.
  167. this.finalized = false;
  168. // False by default until .build(...) is called on an instance.
  169. this.buildable = false;
  170. this.buildParams = [];
  171. }
  172. Def.prototype.isSupertypeOf = function (that) {
  173. if (that instanceof Def) {
  174. if (this.finalized !== true ||
  175. that.finalized !== true) {
  176. throw new Error("");
  177. }
  178. return hasOwn.call(that.allSupertypes, this.typeName);
  179. }
  180. else {
  181. throw new Error(that + " is not a Def");
  182. }
  183. };
  184. Def.prototype.checkAllFields = function (value, deep) {
  185. var allFields = this.allFields;
  186. if (this.finalized !== true) {
  187. throw new Error("" + this.typeName);
  188. }
  189. function checkFieldByName(name) {
  190. var field = allFields[name];
  191. var type = field.type;
  192. var child = field.getValue(value);
  193. return type.check(child, deep);
  194. }
  195. return value !== null &&
  196. typeof value === "object" &&
  197. Object.keys(allFields).every(checkFieldByName);
  198. };
  199. Def.prototype.bases = function () {
  200. var supertypeNames = [];
  201. for (var _i = 0; _i < arguments.length; _i++) {
  202. supertypeNames[_i] = arguments[_i];
  203. }
  204. var bases = this.baseNames;
  205. if (this.finalized) {
  206. if (supertypeNames.length !== bases.length) {
  207. throw new Error("");
  208. }
  209. for (var i = 0; i < supertypeNames.length; i++) {
  210. if (supertypeNames[i] !== bases[i]) {
  211. throw new Error("");
  212. }
  213. }
  214. return this;
  215. }
  216. supertypeNames.forEach(function (baseName) {
  217. // This indexOf lookup may be O(n), but the typical number of base
  218. // names is very small, and indexOf is a native Array method.
  219. if (bases.indexOf(baseName) < 0) {
  220. bases.push(baseName);
  221. }
  222. });
  223. return this; // For chaining.
  224. };
  225. return Def;
  226. }());
  227. exports.Def = Def;
  228. var Field = /** @class */ (function () {
  229. function Field(name, type, defaultFn, hidden) {
  230. this.name = name;
  231. this.type = type;
  232. this.defaultFn = defaultFn;
  233. this.hidden = !!hidden;
  234. }
  235. Field.prototype.toString = function () {
  236. return JSON.stringify(this.name) + ": " + this.type;
  237. };
  238. Field.prototype.getValue = function (obj) {
  239. var value = obj[this.name];
  240. if (typeof value !== "undefined") {
  241. return value;
  242. }
  243. if (typeof this.defaultFn === "function") {
  244. value = this.defaultFn.call(obj);
  245. }
  246. return value;
  247. };
  248. return Field;
  249. }());
  250. function shallowStringify(value) {
  251. if (Array.isArray(value)) {
  252. return "[" + value.map(shallowStringify).join(", ") + "]";
  253. }
  254. if (value && typeof value === "object") {
  255. return "{ " + Object.keys(value).map(function (key) {
  256. return key + ": " + value[key];
  257. }).join(", ") + " }";
  258. }
  259. return JSON.stringify(value);
  260. }
  261. function typesPlugin(_fork) {
  262. var Type = {
  263. or: function () {
  264. var types = [];
  265. for (var _i = 0; _i < arguments.length; _i++) {
  266. types[_i] = arguments[_i];
  267. }
  268. return new OrType(types.map(function (type) { return Type.from(type); }));
  269. },
  270. from: function (value, name) {
  271. if (value instanceof ArrayType ||
  272. value instanceof IdentityType ||
  273. value instanceof ObjectType ||
  274. value instanceof OrType ||
  275. value instanceof PredicateType) {
  276. return value;
  277. }
  278. // The Def type is used as a helper for constructing compound
  279. // interface types for AST nodes.
  280. if (value instanceof Def) {
  281. return value.type;
  282. }
  283. // Support [ElemType] syntax.
  284. if (isArray.check(value)) {
  285. if (value.length !== 1) {
  286. throw new Error("only one element type is permitted for typed arrays");
  287. }
  288. return new ArrayType(Type.from(value[0]));
  289. }
  290. // Support { someField: FieldType, ... } syntax.
  291. if (isObject.check(value)) {
  292. return new ObjectType(Object.keys(value).map(function (name) {
  293. return new Field(name, Type.from(value[name], name));
  294. }));
  295. }
  296. if (typeof value === "function") {
  297. var bicfIndex = builtInCtorFns.indexOf(value);
  298. if (bicfIndex >= 0) {
  299. return builtInCtorTypes[bicfIndex];
  300. }
  301. if (typeof name !== "string") {
  302. throw new Error("missing name");
  303. }
  304. return new PredicateType(name, value);
  305. }
  306. // As a last resort, toType returns a type that matches any value that
  307. // is === from. This is primarily useful for literal values like
  308. // toType(null), but it has the additional advantage of allowing
  309. // toType to be a total function.
  310. return new IdentityType(value);
  311. },
  312. // Define a type whose name is registered in a namespace (the defCache) so
  313. // that future definitions will return the same type given the same name.
  314. // In particular, this system allows for circular and forward definitions.
  315. // The Def object d returned from Type.def may be used to configure the
  316. // type d.type by calling methods such as d.bases, d.build, and d.field.
  317. def: function (typeName) {
  318. return hasOwn.call(defCache, typeName)
  319. ? defCache[typeName]
  320. : defCache[typeName] = new DefImpl(typeName);
  321. },
  322. hasDef: function (typeName) {
  323. return hasOwn.call(defCache, typeName);
  324. }
  325. };
  326. var builtInCtorFns = [];
  327. var builtInCtorTypes = [];
  328. var builtInTypes = {};
  329. function defBuiltInType(example, name) {
  330. var objStr = objToStr.call(example);
  331. var type = new PredicateType(name, function (value) { return objToStr.call(value) === objStr; });
  332. builtInTypes[name] = type;
  333. if (example && typeof example.constructor === "function") {
  334. builtInCtorFns.push(example.constructor);
  335. builtInCtorTypes.push(type);
  336. }
  337. return type;
  338. }
  339. // These types check the underlying [[Class]] attribute of the given
  340. // value, rather than using the problematic typeof operator. Note however
  341. // that no subtyping is considered; so, for instance, isObject.check
  342. // returns false for [], /./, new Date, and null.
  343. var isString = defBuiltInType("truthy", "string");
  344. var isFunction = defBuiltInType(function () { }, "function");
  345. var isArray = defBuiltInType([], "array");
  346. var isObject = defBuiltInType({}, "object");
  347. var isRegExp = defBuiltInType(/./, "RegExp");
  348. var isDate = defBuiltInType(new Date, "Date");
  349. var isNumber = defBuiltInType(3, "number");
  350. var isBoolean = defBuiltInType(true, "boolean");
  351. var isNull = defBuiltInType(null, "null");
  352. var isUndefined = defBuiltInType(void 0, "undefined");
  353. // In order to return the same Def instance every time Type.def is called
  354. // with a particular name, those instances need to be stored in a cache.
  355. var defCache = Object.create(null);
  356. function defFromValue(value) {
  357. if (value && typeof value === "object") {
  358. var type = value.type;
  359. if (typeof type === "string" &&
  360. hasOwn.call(defCache, type)) {
  361. var d = defCache[type];
  362. if (d.finalized) {
  363. return d;
  364. }
  365. }
  366. }
  367. return null;
  368. }
  369. var DefImpl = /** @class */ (function (_super) {
  370. __extends(DefImpl, _super);
  371. function DefImpl(typeName) {
  372. var _this = _super.call(this, new PredicateType(typeName, function (value, deep) { return _this.check(value, deep); }), typeName) || this;
  373. return _this;
  374. }
  375. DefImpl.prototype.check = function (value, deep) {
  376. if (this.finalized !== true) {
  377. throw new Error("prematurely checking unfinalized type " + this.typeName);
  378. }
  379. // A Def type can only match an object value.
  380. if (value === null || typeof value !== "object") {
  381. return false;
  382. }
  383. var vDef = defFromValue(value);
  384. if (!vDef) {
  385. // If we couldn't infer the Def associated with the given value,
  386. // and we expected it to be a SourceLocation or a Position, it was
  387. // probably just missing a "type" field (because Esprima does not
  388. // assign a type property to such nodes). Be optimistic and let
  389. // this.checkAllFields make the final decision.
  390. if (this.typeName === "SourceLocation" ||
  391. this.typeName === "Position") {
  392. return this.checkAllFields(value, deep);
  393. }
  394. // Calling this.checkAllFields for any other type of node is both
  395. // bad for performance and way too forgiving.
  396. return false;
  397. }
  398. // If checking deeply and vDef === this, then we only need to call
  399. // checkAllFields once. Calling checkAllFields is too strict when deep
  400. // is false, because then we only care about this.isSupertypeOf(vDef).
  401. if (deep && vDef === this) {
  402. return this.checkAllFields(value, deep);
  403. }
  404. // In most cases we rely exclusively on isSupertypeOf to make O(1)
  405. // subtyping determinations. This suffices in most situations outside
  406. // of unit tests, since interface conformance is checked whenever new
  407. // instances are created using builder functions.
  408. if (!this.isSupertypeOf(vDef)) {
  409. return false;
  410. }
  411. // The exception is when deep is true; then, we recursively check all
  412. // fields.
  413. if (!deep) {
  414. return true;
  415. }
  416. // Use the more specific Def (vDef) to perform the deep check, but
  417. // shallow-check fields defined by the less specific Def (this).
  418. return vDef.checkAllFields(value, deep)
  419. && this.checkAllFields(value, false);
  420. };
  421. DefImpl.prototype.build = function () {
  422. var _this = this;
  423. var buildParams = [];
  424. for (var _i = 0; _i < arguments.length; _i++) {
  425. buildParams[_i] = arguments[_i];
  426. }
  427. // Calling Def.prototype.build multiple times has the effect of merely
  428. // redefining this property.
  429. this.buildParams = buildParams;
  430. if (this.buildable) {
  431. // If this Def is already buildable, update self.buildParams and
  432. // continue using the old builder function.
  433. return this;
  434. }
  435. // Every buildable type will have its "type" field filled in
  436. // automatically. This includes types that are not subtypes of Node,
  437. // like SourceLocation, but that seems harmless (TODO?).
  438. this.field("type", String, function () { return _this.typeName; });
  439. // Override Dp.buildable for this Def instance.
  440. this.buildable = true;
  441. var addParam = function (built, param, arg, isArgAvailable) {
  442. if (hasOwn.call(built, param))
  443. return;
  444. var all = _this.allFields;
  445. if (!hasOwn.call(all, param)) {
  446. throw new Error("" + param);
  447. }
  448. var field = all[param];
  449. var type = field.type;
  450. var value;
  451. if (isArgAvailable) {
  452. value = arg;
  453. }
  454. else if (field.defaultFn) {
  455. // Expose the partially-built object to the default
  456. // function as its `this` object.
  457. value = field.defaultFn.call(built);
  458. }
  459. else {
  460. var message = "no value or default function given for field " +
  461. JSON.stringify(param) + " of " + _this.typeName + "(" +
  462. _this.buildParams.map(function (name) {
  463. return all[name];
  464. }).join(", ") + ")";
  465. throw new Error(message);
  466. }
  467. if (!type.check(value)) {
  468. throw new Error(shallowStringify(value) +
  469. " does not match field " + field +
  470. " of type " + _this.typeName);
  471. }
  472. built[param] = value;
  473. };
  474. // Calling the builder function will construct an instance of the Def,
  475. // with positional arguments mapped to the fields original passed to .build.
  476. // If not enough arguments are provided, the default value for the remaining fields
  477. // will be used.
  478. var builder = function () {
  479. var args = [];
  480. for (var _i = 0; _i < arguments.length; _i++) {
  481. args[_i] = arguments[_i];
  482. }
  483. var argc = args.length;
  484. if (!_this.finalized) {
  485. throw new Error("attempting to instantiate unfinalized type " +
  486. _this.typeName);
  487. }
  488. var built = Object.create(nodePrototype);
  489. _this.buildParams.forEach(function (param, i) {
  490. if (i < argc) {
  491. addParam(built, param, args[i], true);
  492. }
  493. else {
  494. addParam(built, param, null, false);
  495. }
  496. });
  497. Object.keys(_this.allFields).forEach(function (param) {
  498. // Use the default value.
  499. addParam(built, param, null, false);
  500. });
  501. // Make sure that the "type" field was filled automatically.
  502. if (built.type !== _this.typeName) {
  503. throw new Error("");
  504. }
  505. return built;
  506. };
  507. // Calling .from on the builder function will construct an instance of the Def,
  508. // using field values from the passed object. For fields missing from the passed object,
  509. // their default value will be used.
  510. builder.from = function (obj) {
  511. if (!_this.finalized) {
  512. throw new Error("attempting to instantiate unfinalized type " +
  513. _this.typeName);
  514. }
  515. var built = Object.create(nodePrototype);
  516. Object.keys(_this.allFields).forEach(function (param) {
  517. if (hasOwn.call(obj, param)) {
  518. addParam(built, param, obj[param], true);
  519. }
  520. else {
  521. addParam(built, param, null, false);
  522. }
  523. });
  524. // Make sure that the "type" field was filled automatically.
  525. if (built.type !== _this.typeName) {
  526. throw new Error("");
  527. }
  528. return built;
  529. };
  530. Object.defineProperty(builders, getBuilderName(this.typeName), {
  531. enumerable: true,
  532. value: builder
  533. });
  534. return this;
  535. };
  536. // The reason fields are specified using .field(...) instead of an object
  537. // literal syntax is somewhat subtle: the object literal syntax would
  538. // support only one key and one value, but with .field(...) we can pass
  539. // any number of arguments to specify the field.
  540. DefImpl.prototype.field = function (name, type, defaultFn, hidden) {
  541. if (this.finalized) {
  542. console.error("Ignoring attempt to redefine field " +
  543. JSON.stringify(name) + " of finalized type " +
  544. JSON.stringify(this.typeName));
  545. return this;
  546. }
  547. this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden);
  548. return this; // For chaining.
  549. };
  550. DefImpl.prototype.finalize = function () {
  551. var _this = this;
  552. // It's not an error to finalize a type more than once, but only the
  553. // first call to .finalize does anything.
  554. if (!this.finalized) {
  555. var allFields = this.allFields;
  556. var allSupertypes = this.allSupertypes;
  557. this.baseNames.forEach(function (name) {
  558. var def = defCache[name];
  559. if (def instanceof Def) {
  560. def.finalize();
  561. extend(allFields, def.allFields);
  562. extend(allSupertypes, def.allSupertypes);
  563. }
  564. else {
  565. var message = "unknown supertype name " +
  566. JSON.stringify(name) +
  567. " for subtype " +
  568. JSON.stringify(_this.typeName);
  569. throw new Error(message);
  570. }
  571. });
  572. // TODO Warn if fields are overridden with incompatible types.
  573. extend(allFields, this.ownFields);
  574. allSupertypes[this.typeName] = this;
  575. this.fieldNames.length = 0;
  576. for (var fieldName in allFields) {
  577. if (hasOwn.call(allFields, fieldName) &&
  578. !allFields[fieldName].hidden) {
  579. this.fieldNames.push(fieldName);
  580. }
  581. }
  582. // Types are exported only once they have been finalized.
  583. Object.defineProperty(namedTypes, this.typeName, {
  584. enumerable: true,
  585. value: this.type
  586. });
  587. this.finalized = true;
  588. // A linearization of the inheritance hierarchy.
  589. populateSupertypeList(this.typeName, this.supertypeList);
  590. if (this.buildable &&
  591. this.supertypeList.lastIndexOf("Expression") >= 0) {
  592. wrapExpressionBuilderWithStatement(this.typeName);
  593. }
  594. }
  595. };
  596. return DefImpl;
  597. }(Def));
  598. // Note that the list returned by this function is a copy of the internal
  599. // supertypeList, *without* the typeName itself as the first element.
  600. function getSupertypeNames(typeName) {
  601. if (!hasOwn.call(defCache, typeName)) {
  602. throw new Error("");
  603. }
  604. var d = defCache[typeName];
  605. if (d.finalized !== true) {
  606. throw new Error("");
  607. }
  608. return d.supertypeList.slice(1);
  609. }
  610. // Returns an object mapping from every known type in the defCache to the
  611. // most specific supertype whose name is an own property of the candidates
  612. // object.
  613. function computeSupertypeLookupTable(candidates) {
  614. var table = {};
  615. var typeNames = Object.keys(defCache);
  616. var typeNameCount = typeNames.length;
  617. for (var i = 0; i < typeNameCount; ++i) {
  618. var typeName = typeNames[i];
  619. var d = defCache[typeName];
  620. if (d.finalized !== true) {
  621. throw new Error("" + typeName);
  622. }
  623. for (var j = 0; j < d.supertypeList.length; ++j) {
  624. var superTypeName = d.supertypeList[j];
  625. if (hasOwn.call(candidates, superTypeName)) {
  626. table[typeName] = superTypeName;
  627. break;
  628. }
  629. }
  630. }
  631. return table;
  632. }
  633. var builders = Object.create(null);
  634. // This object is used as prototype for any node created by a builder.
  635. var nodePrototype = {};
  636. // Call this function to define a new method to be shared by all AST
  637. // nodes. The replaced method (if any) is returned for easy wrapping.
  638. function defineMethod(name, func) {
  639. var old = nodePrototype[name];
  640. // Pass undefined as func to delete nodePrototype[name].
  641. if (isUndefined.check(func)) {
  642. delete nodePrototype[name];
  643. }
  644. else {
  645. isFunction.assert(func);
  646. Object.defineProperty(nodePrototype, name, {
  647. enumerable: true,
  648. configurable: true,
  649. value: func
  650. });
  651. }
  652. return old;
  653. }
  654. function getBuilderName(typeName) {
  655. return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) {
  656. var len = upperCasePrefix.length;
  657. switch (len) {
  658. case 0: return "";
  659. // If there's only one initial capital letter, just lower-case it.
  660. case 1: return upperCasePrefix.toLowerCase();
  661. default:
  662. // If there's more than one initial capital letter, lower-case
  663. // all but the last one, so that XMLDefaultDeclaration (for
  664. // example) becomes xmlDefaultDeclaration.
  665. return upperCasePrefix.slice(0, len - 1).toLowerCase() +
  666. upperCasePrefix.charAt(len - 1);
  667. }
  668. });
  669. }
  670. function getStatementBuilderName(typeName) {
  671. typeName = getBuilderName(typeName);
  672. return typeName.replace(/(Expression)?$/, "Statement");
  673. }
  674. var namedTypes = {};
  675. // Like Object.keys, but aware of what fields each AST type should have.
  676. function getFieldNames(object) {
  677. var d = defFromValue(object);
  678. if (d) {
  679. return d.fieldNames.slice(0);
  680. }
  681. if ("type" in object) {
  682. throw new Error("did not recognize object of type " +
  683. JSON.stringify(object.type));
  684. }
  685. return Object.keys(object);
  686. }
  687. // Get the value of an object property, taking object.type and default
  688. // functions into account.
  689. function getFieldValue(object, fieldName) {
  690. var d = defFromValue(object);
  691. if (d) {
  692. var field = d.allFields[fieldName];
  693. if (field) {
  694. return field.getValue(object);
  695. }
  696. }
  697. return object && object[fieldName];
  698. }
  699. // Iterate over all defined fields of an object, including those missing
  700. // or undefined, passing each field name and effective value (as returned
  701. // by getFieldValue) to the callback. If the object has no corresponding
  702. // Def, the callback will never be called.
  703. function eachField(object, callback, context) {
  704. getFieldNames(object).forEach(function (name) {
  705. callback.call(this, name, getFieldValue(object, name));
  706. }, context);
  707. }
  708. // Similar to eachField, except that iteration stops as soon as the
  709. // callback returns a truthy value. Like Array.prototype.some, the final
  710. // result is either true or false to indicates whether the callback
  711. // returned true for any element or not.
  712. function someField(object, callback, context) {
  713. return getFieldNames(object).some(function (name) {
  714. return callback.call(this, name, getFieldValue(object, name));
  715. }, context);
  716. }
  717. // Adds an additional builder for Expression subtypes
  718. // that wraps the built Expression in an ExpressionStatements.
  719. function wrapExpressionBuilderWithStatement(typeName) {
  720. var wrapperName = getStatementBuilderName(typeName);
  721. // skip if the builder already exists
  722. if (builders[wrapperName])
  723. return;
  724. // the builder function to wrap with builders.ExpressionStatement
  725. var wrapped = builders[getBuilderName(typeName)];
  726. // skip if there is nothing to wrap
  727. if (!wrapped)
  728. return;
  729. var builder = function () {
  730. var args = [];
  731. for (var _i = 0; _i < arguments.length; _i++) {
  732. args[_i] = arguments[_i];
  733. }
  734. return builders.expressionStatement(wrapped.apply(builders, args));
  735. };
  736. builder.from = function () {
  737. var args = [];
  738. for (var _i = 0; _i < arguments.length; _i++) {
  739. args[_i] = arguments[_i];
  740. }
  741. return builders.expressionStatement(wrapped.from.apply(builders, args));
  742. };
  743. builders[wrapperName] = builder;
  744. }
  745. function populateSupertypeList(typeName, list) {
  746. list.length = 0;
  747. list.push(typeName);
  748. var lastSeen = Object.create(null);
  749. for (var pos = 0; pos < list.length; ++pos) {
  750. typeName = list[pos];
  751. var d = defCache[typeName];
  752. if (d.finalized !== true) {
  753. throw new Error("");
  754. }
  755. // If we saw typeName earlier in the breadth-first traversal,
  756. // delete the last-seen occurrence.
  757. if (hasOwn.call(lastSeen, typeName)) {
  758. delete list[lastSeen[typeName]];
  759. }
  760. // Record the new index of the last-seen occurrence of typeName.
  761. lastSeen[typeName] = pos;
  762. // Enqueue the base names of this type.
  763. list.push.apply(list, d.baseNames);
  764. }
  765. // Compaction loop to remove array holes.
  766. for (var to = 0, from = to, len = list.length; from < len; ++from) {
  767. if (hasOwn.call(list, from)) {
  768. list[to++] = list[from];
  769. }
  770. }
  771. list.length = to;
  772. }
  773. function extend(into, from) {
  774. Object.keys(from).forEach(function (name) {
  775. into[name] = from[name];
  776. });
  777. return into;
  778. }
  779. function finalize() {
  780. Object.keys(defCache).forEach(function (name) {
  781. defCache[name].finalize();
  782. });
  783. }
  784. return {
  785. Type: Type,
  786. builtInTypes: builtInTypes,
  787. getSupertypeNames: getSupertypeNames,
  788. computeSupertypeLookupTable: computeSupertypeLookupTable,
  789. builders: builders,
  790. defineMethod: defineMethod,
  791. getBuilderName: getBuilderName,
  792. getStatementBuilderName: getStatementBuilderName,
  793. namedTypes: namedTypes,
  794. getFieldNames: getFieldNames,
  795. getFieldValue: getFieldValue,
  796. eachField: eachField,
  797. someField: someField,
  798. finalize: finalize,
  799. };
  800. }
  801. exports.default = typesPlugin;
  802. });
  803. unwrapExports(types);
  804. var types_1 = types.Def;
  805. var path = createCommonjsModule(function (module, exports) {
  806. var __importDefault = (this && this.__importDefault) || function (mod) {
  807. return (mod && mod.__esModule) ? mod : { "default": mod };
  808. };
  809. Object.defineProperty(exports, "__esModule", { value: true });
  810. var types_1 = __importDefault(types);
  811. var Op = Object.prototype;
  812. var hasOwn = Op.hasOwnProperty;
  813. function pathPlugin(fork) {
  814. var types = fork.use(types_1.default);
  815. var isArray = types.builtInTypes.array;
  816. var isNumber = types.builtInTypes.number;
  817. var Path = function Path(value, parentPath, name) {
  818. if (!(this instanceof Path)) {
  819. throw new Error("Path constructor cannot be invoked without 'new'");
  820. }
  821. if (parentPath) {
  822. if (!(parentPath instanceof Path)) {
  823. throw new Error("");
  824. }
  825. }
  826. else {
  827. parentPath = null;
  828. name = null;
  829. }
  830. // The value encapsulated by this Path, generally equal to
  831. // parentPath.value[name] if we have a parentPath.
  832. this.value = value;
  833. // The immediate parent Path of this Path.
  834. this.parentPath = parentPath;
  835. // The name of the property of parentPath.value through which this
  836. // Path's value was reached.
  837. this.name = name;
  838. // Calling path.get("child") multiple times always returns the same
  839. // child Path object, for both performance and consistency reasons.
  840. this.__childCache = null;
  841. };
  842. var Pp = Path.prototype;
  843. function getChildCache(path) {
  844. // Lazily create the child cache. This also cheapens cache
  845. // invalidation, since you can just reset path.__childCache to null.
  846. return path.__childCache || (path.__childCache = Object.create(null));
  847. }
  848. function getChildPath(path, name) {
  849. var cache = getChildCache(path);
  850. var actualChildValue = path.getValueProperty(name);
  851. var childPath = cache[name];
  852. if (!hasOwn.call(cache, name) ||
  853. // Ensure consistency between cache and reality.
  854. childPath.value !== actualChildValue) {
  855. childPath = cache[name] = new path.constructor(actualChildValue, path, name);
  856. }
  857. return childPath;
  858. }
  859. // This method is designed to be overridden by subclasses that need to
  860. // handle missing properties, etc.
  861. Pp.getValueProperty = function getValueProperty(name) {
  862. return this.value[name];
  863. };
  864. Pp.get = function get() {
  865. var names = [];
  866. for (var _i = 0; _i < arguments.length; _i++) {
  867. names[_i] = arguments[_i];
  868. }
  869. var path = this;
  870. var count = names.length;
  871. for (var i = 0; i < count; ++i) {
  872. path = getChildPath(path, names[i]);
  873. }
  874. return path;
  875. };
  876. Pp.each = function each(callback, context) {
  877. var childPaths = [];
  878. var len = this.value.length;
  879. var i = 0;
  880. // Collect all the original child paths before invoking the callback.
  881. for (var i = 0; i < len; ++i) {
  882. if (hasOwn.call(this.value, i)) {
  883. childPaths[i] = this.get(i);
  884. }
  885. }
  886. // Invoke the callback on just the original child paths, regardless of
  887. // any modifications made to the array by the callback. I chose these
  888. // semantics over cleverly invoking the callback on new elements because
  889. // this way is much easier to reason about.
  890. context = context || this;
  891. for (i = 0; i < len; ++i) {
  892. if (hasOwn.call(childPaths, i)) {
  893. callback.call(context, childPaths[i]);
  894. }
  895. }
  896. };
  897. Pp.map = function map(callback, context) {
  898. var result = [];
  899. this.each(function (childPath) {
  900. result.push(callback.call(this, childPath));
  901. }, context);
  902. return result;
  903. };
  904. Pp.filter = function filter(callback, context) {
  905. var result = [];
  906. this.each(function (childPath) {
  907. if (callback.call(this, childPath)) {
  908. result.push(childPath);
  909. }
  910. }, context);
  911. return result;
  912. };
  913. function emptyMoves() { }
  914. function getMoves(path, offset, start, end) {
  915. isArray.assert(path.value);
  916. if (offset === 0) {
  917. return emptyMoves;
  918. }
  919. var length = path.value.length;
  920. if (length < 1) {
  921. return emptyMoves;
  922. }
  923. var argc = arguments.length;
  924. if (argc === 2) {
  925. start = 0;
  926. end = length;
  927. }
  928. else if (argc === 3) {
  929. start = Math.max(start, 0);
  930. end = length;
  931. }
  932. else {
  933. start = Math.max(start, 0);
  934. end = Math.min(end, length);
  935. }
  936. isNumber.assert(start);
  937. isNumber.assert(end);
  938. var moves = Object.create(null);
  939. var cache = getChildCache(path);
  940. for (var i = start; i < end; ++i) {
  941. if (hasOwn.call(path.value, i)) {
  942. var childPath = path.get(i);
  943. if (childPath.name !== i) {
  944. throw new Error("");
  945. }
  946. var newIndex = i + offset;
  947. childPath.name = newIndex;
  948. moves[newIndex] = childPath;
  949. delete cache[i];
  950. }
  951. }
  952. delete cache.length;
  953. return function () {
  954. for (var newIndex in moves) {
  955. var childPath = moves[newIndex];
  956. if (childPath.name !== +newIndex) {
  957. throw new Error("");
  958. }
  959. cache[newIndex] = childPath;
  960. path.value[newIndex] = childPath.value;
  961. }
  962. };
  963. }
  964. Pp.shift = function shift() {
  965. var move = getMoves(this, -1);
  966. var result = this.value.shift();
  967. move();
  968. return result;
  969. };
  970. Pp.unshift = function unshift() {
  971. var args = [];
  972. for (var _i = 0; _i < arguments.length; _i++) {
  973. args[_i] = arguments[_i];
  974. }
  975. var move = getMoves(this, args.length);
  976. var result = this.value.unshift.apply(this.value, args);
  977. move();
  978. return result;
  979. };
  980. Pp.push = function push() {
  981. var args = [];
  982. for (var _i = 0; _i < arguments.length; _i++) {
  983. args[_i] = arguments[_i];
  984. }
  985. isArray.assert(this.value);
  986. delete getChildCache(this).length;
  987. return this.value.push.apply(this.value, args);
  988. };
  989. Pp.pop = function pop() {
  990. isArray.assert(this.value);
  991. var cache = getChildCache(this);
  992. delete cache[this.value.length - 1];
  993. delete cache.length;
  994. return this.value.pop();
  995. };
  996. Pp.insertAt = function insertAt(index) {
  997. var argc = arguments.length;
  998. var move = getMoves(this, argc - 1, index);
  999. if (move === emptyMoves && argc <= 1) {
  1000. return this;
  1001. }
  1002. index = Math.max(index, 0);
  1003. for (var i = 1; i < argc; ++i) {
  1004. this.value[index + i - 1] = arguments[i];
  1005. }
  1006. move();
  1007. return this;
  1008. };
  1009. Pp.insertBefore = function insertBefore() {
  1010. var args = [];
  1011. for (var _i = 0; _i < arguments.length; _i++) {
  1012. args[_i] = arguments[_i];
  1013. }
  1014. var pp = this.parentPath;
  1015. var argc = args.length;
  1016. var insertAtArgs = [this.name];
  1017. for (var i = 0; i < argc; ++i) {
  1018. insertAtArgs.push(args[i]);
  1019. }
  1020. return pp.insertAt.apply(pp, insertAtArgs);
  1021. };
  1022. Pp.insertAfter = function insertAfter() {
  1023. var args = [];
  1024. for (var _i = 0; _i < arguments.length; _i++) {
  1025. args[_i] = arguments[_i];
  1026. }
  1027. var pp = this.parentPath;
  1028. var argc = args.length;
  1029. var insertAtArgs = [this.name + 1];
  1030. for (var i = 0; i < argc; ++i) {
  1031. insertAtArgs.push(args[i]);
  1032. }
  1033. return pp.insertAt.apply(pp, insertAtArgs);
  1034. };
  1035. function repairRelationshipWithParent(path) {
  1036. if (!(path instanceof Path)) {
  1037. throw new Error("");
  1038. }
  1039. var pp = path.parentPath;
  1040. if (!pp) {
  1041. // Orphan paths have no relationship to repair.
  1042. return path;
  1043. }
  1044. var parentValue = pp.value;
  1045. var parentCache = getChildCache(pp);
  1046. // Make sure parentCache[path.name] is populated.
  1047. if (parentValue[path.name] === path.value) {
  1048. parentCache[path.name] = path;
  1049. }
  1050. else if (isArray.check(parentValue)) {
  1051. // Something caused path.name to become out of date, so attempt to
  1052. // recover by searching for path.value in parentValue.
  1053. var i = parentValue.indexOf(path.value);
  1054. if (i >= 0) {
  1055. parentCache[path.name = i] = path;
  1056. }
  1057. }
  1058. else {
  1059. // If path.value disagrees with parentValue[path.name], and
  1060. // path.name is not an array index, let path.value become the new
  1061. // parentValue[path.name] and update parentCache accordingly.
  1062. parentValue[path.name] = path.value;
  1063. parentCache[path.name] = path;
  1064. }
  1065. if (parentValue[path.name] !== path.value) {
  1066. throw new Error("");
  1067. }
  1068. if (path.parentPath.get(path.name) !== path) {
  1069. throw new Error("");
  1070. }
  1071. return path;
  1072. }
  1073. Pp.replace = function replace(replacement) {
  1074. var results = [];
  1075. var parentValue = this.parentPath.value;
  1076. var parentCache = getChildCache(this.parentPath);
  1077. var count = arguments.length;
  1078. repairRelationshipWithParent(this);
  1079. if (isArray.check(parentValue)) {
  1080. var originalLength = parentValue.length;
  1081. var move = getMoves(this.parentPath, count - 1, this.name + 1);
  1082. var spliceArgs = [this.name, 1];
  1083. for (var i = 0; i < count; ++i) {
  1084. spliceArgs.push(arguments[i]);
  1085. }
  1086. var splicedOut = parentValue.splice.apply(parentValue, spliceArgs);
  1087. if (splicedOut[0] !== this.value) {
  1088. throw new Error("");
  1089. }
  1090. if (parentValue.length !== (originalLength - 1 + count)) {
  1091. throw new Error("");
  1092. }
  1093. move();
  1094. if (count === 0) {
  1095. delete this.value;
  1096. delete parentCache[this.name];
  1097. this.__childCache = null;
  1098. }
  1099. else {
  1100. if (parentValue[this.name] !== replacement) {
  1101. throw new Error("");
  1102. }
  1103. if (this.value !== replacement) {
  1104. this.value = replacement;
  1105. this.__childCache = null;
  1106. }
  1107. for (i = 0; i < count; ++i) {
  1108. results.push(this.parentPath.get(this.name + i));
  1109. }
  1110. if (results[0] !== this) {
  1111. throw new Error("");
  1112. }
  1113. }
  1114. }
  1115. else if (count === 1) {
  1116. if (this.value !== replacement) {
  1117. this.__childCache = null;
  1118. }
  1119. this.value = parentValue[this.name] = replacement;
  1120. results.push(this);
  1121. }
  1122. else if (count === 0) {
  1123. delete parentValue[this.name];
  1124. delete this.value;
  1125. this.__childCache = null;
  1126. // Leave this path cached as parentCache[this.name], even though
  1127. // it no longer has a value defined.
  1128. }
  1129. else {
  1130. throw new Error("Could not replace path");
  1131. }
  1132. return results;
  1133. };
  1134. return Path;
  1135. }
  1136. exports.default = pathPlugin;
  1137. module.exports = exports["default"];
  1138. });
  1139. unwrapExports(path);
  1140. var scope = createCommonjsModule(function (module, exports) {
  1141. var __importDefault = (this && this.__importDefault) || function (mod) {
  1142. return (mod && mod.__esModule) ? mod : { "default": mod };
  1143. };
  1144. Object.defineProperty(exports, "__esModule", { value: true });
  1145. var types_1 = __importDefault(types);
  1146. var hasOwn = Object.prototype.hasOwnProperty;
  1147. function scopePlugin(fork) {
  1148. var types = fork.use(types_1.default);
  1149. var Type = types.Type;
  1150. var namedTypes = types.namedTypes;
  1151. var Node = namedTypes.Node;
  1152. var Expression = namedTypes.Expression;
  1153. var isArray = types.builtInTypes.array;
  1154. var b = types.builders;
  1155. var Scope = function Scope(path, parentScope) {
  1156. if (!(this instanceof Scope)) {
  1157. throw new Error("Scope constructor cannot be invoked without 'new'");
  1158. }
  1159. ScopeType.assert(path.value);
  1160. var depth;
  1161. if (parentScope) {
  1162. if (!(parentScope instanceof Scope)) {
  1163. throw new Error("");
  1164. }
  1165. depth = parentScope.depth + 1;
  1166. }
  1167. else {
  1168. parentScope = null;
  1169. depth = 0;
  1170. }
  1171. Object.defineProperties(this, {
  1172. path: { value: path },
  1173. node: { value: path.value },
  1174. isGlobal: { value: !parentScope, enumerable: true },
  1175. depth: { value: depth },
  1176. parent: { value: parentScope },
  1177. bindings: { value: {} },
  1178. types: { value: {} },
  1179. });
  1180. };
  1181. var scopeTypes = [
  1182. // Program nodes introduce global scopes.
  1183. namedTypes.Program,
  1184. // Function is the supertype of FunctionExpression,
  1185. // FunctionDeclaration, ArrowExpression, etc.
  1186. namedTypes.Function,
  1187. // In case you didn't know, the caught parameter shadows any variable
  1188. // of the same name in an outer scope.
  1189. namedTypes.CatchClause
  1190. ];
  1191. var ScopeType = Type.or.apply(Type, scopeTypes);
  1192. Scope.isEstablishedBy = function (node) {
  1193. return ScopeType.check(node);
  1194. };
  1195. var Sp = Scope.prototype;
  1196. // Will be overridden after an instance lazily calls scanScope.
  1197. Sp.didScan = false;
  1198. Sp.declares = function (name) {
  1199. this.scan();
  1200. return hasOwn.call(this.bindings, name);
  1201. };
  1202. Sp.declaresType = function (name) {
  1203. this.scan();
  1204. return hasOwn.call(this.types, name);
  1205. };
  1206. Sp.declareTemporary = function (prefix) {
  1207. if (prefix) {
  1208. if (!/^[a-z$_]/i.test(prefix)) {
  1209. throw new Error("");
  1210. }
  1211. }
  1212. else {
  1213. prefix = "t$";
  1214. }
  1215. // Include this.depth in the name to make sure the name does not
  1216. // collide with any variables in nested/enclosing scopes.
  1217. prefix += this.depth.toString(36) + "$";
  1218. this.scan();
  1219. var index = 0;
  1220. while (this.declares(prefix + index)) {
  1221. ++index;
  1222. }
  1223. var name = prefix + index;
  1224. return this.bindings[name] = types.builders.identifier(name);
  1225. };
  1226. Sp.injectTemporary = function (identifier, init) {
  1227. identifier || (identifier = this.declareTemporary());
  1228. var bodyPath = this.path.get("body");
  1229. if (namedTypes.BlockStatement.check(bodyPath.value)) {
  1230. bodyPath = bodyPath.get("body");
  1231. }
  1232. bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init || null)]));
  1233. return identifier;
  1234. };
  1235. Sp.scan = function (force) {
  1236. if (force || !this.didScan) {
  1237. for (var name in this.bindings) {
  1238. // Empty out this.bindings, just in cases.
  1239. delete this.bindings[name];
  1240. }
  1241. scanScope(this.path, this.bindings, this.types);
  1242. this.didScan = true;
  1243. }
  1244. };
  1245. Sp.getBindings = function () {
  1246. this.scan();
  1247. return this.bindings;
  1248. };
  1249. Sp.getTypes = function () {
  1250. this.scan();
  1251. return this.types;
  1252. };
  1253. function scanScope(path, bindings, scopeTypes) {
  1254. var node = path.value;
  1255. ScopeType.assert(node);
  1256. if (namedTypes.CatchClause.check(node)) {
  1257. // A catch clause establishes a new scope but the only variable
  1258. // bound in that scope is the catch parameter. Any other
  1259. // declarations create bindings in the outer scope.
  1260. addPattern(path.get("param"), bindings);
  1261. }
  1262. else {
  1263. recursiveScanScope(path, bindings, scopeTypes);
  1264. }
  1265. }
  1266. function recursiveScanScope(path, bindings, scopeTypes) {
  1267. var node = path.value;
  1268. if (path.parent &&
  1269. namedTypes.FunctionExpression.check(path.parent.node) &&
  1270. path.parent.node.id) {
  1271. addPattern(path.parent.get("id"), bindings);
  1272. }
  1273. if (!node) ;
  1274. else if (isArray.check(node)) {
  1275. path.each(function (childPath) {
  1276. recursiveScanChild(childPath, bindings, scopeTypes);
  1277. });
  1278. }
  1279. else if (namedTypes.Function.check(node)) {
  1280. path.get("params").each(function (paramPath) {
  1281. addPattern(paramPath, bindings);
  1282. });
  1283. recursiveScanChild(path.get("body"), bindings, scopeTypes);
  1284. }
  1285. else if ((namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) ||
  1286. (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) ||
  1287. (namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) ||
  1288. (namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))) {
  1289. addTypePattern(path.get("id"), scopeTypes);
  1290. }
  1291. else if (namedTypes.VariableDeclarator.check(node)) {
  1292. addPattern(path.get("id"), bindings);
  1293. recursiveScanChild(path.get("init"), bindings, scopeTypes);
  1294. }
  1295. else if (node.type === "ImportSpecifier" ||
  1296. node.type === "ImportNamespaceSpecifier" ||
  1297. node.type === "ImportDefaultSpecifier") {
  1298. addPattern(
  1299. // Esprima used to use the .name field to refer to the local
  1300. // binding identifier for ImportSpecifier nodes, but .id for
  1301. // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes.
  1302. // ESTree/Acorn/ESpree use .local for all three node types.
  1303. path.get(node.local ? "local" :
  1304. node.name ? "name" : "id"), bindings);
  1305. }
  1306. else if (Node.check(node) && !Expression.check(node)) {
  1307. types.eachField(node, function (name, child) {
  1308. var childPath = path.get(name);
  1309. if (!pathHasValue(childPath, child)) {
  1310. throw new Error("");
  1311. }
  1312. recursiveScanChild(childPath, bindings, scopeTypes);
  1313. });
  1314. }
  1315. }
  1316. function pathHasValue(path, value) {
  1317. if (path.value === value) {
  1318. return true;
  1319. }
  1320. // Empty arrays are probably produced by defaults.emptyArray, in which
  1321. // case is makes sense to regard them as equivalent, if not ===.
  1322. if (Array.isArray(path.value) &&
  1323. path.value.length === 0 &&
  1324. Array.isArray(value) &&
  1325. value.length === 0) {
  1326. return true;
  1327. }
  1328. return false;
  1329. }
  1330. function recursiveScanChild(path, bindings, scopeTypes) {
  1331. var node = path.value;
  1332. if (!node || Expression.check(node)) ;
  1333. else if (namedTypes.FunctionDeclaration.check(node) &&
  1334. node.id !== null) {
  1335. addPattern(path.get("id"), bindings);
  1336. }
  1337. else if (namedTypes.ClassDeclaration &&
  1338. namedTypes.ClassDeclaration.check(node)) {
  1339. addPattern(path.get("id"), bindings);
  1340. }
  1341. else if (ScopeType.check(node)) {
  1342. if (namedTypes.CatchClause.check(node) &&
  1343. // TODO Broaden this to accept any pattern.
  1344. namedTypes.Identifier.check(node.param)) {
  1345. var catchParamName = node.param.name;
  1346. var hadBinding = hasOwn.call(bindings, catchParamName);
  1347. // Any declarations that occur inside the catch body that do
  1348. // not have the same name as the catch parameter should count
  1349. // as bindings in the outer scope.
  1350. recursiveScanScope(path.get("body"), bindings, scopeTypes);
  1351. // If a new binding matching the catch parameter name was
  1352. // created while scanning the catch body, ignore it because it
  1353. // actually refers to the catch parameter and not the outer
  1354. // scope that we're currently scanning.
  1355. if (!hadBinding) {
  1356. delete bindings[catchParamName];
  1357. }
  1358. }
  1359. }
  1360. else {
  1361. recursiveScanScope(path, bindings, scopeTypes);
  1362. }
  1363. }
  1364. function addPattern(patternPath, bindings) {
  1365. var pattern = patternPath.value;
  1366. namedTypes.Pattern.assert(pattern);
  1367. if (namedTypes.Identifier.check(pattern)) {
  1368. if (hasOwn.call(bindings, pattern.name)) {
  1369. bindings[pattern.name].push(patternPath);
  1370. }
  1371. else {
  1372. bindings[pattern.name] = [patternPath];
  1373. }
  1374. }
  1375. else if (namedTypes.AssignmentPattern &&
  1376. namedTypes.AssignmentPattern.check(pattern)) {
  1377. addPattern(patternPath.get('left'), bindings);
  1378. }
  1379. else if (namedTypes.ObjectPattern &&
  1380. namedTypes.ObjectPattern.check(pattern)) {
  1381. patternPath.get('properties').each(function (propertyPath) {
  1382. var property = propertyPath.value;
  1383. if (namedTypes.Pattern.check(property)) {
  1384. addPattern(propertyPath, bindings);
  1385. }
  1386. else if (namedTypes.Property.check(property)) {
  1387. addPattern(propertyPath.get('value'), bindings);
  1388. }
  1389. else if (namedTypes.SpreadProperty &&
  1390. namedTypes.SpreadProperty.check(property)) {
  1391. addPattern(propertyPath.get('argument'), bindings);
  1392. }
  1393. });
  1394. }
  1395. else if (namedTypes.ArrayPattern &&
  1396. namedTypes.ArrayPattern.check(pattern)) {
  1397. patternPath.get('elements').each(function (elementPath) {
  1398. var element = elementPath.value;
  1399. if (namedTypes.Pattern.check(element)) {
  1400. addPattern(elementPath, bindings);
  1401. }
  1402. else if (namedTypes.SpreadElement &&
  1403. namedTypes.SpreadElement.check(element)) {
  1404. addPattern(elementPath.get("argument"), bindings);
  1405. }
  1406. });
  1407. }
  1408. else if (namedTypes.PropertyPattern &&
  1409. namedTypes.PropertyPattern.check(pattern)) {
  1410. addPattern(patternPath.get('pattern'), bindings);
  1411. }
  1412. else if ((namedTypes.SpreadElementPattern &&
  1413. namedTypes.SpreadElementPattern.check(pattern)) ||
  1414. (namedTypes.SpreadPropertyPattern &&
  1415. namedTypes.SpreadPropertyPattern.check(pattern))) {
  1416. addPattern(patternPath.get('argument'), bindings);
  1417. }
  1418. }
  1419. function addTypePattern(patternPath, types) {
  1420. var pattern = patternPath.value;
  1421. namedTypes.Pattern.assert(pattern);
  1422. if (namedTypes.Identifier.check(pattern)) {
  1423. if (hasOwn.call(types, pattern.name)) {
  1424. types[pattern.name].push(patternPath);
  1425. }
  1426. else {
  1427. types[pattern.name] = [patternPath];
  1428. }
  1429. }
  1430. }
  1431. Sp.lookup = function (name) {
  1432. for (var scope = this; scope; scope = scope.parent)
  1433. if (scope.declares(name))
  1434. break;
  1435. return scope;
  1436. };
  1437. Sp.lookupType = function (name) {
  1438. for (var scope = this; scope; scope = scope.parent)
  1439. if (scope.declaresType(name))
  1440. break;
  1441. return scope;
  1442. };
  1443. Sp.getGlobalScope = function () {
  1444. var scope = this;
  1445. while (!scope.isGlobal)
  1446. scope = scope.parent;
  1447. return scope;
  1448. };
  1449. return Scope;
  1450. }
  1451. exports.default = scopePlugin;
  1452. module.exports = exports["default"];
  1453. });
  1454. unwrapExports(scope);
  1455. var nodePath = createCommonjsModule(function (module, exports) {
  1456. var __importDefault = (this && this.__importDefault) || function (mod) {
  1457. return (mod && mod.__esModule) ? mod : { "default": mod };
  1458. };
  1459. Object.defineProperty(exports, "__esModule", { value: true });
  1460. var types_1 = __importDefault(types);
  1461. var path_1 = __importDefault(path);
  1462. var scope_1 = __importDefault(scope);
  1463. function nodePathPlugin(fork) {
  1464. var types = fork.use(types_1.default);
  1465. var n = types.namedTypes;
  1466. var b = types.builders;
  1467. var isNumber = types.builtInTypes.number;
  1468. var isArray = types.builtInTypes.array;
  1469. var Path = fork.use(path_1.default);
  1470. var Scope = fork.use(scope_1.default);
  1471. var NodePath = function NodePath(value, parentPath, name) {
  1472. if (!(this instanceof NodePath)) {
  1473. throw new Error("NodePath constructor cannot be invoked without 'new'");
  1474. }
  1475. Path.call(this, value, parentPath, name);
  1476. };
  1477. var NPp = NodePath.prototype = Object.create(Path.prototype, {
  1478. constructor: {
  1479. value: NodePath,
  1480. enumerable: false,
  1481. writable: true,
  1482. configurable: true
  1483. }
  1484. });
  1485. Object.defineProperties(NPp, {
  1486. node: {
  1487. get: function () {
  1488. Object.defineProperty(this, "node", {
  1489. configurable: true,
  1490. value: this._computeNode()
  1491. });
  1492. return this.node;
  1493. }
  1494. },
  1495. parent: {
  1496. get: function () {
  1497. Object.defineProperty(this, "parent", {
  1498. configurable: true,
  1499. value: this._computeParent()
  1500. });
  1501. return this.parent;
  1502. }
  1503. },
  1504. scope: {
  1505. get: function () {
  1506. Object.defineProperty(this, "scope", {
  1507. configurable: true,
  1508. value: this._computeScope()
  1509. });
  1510. return this.scope;
  1511. }
  1512. }
  1513. });
  1514. NPp.replace = function () {
  1515. delete this.node;
  1516. delete this.parent;
  1517. delete this.scope;
  1518. return Path.prototype.replace.apply(this, arguments);
  1519. };
  1520. NPp.prune = function () {
  1521. var remainingNodePath = this.parent;
  1522. this.replace();
  1523. return cleanUpNodesAfterPrune(remainingNodePath);
  1524. };
  1525. // The value of the first ancestor Path whose value is a Node.
  1526. NPp._computeNode = function () {
  1527. var value = this.value;
  1528. if (n.Node.check(value)) {
  1529. return value;
  1530. }
  1531. var pp = this.parentPath;
  1532. return pp && pp.node || null;
  1533. };
  1534. // The first ancestor Path whose value is a Node distinct from this.node.
  1535. NPp._computeParent = function () {
  1536. var value = this.value;
  1537. var pp = this.parentPath;
  1538. if (!n.Node.check(value)) {
  1539. while (pp && !n.Node.check(pp.value)) {
  1540. pp = pp.parentPath;
  1541. }
  1542. if (pp) {
  1543. pp = pp.parentPath;
  1544. }
  1545. }
  1546. while (pp && !n.Node.check(pp.value)) {
  1547. pp = pp.parentPath;
  1548. }
  1549. return pp || null;
  1550. };
  1551. // The closest enclosing scope that governs this node.
  1552. NPp._computeScope = function () {
  1553. var value = this.value;
  1554. var pp = this.parentPath;
  1555. var scope = pp && pp.scope;
  1556. if (n.Node.check(value) &&
  1557. Scope.isEstablishedBy(value)) {
  1558. scope = new Scope(this, scope);
  1559. }
  1560. return scope || null;
  1561. };
  1562. NPp.getValueProperty = function (name) {
  1563. return types.getFieldValue(this.value, name);
  1564. };
  1565. /**
  1566. * Determine whether this.node needs to be wrapped in parentheses in order
  1567. * for a parser to reproduce the same local AST structure.
  1568. *
  1569. * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression
  1570. * whose operator is "+" needs parentheses, because `1 + 2 * 3` would
  1571. * parse differently.
  1572. *
  1573. * If assumeExpressionContext === true, we don't worry about edge cases
  1574. * like an anonymous FunctionExpression appearing lexically first in its
  1575. * enclosing statement and thus needing parentheses to avoid being parsed
  1576. * as a FunctionDeclaration with a missing name.
  1577. */
  1578. NPp.needsParens = function (assumeExpressionContext) {
  1579. var pp = this.parentPath;
  1580. if (!pp) {
  1581. return false;
  1582. }
  1583. var node = this.value;
  1584. // Only expressions need parentheses.
  1585. if (!n.Expression.check(node)) {
  1586. return false;
  1587. }
  1588. // Identifiers never need parentheses.
  1589. if (node.type === "Identifier") {
  1590. return false;
  1591. }
  1592. while (!n.Node.check(pp.value)) {
  1593. pp = pp.parentPath;
  1594. if (!pp) {
  1595. return false;
  1596. }
  1597. }
  1598. var parent = pp.value;
  1599. switch (node.type) {
  1600. case "UnaryExpression":
  1601. case "SpreadElement":
  1602. case "SpreadProperty":
  1603. return parent.type === "MemberExpression"
  1604. && this.name === "object"
  1605. && parent.object === node;
  1606. case "BinaryExpression":
  1607. case "LogicalExpression":
  1608. switch (parent.type) {
  1609. case "CallExpression":
  1610. return this.name === "callee"
  1611. && parent.callee === node;
  1612. case "UnaryExpression":
  1613. case "SpreadElement":
  1614. case "SpreadProperty":
  1615. return true;
  1616. case "MemberExpression":
  1617. return this.name === "object"
  1618. && parent.object === node;
  1619. case "BinaryExpression":
  1620. case "LogicalExpression": {
  1621. var n_1 = node;
  1622. var po = parent.operator;
  1623. var pp_1 = PRECEDENCE[po];
  1624. var no = n_1.operator;
  1625. var np = PRECEDENCE[no];
  1626. if (pp_1 > np) {
  1627. return true;
  1628. }
  1629. if (pp_1 === np && this.name === "right") {
  1630. if (parent.right !== n_1) {
  1631. throw new Error("Nodes must be equal");
  1632. }
  1633. return true;
  1634. }
  1635. }
  1636. default:
  1637. return false;
  1638. }
  1639. case "SequenceExpression":
  1640. switch (parent.type) {
  1641. case "ForStatement":
  1642. // Although parentheses wouldn't hurt around sequence
  1643. // expressions in the head of for loops, traditional style
  1644. // dictates that e.g. i++, j++ should not be wrapped with
  1645. // parentheses.
  1646. return false;
  1647. case "ExpressionStatement":
  1648. return this.name !== "expression";
  1649. default:
  1650. // Otherwise err on the side of overparenthesization, adding
  1651. // explicit exceptions above if this proves overzealous.
  1652. return true;
  1653. }
  1654. case "YieldExpression":
  1655. switch (parent.type) {
  1656. case "BinaryExpression":
  1657. case "LogicalExpression":
  1658. case "UnaryExpression":
  1659. case "SpreadElement":
  1660. case "SpreadProperty":
  1661. case "CallExpression":
  1662. case "MemberExpression":
  1663. case "NewExpression":
  1664. case "ConditionalExpression":
  1665. case "YieldExpression":
  1666. return true;
  1667. default:
  1668. return false;
  1669. }
  1670. case "Literal":
  1671. return parent.type === "MemberExpression"
  1672. && isNumber.check(node.value)
  1673. && this.name === "object"
  1674. && parent.object === node;
  1675. case "AssignmentExpression":
  1676. case "ConditionalExpression":
  1677. switch (parent.type) {
  1678. case "UnaryExpression":
  1679. case "SpreadElement":
  1680. case "SpreadProperty":
  1681. case "BinaryExpression":
  1682. case "LogicalExpression":
  1683. return true;
  1684. case "CallExpression":
  1685. return this.name === "callee"
  1686. && parent.callee === node;
  1687. case "ConditionalExpression":
  1688. return this.name === "test"
  1689. && parent.test === node;
  1690. case "MemberExpression":
  1691. return this.name === "object"
  1692. && parent.object === node;
  1693. default:
  1694. return false;
  1695. }
  1696. default:
  1697. if (parent.type === "NewExpression" &&
  1698. this.name === "callee" &&
  1699. parent.callee === node) {
  1700. return containsCallExpression(node);
  1701. }
  1702. }
  1703. if (assumeExpressionContext !== true &&
  1704. !this.canBeFirstInStatement() &&
  1705. this.firstInStatement())
  1706. return true;
  1707. return false;
  1708. };
  1709. function isBinary(node) {
  1710. return n.BinaryExpression.check(node)
  1711. || n.LogicalExpression.check(node);
  1712. }
  1713. var PRECEDENCE = {};
  1714. [["||"],
  1715. ["&&"],
  1716. ["|"],
  1717. ["^"],
  1718. ["&"],
  1719. ["==", "===", "!=", "!=="],
  1720. ["<", ">", "<=", ">=", "in", "instanceof"],
  1721. [">>", "<<", ">>>"],
  1722. ["+", "-"],
  1723. ["*", "/", "%"]
  1724. ].forEach(function (tier, i) {
  1725. tier.forEach(function (op) {
  1726. PRECEDENCE[op] = i;
  1727. });
  1728. });
  1729. function containsCallExpression(node) {
  1730. if (n.CallExpression.check(node)) {
  1731. return true;
  1732. }
  1733. if (isArray.check(node)) {
  1734. return node.some(containsCallExpression);
  1735. }
  1736. if (n.Node.check(node)) {
  1737. return types.someField(node, function (_name, child) {
  1738. return containsCallExpression(child);
  1739. });
  1740. }
  1741. return false;
  1742. }
  1743. NPp.canBeFirstInStatement = function () {
  1744. var node = this.node;
  1745. return !n.FunctionExpression.check(node)
  1746. && !n.ObjectExpression.check(node);
  1747. };
  1748. NPp.firstInStatement = function () {
  1749. return firstInStatement(this);
  1750. };
  1751. function firstInStatement(path) {
  1752. for (var node, parent; path.parent; path = path.parent) {
  1753. node = path.node;
  1754. parent = path.parent.node;
  1755. if (n.BlockStatement.check(parent) &&
  1756. path.parent.name === "body" &&
  1757. path.name === 0) {
  1758. if (parent.body[0] !== node) {
  1759. throw new Error("Nodes must be equal");
  1760. }
  1761. return true;
  1762. }
  1763. if (n.ExpressionStatement.check(parent) &&
  1764. path.name === "expression") {
  1765. if (parent.expression !== node) {
  1766. throw new Error("Nodes must be equal");
  1767. }
  1768. return true;
  1769. }
  1770. if (n.SequenceExpression.check(parent) &&
  1771. path.parent.name === "expressions" &&
  1772. path.name === 0) {
  1773. if (parent.expressions[0] !== node) {
  1774. throw new Error("Nodes must be equal");
  1775. }
  1776. continue;
  1777. }
  1778. if (n.CallExpression.check(parent) &&
  1779. path.name === "callee") {
  1780. if (parent.callee !== node) {
  1781. throw new Error("Nodes must be equal");
  1782. }
  1783. continue;
  1784. }
  1785. if (n.MemberExpression.check(parent) &&
  1786. path.name === "object") {
  1787. if (parent.object !== node) {
  1788. throw new Error("Nodes must be equal");
  1789. }
  1790. continue;
  1791. }
  1792. if (n.ConditionalExpression.check(parent) &&
  1793. path.name === "test") {
  1794. if (parent.test !== node) {
  1795. throw new Error("Nodes must be equal");
  1796. }
  1797. continue;
  1798. }
  1799. if (isBinary(parent) &&
  1800. path.name === "left") {
  1801. if (parent.left !== node) {
  1802. throw new Error("Nodes must be equal");
  1803. }
  1804. continue;
  1805. }
  1806. if (n.UnaryExpression.check(parent) &&
  1807. !parent.prefix &&
  1808. path.name === "argument") {
  1809. if (parent.argument !== node) {
  1810. throw new Error("Nodes must be equal");
  1811. }
  1812. continue;
  1813. }
  1814. return false;
  1815. }
  1816. return true;
  1817. }
  1818. /**
  1819. * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up.
  1820. */
  1821. function cleanUpNodesAfterPrune(remainingNodePath) {
  1822. if (n.VariableDeclaration.check(remainingNodePath.node)) {
  1823. var declarations = remainingNodePath.get('declarations').value;
  1824. if (!declarations || declarations.length === 0) {
  1825. return remainingNodePath.prune();
  1826. }
  1827. }
  1828. else if (n.ExpressionStatement.check(remainingNodePath.node)) {
  1829. if (!remainingNodePath.get('expression').value) {
  1830. return remainingNodePath.prune();
  1831. }
  1832. }
  1833. else if (n.IfStatement.check(remainingNodePath.node)) {
  1834. cleanUpIfStatementAfterPrune(remainingNodePath);
  1835. }
  1836. return remainingNodePath;
  1837. }
  1838. function cleanUpIfStatementAfterPrune(ifStatement) {
  1839. var testExpression = ifStatement.get('test').value;
  1840. var alternate = ifStatement.get('alternate').value;
  1841. var consequent = ifStatement.get('consequent').value;
  1842. if (!consequent && !alternate) {
  1843. var testExpressionStatement = b.expressionStatement(testExpression);
  1844. ifStatement.replace(testExpressionStatement);
  1845. }
  1846. else if (!consequent && alternate) {
  1847. var negatedTestExpression = b.unaryExpression('!', testExpression, true);
  1848. if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') {
  1849. negatedTestExpression = testExpression.argument;
  1850. }
  1851. ifStatement.get("test").replace(negatedTestExpression);
  1852. ifStatement.get("consequent").replace(alternate);
  1853. ifStatement.get("alternate").replace();
  1854. }
  1855. }
  1856. return NodePath;
  1857. }
  1858. exports.default = nodePathPlugin;
  1859. module.exports = exports["default"];
  1860. });
  1861. unwrapExports(nodePath);
  1862. var pathVisitor = createCommonjsModule(function (module, exports) {
  1863. var __importDefault = (this && this.__importDefault) || function (mod) {
  1864. return (mod && mod.__esModule) ? mod : { "default": mod };
  1865. };
  1866. Object.defineProperty(exports, "__esModule", { value: true });
  1867. var types_1 = __importDefault(types);
  1868. var node_path_1 = __importDefault(nodePath);
  1869. var hasOwn = Object.prototype.hasOwnProperty;
  1870. function pathVisitorPlugin(fork) {
  1871. var types = fork.use(types_1.default);
  1872. var NodePath = fork.use(node_path_1.default);
  1873. var isArray = types.builtInTypes.array;
  1874. var isObject = types.builtInTypes.object;
  1875. var isFunction = types.builtInTypes.function;
  1876. var undefined$1;
  1877. var PathVisitor = function PathVisitor() {
  1878. if (!(this instanceof PathVisitor)) {
  1879. throw new Error("PathVisitor constructor cannot be invoked without 'new'");
  1880. }
  1881. // Permanent state.
  1882. this._reusableContextStack = [];
  1883. this._methodNameTable = computeMethodNameTable(this);
  1884. this._shouldVisitComments =
  1885. hasOwn.call(this._methodNameTable, "Block") ||
  1886. hasOwn.call(this._methodNameTable, "Line");
  1887. this.Context = makeContextConstructor(this);
  1888. // State reset every time PathVisitor.prototype.visit is called.
  1889. this._visiting = false;
  1890. this._changeReported = false;
  1891. };
  1892. function computeMethodNameTable(visitor) {
  1893. var typeNames = Object.create(null);
  1894. for (var methodName in visitor) {
  1895. if (/^visit[A-Z]/.test(methodName)) {
  1896. typeNames[methodName.slice("visit".length)] = true;
  1897. }
  1898. }
  1899. var supertypeTable = types.computeSupertypeLookupTable(typeNames);
  1900. var methodNameTable = Object.create(null);
  1901. var typeNameKeys = Object.keys(supertypeTable);
  1902. var typeNameCount = typeNameKeys.length;
  1903. for (var i = 0; i < typeNameCount; ++i) {
  1904. var typeName = typeNameKeys[i];
  1905. methodName = "visit" + supertypeTable[typeName];
  1906. if (isFunction.check(visitor[methodName])) {
  1907. methodNameTable[typeName] = methodName;
  1908. }
  1909. }
  1910. return methodNameTable;
  1911. }
  1912. PathVisitor.fromMethodsObject = function fromMethodsObject(methods) {
  1913. if (methods instanceof PathVisitor) {
  1914. return methods;
  1915. }
  1916. if (!isObject.check(methods)) {
  1917. // An empty visitor?
  1918. return new PathVisitor;
  1919. }
  1920. var Visitor = function Visitor() {
  1921. if (!(this instanceof Visitor)) {
  1922. throw new Error("Visitor constructor cannot be invoked without 'new'");
  1923. }
  1924. PathVisitor.call(this);
  1925. };
  1926. var Vp = Visitor.prototype = Object.create(PVp);
  1927. Vp.constructor = Visitor;
  1928. extend(Vp, methods);
  1929. extend(Visitor, PathVisitor);
  1930. isFunction.assert(Visitor.fromMethodsObject);
  1931. isFunction.assert(Visitor.visit);
  1932. return new Visitor;
  1933. };
  1934. function extend(target, source) {
  1935. for (var property in source) {
  1936. if (hasOwn.call(source, property)) {
  1937. target[property] = source[property];
  1938. }
  1939. }
  1940. return target;
  1941. }
  1942. PathVisitor.visit = function visit(node, methods) {
  1943. return PathVisitor.fromMethodsObject(methods).visit(node);
  1944. };
  1945. var PVp = PathVisitor.prototype;
  1946. PVp.visit = function () {
  1947. if (this._visiting) {
  1948. throw new Error("Recursively calling visitor.visit(path) resets visitor state. " +
  1949. "Try this.visit(path) or this.traverse(path) instead.");
  1950. }
  1951. // Private state that needs to be reset before every traversal.
  1952. this._visiting = true;
  1953. this._changeReported = false;
  1954. this._abortRequested = false;
  1955. var argc = arguments.length;
  1956. var args = new Array(argc);
  1957. for (var i = 0; i < argc; ++i) {
  1958. args[i] = arguments[i];
  1959. }
  1960. if (!(args[0] instanceof NodePath)) {
  1961. args[0] = new NodePath({ root: args[0] }).get("root");
  1962. }
  1963. // Called with the same arguments as .visit.
  1964. this.reset.apply(this, args);
  1965. var didNotThrow;
  1966. try {
  1967. var root = this.visitWithoutReset(args[0]);
  1968. didNotThrow = true;
  1969. }
  1970. finally {
  1971. this._visiting = false;
  1972. if (!didNotThrow && this._abortRequested) {
  1973. // If this.visitWithoutReset threw an exception and
  1974. // this._abortRequested was set to true, return the root of
  1975. // the AST instead of letting the exception propagate, so that
  1976. // client code does not have to provide a try-catch block to
  1977. // intercept the AbortRequest exception. Other kinds of
  1978. // exceptions will propagate without being intercepted and
  1979. // rethrown by a catch block, so their stacks will accurately
  1980. // reflect the original throwing context.
  1981. return args[0].value;
  1982. }
  1983. }
  1984. return root;
  1985. };
  1986. PVp.AbortRequest = function AbortRequest() { };
  1987. PVp.abort = function () {
  1988. var visitor = this;
  1989. visitor._abortRequested = true;
  1990. var request = new visitor.AbortRequest();
  1991. // If you decide to catch this exception and stop it from propagating,
  1992. // make sure to call its cancel method to avoid silencing other
  1993. // exceptions that might be thrown later in the traversal.
  1994. request.cancel = function () {
  1995. visitor._abortRequested = false;
  1996. };
  1997. throw request;
  1998. };
  1999. PVp.reset = function (_path /*, additional arguments */) {
  2000. // Empty stub; may be reassigned or overridden by subclasses.
  2001. };
  2002. PVp.visitWithoutReset = function (path) {
  2003. if (this instanceof this.Context) {
  2004. // Since this.Context.prototype === this, there's a chance we
  2005. // might accidentally call context.visitWithoutReset. If that
  2006. // happens, re-invoke the method against context.visitor.
  2007. return this.visitor.visitWithoutReset(path);
  2008. }
  2009. if (!(path instanceof NodePath)) {
  2010. throw new Error("");
  2011. }
  2012. var value = path.value;
  2013. var methodName = value &&
  2014. typeof value === "object" &&
  2015. typeof value.type === "string" &&
  2016. this._methodNameTable[value.type];
  2017. if (methodName) {
  2018. var context = this.acquireContext(path);
  2019. try {
  2020. return context.invokeVisitorMethod(methodName);
  2021. }
  2022. finally {
  2023. this.releaseContext(context);
  2024. }
  2025. }
  2026. else {
  2027. // If there was no visitor method to call, visit the children of
  2028. // this node generically.
  2029. return visitChildren(path, this);
  2030. }
  2031. };
  2032. function visitChildren(path, visitor) {
  2033. if (!(path instanceof NodePath)) {
  2034. throw new Error("");
  2035. }
  2036. if (!(visitor instanceof PathVisitor)) {
  2037. throw new Error("");
  2038. }
  2039. var value = path.value;
  2040. if (isArray.check(value)) {
  2041. path.each(visitor.visitWithoutReset, visitor);
  2042. }
  2043. else if (!isObject.check(value)) ;
  2044. else {
  2045. var childNames = types.getFieldNames(value);
  2046. // The .comments field of the Node type is hidden, so we only
  2047. // visit it if the visitor defines visitBlock or visitLine, and
  2048. // value.comments is defined.
  2049. if (visitor._shouldVisitComments &&
  2050. value.comments &&
  2051. childNames.indexOf("comments") < 0) {
  2052. childNames.push("comments");
  2053. }
  2054. var childCount = childNames.length;
  2055. var childPaths = [];
  2056. for (var i = 0; i < childCount; ++i) {
  2057. var childName = childNames[i];
  2058. if (!hasOwn.call(value, childName)) {
  2059. value[childName] = types.getFieldValue(value, childName);
  2060. }
  2061. childPaths.push(path.get(childName));
  2062. }
  2063. for (var i = 0; i < childCount; ++i) {
  2064. visitor.visitWithoutReset(childPaths[i]);
  2065. }
  2066. }
  2067. return path.value;
  2068. }
  2069. PVp.acquireContext = function (path) {
  2070. if (this._reusableContextStack.length === 0) {
  2071. return new this.Context(path);
  2072. }
  2073. return this._reusableContextStack.pop().reset(path);
  2074. };
  2075. PVp.releaseContext = function (context) {
  2076. if (!(context instanceof this.Context)) {
  2077. throw new Error("");
  2078. }
  2079. this._reusableContextStack.push(context);
  2080. context.currentPath = null;
  2081. };
  2082. PVp.reportChanged = function () {
  2083. this._changeReported = true;
  2084. };
  2085. PVp.wasChangeReported = function () {
  2086. return this._changeReported;
  2087. };
  2088. function makeContextConstructor(visitor) {
  2089. function Context(path) {
  2090. if (!(this instanceof Context)) {
  2091. throw new Error("");
  2092. }
  2093. if (!(this instanceof PathVisitor)) {
  2094. throw new Error("");
  2095. }
  2096. if (!(path instanceof NodePath)) {
  2097. throw new Error("");
  2098. }
  2099. Object.defineProperty(this, "visitor", {
  2100. value: visitor,
  2101. writable: false,
  2102. enumerable: true,
  2103. configurable: false
  2104. });
  2105. this.currentPath = path;
  2106. this.needToCallTraverse = true;
  2107. Object.seal(this);
  2108. }
  2109. if (!(visitor instanceof PathVisitor)) {
  2110. throw new Error("");
  2111. }
  2112. // Note that the visitor object is the prototype of Context.prototype,
  2113. // so all visitor methods are inherited by context objects.
  2114. var Cp = Context.prototype = Object.create(visitor);
  2115. Cp.constructor = Context;
  2116. extend(Cp, sharedContextProtoMethods);
  2117. return Context;
  2118. }
  2119. // Every PathVisitor has a different this.Context constructor and
  2120. // this.Context.prototype object, but those prototypes can all use the
  2121. // same reset, invokeVisitorMethod, and traverse function objects.
  2122. var sharedContextProtoMethods = Object.create(null);
  2123. sharedContextProtoMethods.reset =
  2124. function reset(path) {
  2125. if (!(this instanceof this.Context)) {
  2126. throw new Error("");
  2127. }
  2128. if (!(path instanceof NodePath)) {
  2129. throw new Error("");
  2130. }
  2131. this.currentPath = path;
  2132. this.needToCallTraverse = true;
  2133. return this;
  2134. };
  2135. sharedContextProtoMethods.invokeVisitorMethod =
  2136. function invokeVisitorMethod(methodName) {
  2137. if (!(this instanceof this.Context)) {
  2138. throw new Error("");
  2139. }
  2140. if (!(this.currentPath instanceof NodePath)) {
  2141. throw new Error("");
  2142. }
  2143. var result = this.visitor[methodName].call(this, this.currentPath);
  2144. if (result === false) {
  2145. // Visitor methods return false to indicate that they have handled
  2146. // their own traversal needs, and we should not complain if
  2147. // this.needToCallTraverse is still true.
  2148. this.needToCallTraverse = false;
  2149. }
  2150. else if (result !== undefined$1) {
  2151. // Any other non-undefined value returned from the visitor method
  2152. // is interpreted as a replacement value.
  2153. this.currentPath = this.currentPath.replace(result)[0];
  2154. if (this.needToCallTraverse) {
  2155. // If this.traverse still hasn't been called, visit the
  2156. // children of the replacement node.
  2157. this.traverse(this.currentPath);
  2158. }
  2159. }
  2160. if (this.needToCallTraverse !== false) {
  2161. throw new Error("Must either call this.traverse or return false in " + methodName);
  2162. }
  2163. var path = this.currentPath;
  2164. return path && path.value;
  2165. };
  2166. sharedContextProtoMethods.traverse =
  2167. function traverse(path, newVisitor) {
  2168. if (!(this instanceof this.Context)) {
  2169. throw new Error("");
  2170. }
  2171. if (!(path instanceof NodePath)) {
  2172. throw new Error("");
  2173. }
  2174. if (!(this.currentPath instanceof NodePath)) {
  2175. throw new Error("");
  2176. }
  2177. this.needToCallTraverse = false;
  2178. return visitChildren(path, PathVisitor.fromMethodsObject(newVisitor || this.visitor));
  2179. };
  2180. sharedContextProtoMethods.visit =
  2181. function visit(path, newVisitor) {
  2182. if (!(this instanceof this.Context)) {
  2183. throw new Error("");
  2184. }
  2185. if (!(path instanceof NodePath)) {
  2186. throw new Error("");
  2187. }
  2188. if (!(this.currentPath instanceof NodePath)) {
  2189. throw new Error("");
  2190. }
  2191. this.needToCallTraverse = false;
  2192. return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path);
  2193. };
  2194. sharedContextProtoMethods.reportChanged = function reportChanged() {
  2195. this.visitor.reportChanged();
  2196. };
  2197. sharedContextProtoMethods.abort = function abort() {
  2198. this.needToCallTraverse = false;
  2199. this.visitor.abort();
  2200. };
  2201. return PathVisitor;
  2202. }
  2203. exports.default = pathVisitorPlugin;
  2204. module.exports = exports["default"];
  2205. });
  2206. unwrapExports(pathVisitor);
  2207. var equiv = createCommonjsModule(function (module, exports) {
  2208. var __importDefault = (this && this.__importDefault) || function (mod) {
  2209. return (mod && mod.__esModule) ? mod : { "default": mod };
  2210. };
  2211. Object.defineProperty(exports, "__esModule", { value: true });
  2212. var types_1 = __importDefault(types);
  2213. function default_1(fork) {
  2214. var types = fork.use(types_1.default);
  2215. var getFieldNames = types.getFieldNames;
  2216. var getFieldValue = types.getFieldValue;
  2217. var isArray = types.builtInTypes.array;
  2218. var isObject = types.builtInTypes.object;
  2219. var isDate = types.builtInTypes.Date;
  2220. var isRegExp = types.builtInTypes.RegExp;
  2221. var hasOwn = Object.prototype.hasOwnProperty;
  2222. function astNodesAreEquivalent(a, b, problemPath) {
  2223. if (isArray.check(problemPath)) {
  2224. problemPath.length = 0;
  2225. }
  2226. else {
  2227. problemPath = null;
  2228. }
  2229. return areEquivalent(a, b, problemPath);
  2230. }
  2231. astNodesAreEquivalent.assert = function (a, b) {
  2232. var problemPath = [];
  2233. if (!astNodesAreEquivalent(a, b, problemPath)) {
  2234. if (problemPath.length === 0) {
  2235. if (a !== b) {
  2236. throw new Error("Nodes must be equal");
  2237. }
  2238. }
  2239. else {
  2240. throw new Error("Nodes differ in the following path: " +
  2241. problemPath.map(subscriptForProperty).join(""));
  2242. }
  2243. }
  2244. };
  2245. function subscriptForProperty(property) {
  2246. if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
  2247. return "." + property;
  2248. }
  2249. return "[" + JSON.stringify(property) + "]";
  2250. }
  2251. function areEquivalent(a, b, problemPath) {
  2252. if (a === b) {
  2253. return true;
  2254. }
  2255. if (isArray.check(a)) {
  2256. return arraysAreEquivalent(a, b, problemPath);
  2257. }
  2258. if (isObject.check(a)) {
  2259. return objectsAreEquivalent(a, b, problemPath);
  2260. }
  2261. if (isDate.check(a)) {
  2262. return isDate.check(b) && (+a === +b);
  2263. }
  2264. if (isRegExp.check(a)) {
  2265. return isRegExp.check(b) && (a.source === b.source &&
  2266. a.global === b.global &&
  2267. a.multiline === b.multiline &&
  2268. a.ignoreCase === b.ignoreCase);
  2269. }
  2270. return a == b;
  2271. }
  2272. function arraysAreEquivalent(a, b, problemPath) {
  2273. isArray.assert(a);
  2274. var aLength = a.length;
  2275. if (!isArray.check(b) || b.length !== aLength) {
  2276. if (problemPath) {
  2277. problemPath.push("length");
  2278. }
  2279. return false;
  2280. }
  2281. for (var i = 0; i < aLength; ++i) {
  2282. if (problemPath) {
  2283. problemPath.push(i);
  2284. }
  2285. if (i in a !== i in b) {
  2286. return false;
  2287. }
  2288. if (!areEquivalent(a[i], b[i], problemPath)) {
  2289. return false;
  2290. }
  2291. if (problemPath) {
  2292. var problemPathTail = problemPath.pop();
  2293. if (problemPathTail !== i) {
  2294. throw new Error("" + problemPathTail);
  2295. }
  2296. }
  2297. }
  2298. return true;
  2299. }
  2300. function objectsAreEquivalent(a, b, problemPath) {
  2301. isObject.assert(a);
  2302. if (!isObject.check(b)) {
  2303. return false;
  2304. }
  2305. // Fast path for a common property of AST nodes.
  2306. if (a.type !== b.type) {
  2307. if (problemPath) {
  2308. problemPath.push("type");
  2309. }
  2310. return false;
  2311. }
  2312. var aNames = getFieldNames(a);
  2313. var aNameCount = aNames.length;
  2314. var bNames = getFieldNames(b);
  2315. var bNameCount = bNames.length;
  2316. if (aNameCount === bNameCount) {
  2317. for (var i = 0; i < aNameCount; ++i) {
  2318. var name = aNames[i];
  2319. var aChild = getFieldValue(a, name);
  2320. var bChild = getFieldValue(b, name);
  2321. if (problemPath) {
  2322. problemPath.push(name);
  2323. }
  2324. if (!areEquivalent(aChild, bChild, problemPath)) {
  2325. return false;
  2326. }
  2327. if (problemPath) {
  2328. var problemPathTail = problemPath.pop();
  2329. if (problemPathTail !== name) {
  2330. throw new Error("" + problemPathTail);
  2331. }
  2332. }
  2333. }
  2334. return true;
  2335. }
  2336. if (!problemPath) {
  2337. return false;
  2338. }
  2339. // Since aNameCount !== bNameCount, we need to find some name that's
  2340. // missing in aNames but present in bNames, or vice-versa.
  2341. var seenNames = Object.create(null);
  2342. for (i = 0; i < aNameCount; ++i) {
  2343. seenNames[aNames[i]] = true;
  2344. }
  2345. for (i = 0; i < bNameCount; ++i) {
  2346. name = bNames[i];
  2347. if (!hasOwn.call(seenNames, name)) {
  2348. problemPath.push(name);
  2349. return false;
  2350. }
  2351. delete seenNames[name];
  2352. }
  2353. for (name in seenNames) {
  2354. problemPath.push(name);
  2355. break;
  2356. }
  2357. return false;
  2358. }
  2359. return astNodesAreEquivalent;
  2360. }
  2361. exports.default = default_1;
  2362. module.exports = exports["default"];
  2363. });
  2364. unwrapExports(equiv);
  2365. var fork = createCommonjsModule(function (module, exports) {
  2366. var __importDefault = (this && this.__importDefault) || function (mod) {
  2367. return (mod && mod.__esModule) ? mod : { "default": mod };
  2368. };
  2369. Object.defineProperty(exports, "__esModule", { value: true });
  2370. var types_1 = __importDefault(types);
  2371. var path_visitor_1 = __importDefault(pathVisitor);
  2372. var equiv_1 = __importDefault(equiv);
  2373. var path_1 = __importDefault(path);
  2374. var node_path_1 = __importDefault(nodePath);
  2375. function default_1(defs) {
  2376. var fork = createFork();
  2377. var types = fork.use(types_1.default);
  2378. defs.forEach(fork.use);
  2379. types.finalize();
  2380. var PathVisitor = fork.use(path_visitor_1.default);
  2381. return {
  2382. Type: types.Type,
  2383. builtInTypes: types.builtInTypes,
  2384. namedTypes: types.namedTypes,
  2385. builders: types.builders,
  2386. defineMethod: types.defineMethod,
  2387. getFieldNames: types.getFieldNames,
  2388. getFieldValue: types.getFieldValue,
  2389. eachField: types.eachField,
  2390. someField: types.someField,
  2391. getSupertypeNames: types.getSupertypeNames,
  2392. getBuilderName: types.getBuilderName,
  2393. astNodesAreEquivalent: fork.use(equiv_1.default),
  2394. finalize: types.finalize,
  2395. Path: fork.use(path_1.default),
  2396. NodePath: fork.use(node_path_1.default),
  2397. PathVisitor: PathVisitor,
  2398. use: fork.use,
  2399. visit: PathVisitor.visit,
  2400. };
  2401. }
  2402. exports.default = default_1;
  2403. function createFork() {
  2404. var used = [];
  2405. var usedResult = [];
  2406. function use(plugin) {
  2407. var idx = used.indexOf(plugin);
  2408. if (idx === -1) {
  2409. idx = used.length;
  2410. used.push(plugin);
  2411. usedResult[idx] = plugin(fork);
  2412. }
  2413. return usedResult[idx];
  2414. }
  2415. var fork = { use: use };
  2416. return fork;
  2417. }
  2418. module.exports = exports["default"];
  2419. });
  2420. unwrapExports(fork);
  2421. var shared = createCommonjsModule(function (module, exports) {
  2422. var __importDefault = (this && this.__importDefault) || function (mod) {
  2423. return (mod && mod.__esModule) ? mod : { "default": mod };
  2424. };
  2425. Object.defineProperty(exports, "__esModule", { value: true });
  2426. var types_1 = __importDefault(types);
  2427. function default_1(fork) {
  2428. var types = fork.use(types_1.default);
  2429. var Type = types.Type;
  2430. var builtin = types.builtInTypes;
  2431. var isNumber = builtin.number;
  2432. // An example of constructing a new type with arbitrary constraints from
  2433. // an existing type.
  2434. function geq(than) {
  2435. return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than);
  2436. }
  2437. // Default value-returning functions that may optionally be passed as a
  2438. // third argument to Def.prototype.field.
  2439. var defaults = {
  2440. // Functions were used because (among other reasons) that's the most
  2441. // elegant way to allow for the emptyArray one always to give a new
  2442. // array instance.
  2443. "null": function () { return null; },
  2444. "emptyArray": function () { return []; },
  2445. "false": function () { return false; },
  2446. "true": function () { return true; },
  2447. "undefined": function () { },
  2448. "use strict": function () { return "use strict"; }
  2449. };
  2450. var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined);
  2451. var isPrimitive = Type.from(function (value) {
  2452. if (value === null)
  2453. return true;
  2454. var type = typeof value;
  2455. if (type === "object" ||
  2456. type === "function") {
  2457. return false;
  2458. }
  2459. return true;
  2460. }, naiveIsPrimitive.toString());
  2461. return {
  2462. geq: geq,
  2463. defaults: defaults,
  2464. isPrimitive: isPrimitive,
  2465. };
  2466. }
  2467. exports.default = default_1;
  2468. module.exports = exports["default"];
  2469. });
  2470. unwrapExports(shared);
  2471. var core = createCommonjsModule(function (module, exports) {
  2472. var __importDefault = (this && this.__importDefault) || function (mod) {
  2473. return (mod && mod.__esModule) ? mod : { "default": mod };
  2474. };
  2475. Object.defineProperty(exports, "__esModule", { value: true });
  2476. var types_1 = __importDefault(types);
  2477. var shared_1 = __importDefault(shared);
  2478. function default_1(fork) {
  2479. var types = fork.use(types_1.default);
  2480. var Type = types.Type;
  2481. var def = Type.def;
  2482. var or = Type.or;
  2483. var shared = fork.use(shared_1.default);
  2484. var defaults = shared.defaults;
  2485. var geq = shared.geq;
  2486. // Abstract supertype of all syntactic entities that are allowed to have a
  2487. // .loc field.
  2488. def("Printable")
  2489. .field("loc", or(def("SourceLocation"), null), defaults["null"], true);
  2490. def("Node")
  2491. .bases("Printable")
  2492. .field("type", String)
  2493. .field("comments", or([def("Comment")], null), defaults["null"], true);
  2494. def("SourceLocation")
  2495. .field("start", def("Position"))
  2496. .field("end", def("Position"))
  2497. .field("source", or(String, null), defaults["null"]);
  2498. def("Position")
  2499. .field("line", geq(1))
  2500. .field("column", geq(0));
  2501. def("File")
  2502. .bases("Node")
  2503. .build("program", "name")
  2504. .field("program", def("Program"))
  2505. .field("name", or(String, null), defaults["null"]);
  2506. def("Program")
  2507. .bases("Node")
  2508. .build("body")
  2509. .field("body", [def("Statement")]);
  2510. def("Function")
  2511. .bases("Node")
  2512. .field("id", or(def("Identifier"), null), defaults["null"])
  2513. .field("params", [def("Pattern")])
  2514. .field("body", def("BlockStatement"))
  2515. .field("generator", Boolean, defaults["false"])
  2516. .field("async", Boolean, defaults["false"]);
  2517. def("Statement").bases("Node");
  2518. // The empty .build() here means that an EmptyStatement can be constructed
  2519. // (i.e. it's not abstract) but that it needs no arguments.
  2520. def("EmptyStatement").bases("Statement").build();
  2521. def("BlockStatement")
  2522. .bases("Statement")
  2523. .build("body")
  2524. .field("body", [def("Statement")]);
  2525. // TODO Figure out how to silently coerce Expressions to
  2526. // ExpressionStatements where a Statement was expected.
  2527. def("ExpressionStatement")
  2528. .bases("Statement")
  2529. .build("expression")
  2530. .field("expression", def("Expression"));
  2531. def("IfStatement")
  2532. .bases("Statement")
  2533. .build("test", "consequent", "alternate")
  2534. .field("test", def("Expression"))
  2535. .field("consequent", def("Statement"))
  2536. .field("alternate", or(def("Statement"), null), defaults["null"]);
  2537. def("LabeledStatement")
  2538. .bases("Statement")
  2539. .build("label", "body")
  2540. .field("label", def("Identifier"))
  2541. .field("body", def("Statement"));
  2542. def("BreakStatement")
  2543. .bases("Statement")
  2544. .build("label")
  2545. .field("label", or(def("Identifier"), null), defaults["null"]);
  2546. def("ContinueStatement")
  2547. .bases("Statement")
  2548. .build("label")
  2549. .field("label", or(def("Identifier"), null), defaults["null"]);
  2550. def("WithStatement")
  2551. .bases("Statement")
  2552. .build("object", "body")
  2553. .field("object", def("Expression"))
  2554. .field("body", def("Statement"));
  2555. def("SwitchStatement")
  2556. .bases("Statement")
  2557. .build("discriminant", "cases", "lexical")
  2558. .field("discriminant", def("Expression"))
  2559. .field("cases", [def("SwitchCase")])
  2560. .field("lexical", Boolean, defaults["false"]);
  2561. def("ReturnStatement")
  2562. .bases("Statement")
  2563. .build("argument")
  2564. .field("argument", or(def("Expression"), null));
  2565. def("ThrowStatement")
  2566. .bases("Statement")
  2567. .build("argument")
  2568. .field("argument", def("Expression"));
  2569. def("TryStatement")
  2570. .bases("Statement")
  2571. .build("block", "handler", "finalizer")
  2572. .field("block", def("BlockStatement"))
  2573. .field("handler", or(def("CatchClause"), null), function () {
  2574. return this.handlers && this.handlers[0] || null;
  2575. })
  2576. .field("handlers", [def("CatchClause")], function () {
  2577. return this.handler ? [this.handler] : [];
  2578. }, true) // Indicates this field is hidden from eachField iteration.
  2579. .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray)
  2580. .field("finalizer", or(def("BlockStatement"), null), defaults["null"]);
  2581. def("CatchClause")
  2582. .bases("Node")
  2583. .build("param", "guard", "body")
  2584. // https://github.com/tc39/proposal-optional-catch-binding
  2585. .field("param", or(def("Pattern"), null), defaults["null"])
  2586. .field("guard", or(def("Expression"), null), defaults["null"])
  2587. .field("body", def("BlockStatement"));
  2588. def("WhileStatement")
  2589. .bases("Statement")
  2590. .build("test", "body")
  2591. .field("test", def("Expression"))
  2592. .field("body", def("Statement"));
  2593. def("DoWhileStatement")
  2594. .bases("Statement")
  2595. .build("body", "test")
  2596. .field("body", def("Statement"))
  2597. .field("test", def("Expression"));
  2598. def("ForStatement")
  2599. .bases("Statement")
  2600. .build("init", "test", "update", "body")
  2601. .field("init", or(def("VariableDeclaration"), def("Expression"), null))
  2602. .field("test", or(def("Expression"), null))
  2603. .field("update", or(def("Expression"), null))
  2604. .field("body", def("Statement"));
  2605. def("ForInStatement")
  2606. .bases("Statement")
  2607. .build("left", "right", "body")
  2608. .field("left", or(def("VariableDeclaration"), def("Expression")))
  2609. .field("right", def("Expression"))
  2610. .field("body", def("Statement"));
  2611. def("DebuggerStatement").bases("Statement").build();
  2612. def("Declaration").bases("Statement");
  2613. def("FunctionDeclaration")
  2614. .bases("Function", "Declaration")
  2615. .build("id", "params", "body")
  2616. .field("id", def("Identifier"));
  2617. def("FunctionExpression")
  2618. .bases("Function", "Expression")
  2619. .build("id", "params", "body");
  2620. def("VariableDeclaration")
  2621. .bases("Declaration")
  2622. .build("kind", "declarations")
  2623. .field("kind", or("var", "let", "const"))
  2624. .field("declarations", [def("VariableDeclarator")]);
  2625. def("VariableDeclarator")
  2626. .bases("Node")
  2627. .build("id", "init")
  2628. .field("id", def("Pattern"))
  2629. .field("init", or(def("Expression"), null), defaults["null"]);
  2630. def("Expression").bases("Node");
  2631. def("ThisExpression").bases("Expression").build();
  2632. def("ArrayExpression")
  2633. .bases("Expression")
  2634. .build("elements")
  2635. .field("elements", [or(def("Expression"), null)]);
  2636. def("ObjectExpression")
  2637. .bases("Expression")
  2638. .build("properties")
  2639. .field("properties", [def("Property")]);
  2640. // TODO Not in the Mozilla Parser API, but used by Esprima.
  2641. def("Property")
  2642. .bases("Node") // Want to be able to visit Property Nodes.
  2643. .build("kind", "key", "value")
  2644. .field("kind", or("init", "get", "set"))
  2645. .field("key", or(def("Literal"), def("Identifier")))
  2646. .field("value", def("Expression"));
  2647. def("SequenceExpression")
  2648. .bases("Expression")
  2649. .build("expressions")
  2650. .field("expressions", [def("Expression")]);
  2651. var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete");
  2652. def("UnaryExpression")
  2653. .bases("Expression")
  2654. .build("operator", "argument", "prefix")
  2655. .field("operator", UnaryOperator)
  2656. .field("argument", def("Expression"))
  2657. // Esprima doesn't bother with this field, presumably because it's
  2658. // always true for unary operators.
  2659. .field("prefix", Boolean, defaults["true"]);
  2660. var BinaryOperator = or("==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "**", "&", // TODO Missing from the Parser API.
  2661. "|", "^", "in", "instanceof");
  2662. def("BinaryExpression")
  2663. .bases("Expression")
  2664. .build("operator", "left", "right")
  2665. .field("operator", BinaryOperator)
  2666. .field("left", def("Expression"))
  2667. .field("right", def("Expression"));
  2668. var AssignmentOperator = or("=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=");
  2669. def("AssignmentExpression")
  2670. .bases("Expression")
  2671. .build("operator", "left", "right")
  2672. .field("operator", AssignmentOperator)
  2673. .field("left", or(def("Pattern"), def("MemberExpression")))
  2674. .field("right", def("Expression"));
  2675. var UpdateOperator = or("++", "--");
  2676. def("UpdateExpression")
  2677. .bases("Expression")
  2678. .build("operator", "argument", "prefix")
  2679. .field("operator", UpdateOperator)
  2680. .field("argument", def("Expression"))
  2681. .field("prefix", Boolean);
  2682. var LogicalOperator = or("||", "&&");
  2683. def("LogicalExpression")
  2684. .bases("Expression")
  2685. .build("operator", "left", "right")
  2686. .field("operator", LogicalOperator)
  2687. .field("left", def("Expression"))
  2688. .field("right", def("Expression"));
  2689. def("ConditionalExpression")
  2690. .bases("Expression")
  2691. .build("test", "consequent", "alternate")
  2692. .field("test", def("Expression"))
  2693. .field("consequent", def("Expression"))
  2694. .field("alternate", def("Expression"));
  2695. def("NewExpression")
  2696. .bases("Expression")
  2697. .build("callee", "arguments")
  2698. .field("callee", def("Expression"))
  2699. // The Mozilla Parser API gives this type as [or(def("Expression"),
  2700. // null)], but null values don't really make sense at the call site.
  2701. // TODO Report this nonsense.
  2702. .field("arguments", [def("Expression")]);
  2703. def("CallExpression")
  2704. .bases("Expression")
  2705. .build("callee", "arguments")
  2706. .field("callee", def("Expression"))
  2707. // See comment for NewExpression above.
  2708. .field("arguments", [def("Expression")]);
  2709. def("MemberExpression")
  2710. .bases("Expression")
  2711. .build("object", "property", "computed")
  2712. .field("object", def("Expression"))
  2713. .field("property", or(def("Identifier"), def("Expression")))
  2714. .field("computed", Boolean, function () {
  2715. var type = this.property.type;
  2716. if (type === 'Literal' ||
  2717. type === 'MemberExpression' ||
  2718. type === 'BinaryExpression') {
  2719. return true;
  2720. }
  2721. return false;
  2722. });
  2723. def("Pattern").bases("Node");
  2724. def("SwitchCase")
  2725. .bases("Node")
  2726. .build("test", "consequent")
  2727. .field("test", or(def("Expression"), null))
  2728. .field("consequent", [def("Statement")]);
  2729. def("Identifier")
  2730. .bases("Expression", "Pattern")
  2731. .build("name")
  2732. .field("name", String)
  2733. .field("optional", Boolean, defaults["false"]);
  2734. def("Literal")
  2735. .bases("Expression")
  2736. .build("value")
  2737. .field("value", or(String, Boolean, null, Number, RegExp))
  2738. .field("regex", or({
  2739. pattern: String,
  2740. flags: String
  2741. }, null), function () {
  2742. if (this.value instanceof RegExp) {
  2743. var flags = "";
  2744. if (this.value.ignoreCase)
  2745. flags += "i";
  2746. if (this.value.multiline)
  2747. flags += "m";
  2748. if (this.value.global)
  2749. flags += "g";
  2750. return {
  2751. pattern: this.value.source,
  2752. flags: flags
  2753. };
  2754. }
  2755. return null;
  2756. });
  2757. // Abstract (non-buildable) comment supertype. Not a Node.
  2758. def("Comment")
  2759. .bases("Printable")
  2760. .field("value", String)
  2761. // A .leading comment comes before the node, whereas a .trailing
  2762. // comment comes after it. These two fields should not both be true,
  2763. // but they might both be false when the comment falls inside a node
  2764. // and the node has no children for the comment to lead or trail,
  2765. // e.g. { /*dangling*/ }.
  2766. .field("leading", Boolean, defaults["true"])
  2767. .field("trailing", Boolean, defaults["false"]);
  2768. }
  2769. exports.default = default_1;
  2770. module.exports = exports["default"];
  2771. });
  2772. unwrapExports(core);
  2773. var es6 = createCommonjsModule(function (module, exports) {
  2774. var __importDefault = (this && this.__importDefault) || function (mod) {
  2775. return (mod && mod.__esModule) ? mod : { "default": mod };
  2776. };
  2777. Object.defineProperty(exports, "__esModule", { value: true });
  2778. var core_1 = __importDefault(core);
  2779. var types_1 = __importDefault(types);
  2780. var shared_1 = __importDefault(shared);
  2781. function default_1(fork) {
  2782. fork.use(core_1.default);
  2783. var types = fork.use(types_1.default);
  2784. var def = types.Type.def;
  2785. var or = types.Type.or;
  2786. var defaults = fork.use(shared_1.default).defaults;
  2787. def("Function")
  2788. .field("generator", Boolean, defaults["false"])
  2789. .field("expression", Boolean, defaults["false"])
  2790. .field("defaults", [or(def("Expression"), null)], defaults.emptyArray)
  2791. // TODO This could be represented as a RestElement in .params.
  2792. .field("rest", or(def("Identifier"), null), defaults["null"]);
  2793. // The ESTree way of representing a ...rest parameter.
  2794. def("RestElement")
  2795. .bases("Pattern")
  2796. .build("argument")
  2797. .field("argument", def("Pattern"))
  2798. .field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier
  2799. or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]);
  2800. def("SpreadElementPattern")
  2801. .bases("Pattern")
  2802. .build("argument")
  2803. .field("argument", def("Pattern"));
  2804. def("FunctionDeclaration")
  2805. .build("id", "params", "body", "generator", "expression");
  2806. def("FunctionExpression")
  2807. .build("id", "params", "body", "generator", "expression");
  2808. // The Parser API calls this ArrowExpression, but Esprima and all other
  2809. // actual parsers use ArrowFunctionExpression.
  2810. def("ArrowFunctionExpression")
  2811. .bases("Function", "Expression")
  2812. .build("params", "body", "expression")
  2813. // The forced null value here is compatible with the overridden
  2814. // definition of the "id" field in the Function interface.
  2815. .field("id", null, defaults["null"])
  2816. // Arrow function bodies are allowed to be expressions.
  2817. .field("body", or(def("BlockStatement"), def("Expression")))
  2818. // The current spec forbids arrow generators, so I have taken the
  2819. // liberty of enforcing that. TODO Report this.
  2820. .field("generator", false, defaults["false"]);
  2821. def("ForOfStatement")
  2822. .bases("Statement")
  2823. .build("left", "right", "body")
  2824. .field("left", or(def("VariableDeclaration"), def("Pattern")))
  2825. .field("right", def("Expression"))
  2826. .field("body", def("Statement"));
  2827. def("YieldExpression")
  2828. .bases("Expression")
  2829. .build("argument", "delegate")
  2830. .field("argument", or(def("Expression"), null))
  2831. .field("delegate", Boolean, defaults["false"]);
  2832. def("GeneratorExpression")
  2833. .bases("Expression")
  2834. .build("body", "blocks", "filter")
  2835. .field("body", def("Expression"))
  2836. .field("blocks", [def("ComprehensionBlock")])
  2837. .field("filter", or(def("Expression"), null));
  2838. def("ComprehensionExpression")
  2839. .bases("Expression")
  2840. .build("body", "blocks", "filter")
  2841. .field("body", def("Expression"))
  2842. .field("blocks", [def("ComprehensionBlock")])
  2843. .field("filter", or(def("Expression"), null));
  2844. def("ComprehensionBlock")
  2845. .bases("Node")
  2846. .build("left", "right", "each")
  2847. .field("left", def("Pattern"))
  2848. .field("right", def("Expression"))
  2849. .field("each", Boolean);
  2850. def("Property")
  2851. .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
  2852. .field("value", or(def("Expression"), def("Pattern")))
  2853. .field("method", Boolean, defaults["false"])
  2854. .field("shorthand", Boolean, defaults["false"])
  2855. .field("computed", Boolean, defaults["false"]);
  2856. def("ObjectProperty")
  2857. .field("shorthand", Boolean, defaults["false"]);
  2858. def("PropertyPattern")
  2859. .bases("Pattern")
  2860. .build("key", "pattern")
  2861. .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
  2862. .field("pattern", def("Pattern"))
  2863. .field("computed", Boolean, defaults["false"]);
  2864. def("ObjectPattern")
  2865. .bases("Pattern")
  2866. .build("properties")
  2867. .field("properties", [or(def("PropertyPattern"), def("Property"))]);
  2868. def("ArrayPattern")
  2869. .bases("Pattern")
  2870. .build("elements")
  2871. .field("elements", [or(def("Pattern"), null)]);
  2872. def("MethodDefinition")
  2873. .bases("Declaration")
  2874. .build("kind", "key", "value", "static")
  2875. .field("kind", or("constructor", "method", "get", "set"))
  2876. .field("key", def("Expression"))
  2877. .field("value", def("Function"))
  2878. .field("computed", Boolean, defaults["false"])
  2879. .field("static", Boolean, defaults["false"]);
  2880. def("SpreadElement")
  2881. .bases("Node")
  2882. .build("argument")
  2883. .field("argument", def("Expression"));
  2884. def("ArrayExpression")
  2885. .field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]);
  2886. def("NewExpression")
  2887. .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
  2888. def("CallExpression")
  2889. .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
  2890. // Note: this node type is *not* an AssignmentExpression with a Pattern on
  2891. // the left-hand side! The existing AssignmentExpression type already
  2892. // supports destructuring assignments. AssignmentPattern nodes may appear
  2893. // wherever a Pattern is allowed, and the right-hand side represents a
  2894. // default value to be destructured against the left-hand side, if no
  2895. // value is otherwise provided. For example: default parameter values.
  2896. def("AssignmentPattern")
  2897. .bases("Pattern")
  2898. .build("left", "right")
  2899. .field("left", def("Pattern"))
  2900. .field("right", def("Expression"));
  2901. var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"));
  2902. def("ClassProperty")
  2903. .bases("Declaration")
  2904. .build("key")
  2905. .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
  2906. .field("computed", Boolean, defaults["false"]);
  2907. def("ClassPropertyDefinition") // static property
  2908. .bases("Declaration")
  2909. .build("definition")
  2910. // Yes, Virginia, circular definitions are permitted.
  2911. .field("definition", ClassBodyElement);
  2912. def("ClassBody")
  2913. .bases("Declaration")
  2914. .build("body")
  2915. .field("body", [ClassBodyElement]);
  2916. def("ClassDeclaration")
  2917. .bases("Declaration")
  2918. .build("id", "body", "superClass")
  2919. .field("id", or(def("Identifier"), null))
  2920. .field("body", def("ClassBody"))
  2921. .field("superClass", or(def("Expression"), null), defaults["null"]);
  2922. def("ClassExpression")
  2923. .bases("Expression")
  2924. .build("id", "body", "superClass")
  2925. .field("id", or(def("Identifier"), null), defaults["null"])
  2926. .field("body", def("ClassBody"))
  2927. .field("superClass", or(def("Expression"), null), defaults["null"]);
  2928. // Specifier and ModuleSpecifier are abstract non-standard types
  2929. // introduced for definitional convenience.
  2930. def("Specifier").bases("Node");
  2931. // This supertype is shared/abused by both def/babel.js and
  2932. // def/esprima.js. In the future, it will be possible to load only one set
  2933. // of definitions appropriate for a given parser, but until then we must
  2934. // rely on default functions to reconcile the conflicting AST formats.
  2935. def("ModuleSpecifier")
  2936. .bases("Specifier")
  2937. // This local field is used by Babel/Acorn. It should not technically
  2938. // be optional in the Babel/Acorn AST format, but it must be optional
  2939. // in the Esprima AST format.
  2940. .field("local", or(def("Identifier"), null), defaults["null"])
  2941. // The id and name fields are used by Esprima. The id field should not
  2942. // technically be optional in the Esprima AST format, but it must be
  2943. // optional in the Babel/Acorn AST format.
  2944. .field("id", or(def("Identifier"), null), defaults["null"])
  2945. .field("name", or(def("Identifier"), null), defaults["null"]);
  2946. // Like ModuleSpecifier, except type:"ImportSpecifier" and buildable.
  2947. // import {<id [as name]>} from ...;
  2948. def("ImportSpecifier")
  2949. .bases("ModuleSpecifier")
  2950. .build("id", "name");
  2951. // import <* as id> from ...;
  2952. def("ImportNamespaceSpecifier")
  2953. .bases("ModuleSpecifier")
  2954. .build("id");
  2955. // import <id> from ...;
  2956. def("ImportDefaultSpecifier")
  2957. .bases("ModuleSpecifier")
  2958. .build("id");
  2959. def("ImportDeclaration")
  2960. .bases("Declaration")
  2961. .build("specifiers", "source", "importKind")
  2962. .field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray)
  2963. .field("source", def("Literal"))
  2964. .field("importKind", or("value", "type"), function () {
  2965. return "value";
  2966. });
  2967. def("TaggedTemplateExpression")
  2968. .bases("Expression")
  2969. .build("tag", "quasi")
  2970. .field("tag", def("Expression"))
  2971. .field("quasi", def("TemplateLiteral"));
  2972. def("TemplateLiteral")
  2973. .bases("Expression")
  2974. .build("quasis", "expressions")
  2975. .field("quasis", [def("TemplateElement")])
  2976. .field("expressions", [def("Expression")]);
  2977. def("TemplateElement")
  2978. .bases("Node")
  2979. .build("value", "tail")
  2980. .field("value", { "cooked": String, "raw": String })
  2981. .field("tail", Boolean);
  2982. }
  2983. exports.default = default_1;
  2984. module.exports = exports["default"];
  2985. });
  2986. unwrapExports(es6);
  2987. var es7 = createCommonjsModule(function (module, exports) {
  2988. var __importDefault = (this && this.__importDefault) || function (mod) {
  2989. return (mod && mod.__esModule) ? mod : { "default": mod };
  2990. };
  2991. Object.defineProperty(exports, "__esModule", { value: true });
  2992. var es6_1 = __importDefault(es6);
  2993. var types_1 = __importDefault(types);
  2994. var shared_1 = __importDefault(shared);
  2995. function default_1(fork) {
  2996. fork.use(es6_1.default);
  2997. var types = fork.use(types_1.default);
  2998. var def = types.Type.def;
  2999. var or = types.Type.or;
  3000. var defaults = fork.use(shared_1.default).defaults;
  3001. def("Function")
  3002. .field("async", Boolean, defaults["false"]);
  3003. def("SpreadProperty")
  3004. .bases("Node")
  3005. .build("argument")
  3006. .field("argument", def("Expression"));
  3007. def("ObjectExpression")
  3008. .field("properties", [or(def("Property"), def("SpreadProperty"), def("SpreadElement"))]);
  3009. def("SpreadPropertyPattern")
  3010. .bases("Pattern")
  3011. .build("argument")
  3012. .field("argument", def("Pattern"));
  3013. def("ObjectPattern")
  3014. .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"))]);
  3015. def("AwaitExpression")
  3016. .bases("Expression")
  3017. .build("argument", "all")
  3018. .field("argument", or(def("Expression"), null))
  3019. .field("all", Boolean, defaults["false"]);
  3020. }
  3021. exports.default = default_1;
  3022. module.exports = exports["default"];
  3023. });
  3024. unwrapExports(es7);
  3025. var jsx = createCommonjsModule(function (module, exports) {
  3026. var __importDefault = (this && this.__importDefault) || function (mod) {
  3027. return (mod && mod.__esModule) ? mod : { "default": mod };
  3028. };
  3029. Object.defineProperty(exports, "__esModule", { value: true });
  3030. var es7_1 = __importDefault(es7);
  3031. var types_1 = __importDefault(types);
  3032. var shared_1 = __importDefault(shared);
  3033. function default_1(fork) {
  3034. fork.use(es7_1.default);
  3035. var types = fork.use(types_1.default);
  3036. var def = types.Type.def;
  3037. var or = types.Type.or;
  3038. var defaults = fork.use(shared_1.default).defaults;
  3039. def("JSXAttribute")
  3040. .bases("Node")
  3041. .build("name", "value")
  3042. .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName")))
  3043. .field("value", or(def("Literal"), // attr="value"
  3044. def("JSXExpressionContainer"), // attr={value}
  3045. null // attr= or just attr
  3046. ), defaults["null"]);
  3047. def("JSXIdentifier")
  3048. .bases("Identifier")
  3049. .build("name")
  3050. .field("name", String);
  3051. def("JSXNamespacedName")
  3052. .bases("Node")
  3053. .build("namespace", "name")
  3054. .field("namespace", def("JSXIdentifier"))
  3055. .field("name", def("JSXIdentifier"));
  3056. def("JSXMemberExpression")
  3057. .bases("MemberExpression")
  3058. .build("object", "property")
  3059. .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression")))
  3060. .field("property", def("JSXIdentifier"))
  3061. .field("computed", Boolean, defaults.false);
  3062. var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression"));
  3063. def("JSXSpreadAttribute")
  3064. .bases("Node")
  3065. .build("argument")
  3066. .field("argument", def("Expression"));
  3067. var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))];
  3068. def("JSXExpressionContainer")
  3069. .bases("Expression")
  3070. .build("expression")
  3071. .field("expression", def("Expression"));
  3072. def("JSXElement")
  3073. .bases("Expression")
  3074. .build("openingElement", "closingElement", "children")
  3075. .field("openingElement", def("JSXOpeningElement"))
  3076. .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"])
  3077. .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead.
  3078. )], defaults.emptyArray)
  3079. .field("name", JSXElementName, function () {
  3080. // Little-known fact: the `this` object inside a default function
  3081. // is none other than the partially-built object itself, and any
  3082. // fields initialized directly from builder function arguments
  3083. // (like openingElement, closingElement, and children) are
  3084. // guaranteed to be available.
  3085. return this.openingElement.name;
  3086. }, true) // hidden from traversal
  3087. .field("selfClosing", Boolean, function () {
  3088. return this.openingElement.selfClosing;
  3089. }, true) // hidden from traversal
  3090. .field("attributes", JSXAttributes, function () {
  3091. return this.openingElement.attributes;
  3092. }, true); // hidden from traversal
  3093. def("JSXOpeningElement")
  3094. .bases("Node") // TODO Does this make sense? Can't really be an JSXElement.
  3095. .build("name", "attributes", "selfClosing")
  3096. .field("name", JSXElementName)
  3097. .field("attributes", JSXAttributes, defaults.emptyArray)
  3098. .field("selfClosing", Boolean, defaults["false"]);
  3099. def("JSXClosingElement")
  3100. .bases("Node") // TODO Same concern.
  3101. .build("name")
  3102. .field("name", JSXElementName);
  3103. def("JSXFragment")
  3104. .bases("Expression")
  3105. .build("openingElement", "closingElement", "children")
  3106. .field("openingElement", def("JSXOpeningFragment"))
  3107. .field("closingElement", def("JSXClosingFragment"))
  3108. .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead.
  3109. )], defaults.emptyArray);
  3110. def("JSXOpeningFragment")
  3111. .bases("Node") // TODO Same concern.
  3112. .build();
  3113. def("JSXClosingFragment")
  3114. .bases("Node") // TODO Same concern.
  3115. .build();
  3116. def("JSXText")
  3117. .bases("Literal")
  3118. .build("value")
  3119. .field("value", String);
  3120. def("JSXEmptyExpression").bases("Expression").build();
  3121. // This PR has caused many people issues, but supporting it seems like a
  3122. // good idea anyway: https://github.com/babel/babel/pull/4988
  3123. def("JSXSpreadChild")
  3124. .bases("Expression")
  3125. .build("expression")
  3126. .field("expression", def("Expression"));
  3127. }
  3128. exports.default = default_1;
  3129. module.exports = exports["default"];
  3130. });
  3131. unwrapExports(jsx);
  3132. var typeAnnotations = createCommonjsModule(function (module, exports) {
  3133. /**
  3134. * Type annotation defs shared between Flow and TypeScript.
  3135. * These defs could not be defined in ./flow.ts or ./typescript.ts directly
  3136. * because they use the same name.
  3137. */
  3138. var __importDefault = (this && this.__importDefault) || function (mod) {
  3139. return (mod && mod.__esModule) ? mod : { "default": mod };
  3140. };
  3141. Object.defineProperty(exports, "__esModule", { value: true });
  3142. var types_1 = __importDefault(types);
  3143. var shared_1 = __importDefault(shared);
  3144. function default_1(fork) {
  3145. var types = fork.use(types_1.default);
  3146. var def = types.Type.def;
  3147. var or = types.Type.or;
  3148. var defaults = fork.use(shared_1.default).defaults;
  3149. var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null);
  3150. var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null);
  3151. def("Identifier")
  3152. .field("typeAnnotation", TypeAnnotation, defaults["null"]);
  3153. def("ObjectPattern")
  3154. .field("typeAnnotation", TypeAnnotation, defaults["null"]);
  3155. def("Function")
  3156. .field("returnType", TypeAnnotation, defaults["null"])
  3157. .field("typeParameters", TypeParamDecl, defaults["null"]);
  3158. def("ClassProperty")
  3159. .build("key", "value", "typeAnnotation", "static")
  3160. .field("value", or(def("Expression"), null))
  3161. .field("static", Boolean, defaults["false"])
  3162. .field("typeAnnotation", TypeAnnotation, defaults["null"]);
  3163. ["ClassDeclaration",
  3164. "ClassExpression",
  3165. ].forEach(function (typeName) {
  3166. def(typeName)
  3167. .field("typeParameters", TypeParamDecl, defaults["null"])
  3168. .field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"])
  3169. .field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray);
  3170. });
  3171. }
  3172. exports.default = default_1;
  3173. module.exports = exports["default"];
  3174. });
  3175. unwrapExports(typeAnnotations);
  3176. var flow = createCommonjsModule(function (module, exports) {
  3177. var __importDefault = (this && this.__importDefault) || function (mod) {
  3178. return (mod && mod.__esModule) ? mod : { "default": mod };
  3179. };
  3180. Object.defineProperty(exports, "__esModule", { value: true });
  3181. var es7_1 = __importDefault(es7);
  3182. var type_annotations_1 = __importDefault(typeAnnotations);
  3183. var types_1 = __importDefault(types);
  3184. var shared_1 = __importDefault(shared);
  3185. function default_1(fork) {
  3186. fork.use(es7_1.default);
  3187. fork.use(type_annotations_1.default);
  3188. var types = fork.use(types_1.default);
  3189. var def = types.Type.def;
  3190. var or = types.Type.or;
  3191. var defaults = fork.use(shared_1.default).defaults;
  3192. // Base types
  3193. def("Flow").bases("Node");
  3194. def("FlowType").bases("Flow");
  3195. // Type annotations
  3196. def("AnyTypeAnnotation")
  3197. .bases("FlowType")
  3198. .build();
  3199. def("EmptyTypeAnnotation")
  3200. .bases("FlowType")
  3201. .build();
  3202. def("MixedTypeAnnotation")
  3203. .bases("FlowType")
  3204. .build();
  3205. def("VoidTypeAnnotation")
  3206. .bases("FlowType")
  3207. .build();
  3208. def("NumberTypeAnnotation")
  3209. .bases("FlowType")
  3210. .build();
  3211. def("NumberLiteralTypeAnnotation")
  3212. .bases("FlowType")
  3213. .build("value", "raw")
  3214. .field("value", Number)
  3215. .field("raw", String);
  3216. // Babylon 6 differs in AST from Flow
  3217. // same as NumberLiteralTypeAnnotation
  3218. def("NumericLiteralTypeAnnotation")
  3219. .bases("FlowType")
  3220. .build("value", "raw")
  3221. .field("value", Number)
  3222. .field("raw", String);
  3223. def("StringTypeAnnotation")
  3224. .bases("FlowType")
  3225. .build();
  3226. def("StringLiteralTypeAnnotation")
  3227. .bases("FlowType")
  3228. .build("value", "raw")
  3229. .field("value", String)
  3230. .field("raw", String);
  3231. def("BooleanTypeAnnotation")
  3232. .bases("FlowType")
  3233. .build();
  3234. def("BooleanLiteralTypeAnnotation")
  3235. .bases("FlowType")
  3236. .build("value", "raw")
  3237. .field("value", Boolean)
  3238. .field("raw", String);
  3239. def("TypeAnnotation")
  3240. .bases("Node")
  3241. .build("typeAnnotation")
  3242. .field("typeAnnotation", def("FlowType"));
  3243. def("NullableTypeAnnotation")
  3244. .bases("FlowType")
  3245. .build("typeAnnotation")
  3246. .field("typeAnnotation", def("FlowType"));
  3247. def("NullLiteralTypeAnnotation")
  3248. .bases("FlowType")
  3249. .build();
  3250. def("NullTypeAnnotation")
  3251. .bases("FlowType")
  3252. .build();
  3253. def("ThisTypeAnnotation")
  3254. .bases("FlowType")
  3255. .build();
  3256. def("ExistsTypeAnnotation")
  3257. .bases("FlowType")
  3258. .build();
  3259. def("ExistentialTypeParam")
  3260. .bases("FlowType")
  3261. .build();
  3262. def("FunctionTypeAnnotation")
  3263. .bases("FlowType")
  3264. .build("params", "returnType", "rest", "typeParameters")
  3265. .field("params", [def("FunctionTypeParam")])
  3266. .field("returnType", def("FlowType"))
  3267. .field("rest", or(def("FunctionTypeParam"), null))
  3268. .field("typeParameters", or(def("TypeParameterDeclaration"), null));
  3269. def("FunctionTypeParam")
  3270. .bases("Node")
  3271. .build("name", "typeAnnotation", "optional")
  3272. .field("name", def("Identifier"))
  3273. .field("typeAnnotation", def("FlowType"))
  3274. .field("optional", Boolean);
  3275. def("ArrayTypeAnnotation")
  3276. .bases("FlowType")
  3277. .build("elementType")
  3278. .field("elementType", def("FlowType"));
  3279. def("ObjectTypeAnnotation")
  3280. .bases("FlowType")
  3281. .build("properties", "indexers", "callProperties")
  3282. .field("properties", [
  3283. or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty"))
  3284. ])
  3285. .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
  3286. .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray)
  3287. .field("inexact", or(Boolean, void 0), defaults["undefined"])
  3288. .field("exact", Boolean, defaults["false"])
  3289. .field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray);
  3290. def("Variance")
  3291. .bases("Node")
  3292. .build("kind")
  3293. .field("kind", or("plus", "minus"));
  3294. var LegacyVariance = or(def("Variance"), "plus", "minus", null);
  3295. def("ObjectTypeProperty")
  3296. .bases("Node")
  3297. .build("key", "value", "optional")
  3298. .field("key", or(def("Literal"), def("Identifier")))
  3299. .field("value", def("FlowType"))
  3300. .field("optional", Boolean)
  3301. .field("variance", LegacyVariance, defaults["null"]);
  3302. def("ObjectTypeIndexer")
  3303. .bases("Node")
  3304. .build("id", "key", "value")
  3305. .field("id", def("Identifier"))
  3306. .field("key", def("FlowType"))
  3307. .field("value", def("FlowType"))
  3308. .field("variance", LegacyVariance, defaults["null"]);
  3309. def("ObjectTypeCallProperty")
  3310. .bases("Node")
  3311. .build("value")
  3312. .field("value", def("FunctionTypeAnnotation"))
  3313. .field("static", Boolean, defaults["false"]);
  3314. def("QualifiedTypeIdentifier")
  3315. .bases("Node")
  3316. .build("qualification", "id")
  3317. .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  3318. .field("id", def("Identifier"));
  3319. def("GenericTypeAnnotation")
  3320. .bases("FlowType")
  3321. .build("id", "typeParameters")
  3322. .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  3323. .field("typeParameters", or(def("TypeParameterInstantiation"), null));
  3324. def("MemberTypeAnnotation")
  3325. .bases("FlowType")
  3326. .build("object", "property")
  3327. .field("object", def("Identifier"))
  3328. .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation")));
  3329. def("UnionTypeAnnotation")
  3330. .bases("FlowType")
  3331. .build("types")
  3332. .field("types", [def("FlowType")]);
  3333. def("IntersectionTypeAnnotation")
  3334. .bases("FlowType")
  3335. .build("types")
  3336. .field("types", [def("FlowType")]);
  3337. def("TypeofTypeAnnotation")
  3338. .bases("FlowType")
  3339. .build("argument")
  3340. .field("argument", def("FlowType"));
  3341. def("ObjectTypeSpreadProperty")
  3342. .bases("Node")
  3343. .build("argument")
  3344. .field("argument", def("FlowType"));
  3345. def("ObjectTypeInternalSlot")
  3346. .bases("Node")
  3347. .build("id", "value", "optional", "static", "method")
  3348. .field("id", def("Identifier"))
  3349. .field("value", def("FlowType"))
  3350. .field("optional", Boolean)
  3351. .field("static", Boolean)
  3352. .field("method", Boolean);
  3353. def("TypeParameterDeclaration")
  3354. .bases("Node")
  3355. .build("params")
  3356. .field("params", [def("TypeParameter")]);
  3357. def("TypeParameterInstantiation")
  3358. .bases("Node")
  3359. .build("params")
  3360. .field("params", [def("FlowType")]);
  3361. def("TypeParameter")
  3362. .bases("FlowType")
  3363. .build("name", "variance", "bound")
  3364. .field("name", String)
  3365. .field("variance", LegacyVariance, defaults["null"])
  3366. .field("bound", or(def("TypeAnnotation"), null), defaults["null"]);
  3367. def("ClassProperty")
  3368. .field("variance", LegacyVariance, defaults["null"]);
  3369. def("ClassImplements")
  3370. .bases("Node")
  3371. .build("id")
  3372. .field("id", def("Identifier"))
  3373. .field("superClass", or(def("Expression"), null), defaults["null"])
  3374. .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
  3375. def("InterfaceTypeAnnotation")
  3376. .bases("FlowType")
  3377. .build("body", "extends")
  3378. .field("body", def("ObjectTypeAnnotation"))
  3379. .field("extends", or([def("InterfaceExtends")], null), defaults["null"]);
  3380. def("InterfaceDeclaration")
  3381. .bases("Declaration")
  3382. .build("id", "body", "extends")
  3383. .field("id", def("Identifier"))
  3384. .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"])
  3385. .field("body", def("ObjectTypeAnnotation"))
  3386. .field("extends", [def("InterfaceExtends")]);
  3387. def("DeclareInterface")
  3388. .bases("InterfaceDeclaration")
  3389. .build("id", "body", "extends");
  3390. def("InterfaceExtends")
  3391. .bases("Node")
  3392. .build("id")
  3393. .field("id", def("Identifier"))
  3394. .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
  3395. def("TypeAlias")
  3396. .bases("Declaration")
  3397. .build("id", "typeParameters", "right")
  3398. .field("id", def("Identifier"))
  3399. .field("typeParameters", or(def("TypeParameterDeclaration"), null))
  3400. .field("right", def("FlowType"));
  3401. def("OpaqueType")
  3402. .bases("Declaration")
  3403. .build("id", "typeParameters", "impltype", "supertype")
  3404. .field("id", def("Identifier"))
  3405. .field("typeParameters", or(def("TypeParameterDeclaration"), null))
  3406. .field("impltype", def("FlowType"))
  3407. .field("supertype", def("FlowType"));
  3408. def("DeclareTypeAlias")
  3409. .bases("TypeAlias")
  3410. .build("id", "typeParameters", "right");
  3411. def("DeclareOpaqueType")
  3412. .bases("TypeAlias")
  3413. .build("id", "typeParameters", "supertype");
  3414. def("TypeCastExpression")
  3415. .bases("Expression")
  3416. .build("expression", "typeAnnotation")
  3417. .field("expression", def("Expression"))
  3418. .field("typeAnnotation", def("TypeAnnotation"));
  3419. def("TupleTypeAnnotation")
  3420. .bases("FlowType")
  3421. .build("types")
  3422. .field("types", [def("FlowType")]);
  3423. def("DeclareVariable")
  3424. .bases("Statement")
  3425. .build("id")
  3426. .field("id", def("Identifier"));
  3427. def("DeclareFunction")
  3428. .bases("Statement")
  3429. .build("id")
  3430. .field("id", def("Identifier"));
  3431. def("DeclareClass")
  3432. .bases("InterfaceDeclaration")
  3433. .build("id");
  3434. def("DeclareModule")
  3435. .bases("Statement")
  3436. .build("id", "body")
  3437. .field("id", or(def("Identifier"), def("Literal")))
  3438. .field("body", def("BlockStatement"));
  3439. def("DeclareModuleExports")
  3440. .bases("Statement")
  3441. .build("typeAnnotation")
  3442. .field("typeAnnotation", def("TypeAnnotation"));
  3443. def("DeclareExportDeclaration")
  3444. .bases("Declaration")
  3445. .build("default", "declaration", "specifiers", "source")
  3446. .field("default", Boolean)
  3447. .field("declaration", or(def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("FlowType"), // Implies default.
  3448. null))
  3449. .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray)
  3450. .field("source", or(def("Literal"), null), defaults["null"]);
  3451. def("DeclareExportAllDeclaration")
  3452. .bases("Declaration")
  3453. .build("source")
  3454. .field("source", or(def("Literal"), null), defaults["null"]);
  3455. def("FlowPredicate").bases("Flow");
  3456. def("InferredPredicate")
  3457. .bases("FlowPredicate")
  3458. .build();
  3459. def("DeclaredPredicate")
  3460. .bases("FlowPredicate")
  3461. .build("value")
  3462. .field("value", def("Expression"));
  3463. def("CallExpression")
  3464. .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
  3465. def("NewExpression")
  3466. .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
  3467. }
  3468. exports.default = default_1;
  3469. module.exports = exports["default"];
  3470. });
  3471. unwrapExports(flow);
  3472. var esprima = createCommonjsModule(function (module, exports) {
  3473. var __importDefault = (this && this.__importDefault) || function (mod) {
  3474. return (mod && mod.__esModule) ? mod : { "default": mod };
  3475. };
  3476. Object.defineProperty(exports, "__esModule", { value: true });
  3477. var es7_1 = __importDefault(es7);
  3478. var types_1 = __importDefault(types);
  3479. var shared_1 = __importDefault(shared);
  3480. function default_1(fork) {
  3481. fork.use(es7_1.default);
  3482. var types = fork.use(types_1.default);
  3483. var defaults = fork.use(shared_1.default).defaults;
  3484. var def = types.Type.def;
  3485. var or = types.Type.or;
  3486. def("VariableDeclaration")
  3487. .field("declarations", [or(def("VariableDeclarator"), def("Identifier") // Esprima deviation.
  3488. )]);
  3489. def("Property")
  3490. .field("value", or(def("Expression"), def("Pattern") // Esprima deviation.
  3491. ));
  3492. def("ArrayPattern")
  3493. .field("elements", [or(def("Pattern"), def("SpreadElement"), null)]);
  3494. def("ObjectPattern")
  3495. .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty") // Used by Esprima.
  3496. )]);
  3497. // Like ModuleSpecifier, except type:"ExportSpecifier" and buildable.
  3498. // export {<id [as name]>} [from ...];
  3499. def("ExportSpecifier")
  3500. .bases("ModuleSpecifier")
  3501. .build("id", "name");
  3502. // export <*> from ...;
  3503. def("ExportBatchSpecifier")
  3504. .bases("Specifier")
  3505. .build();
  3506. def("ExportDeclaration")
  3507. .bases("Declaration")
  3508. .build("default", "declaration", "specifiers", "source")
  3509. .field("default", Boolean)
  3510. .field("declaration", or(def("Declaration"), def("Expression"), // Implies default.
  3511. null))
  3512. .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray)
  3513. .field("source", or(def("Literal"), null), defaults["null"]);
  3514. def("Block")
  3515. .bases("Comment")
  3516. .build("value", /*optional:*/ "leading", "trailing");
  3517. def("Line")
  3518. .bases("Comment")
  3519. .build("value", /*optional:*/ "leading", "trailing");
  3520. }
  3521. exports.default = default_1;
  3522. module.exports = exports["default"];
  3523. });
  3524. unwrapExports(esprima);
  3525. var babelCore = createCommonjsModule(function (module, exports) {
  3526. var __importDefault = (this && this.__importDefault) || function (mod) {
  3527. return (mod && mod.__esModule) ? mod : { "default": mod };
  3528. };
  3529. Object.defineProperty(exports, "__esModule", { value: true });
  3530. var types_1 = __importDefault(types);
  3531. var shared_1 = __importDefault(shared);
  3532. var es7_1 = __importDefault(es7);
  3533. function default_1(fork) {
  3534. fork.use(es7_1.default);
  3535. var types = fork.use(types_1.default);
  3536. var defaults = fork.use(shared_1.default).defaults;
  3537. var def = types.Type.def;
  3538. var or = types.Type.or;
  3539. def("Noop")
  3540. .bases("Statement")
  3541. .build();
  3542. def("DoExpression")
  3543. .bases("Expression")
  3544. .build("body")
  3545. .field("body", [def("Statement")]);
  3546. def("Super")
  3547. .bases("Expression")
  3548. .build();
  3549. def("BindExpression")
  3550. .bases("Expression")
  3551. .build("object", "callee")
  3552. .field("object", or(def("Expression"), null))
  3553. .field("callee", def("Expression"));
  3554. def("Decorator")
  3555. .bases("Node")
  3556. .build("expression")
  3557. .field("expression", def("Expression"));
  3558. def("Property")
  3559. .field("decorators", or([def("Decorator")], null), defaults["null"]);
  3560. def("MethodDefinition")
  3561. .field("decorators", or([def("Decorator")], null), defaults["null"]);
  3562. def("MetaProperty")
  3563. .bases("Expression")
  3564. .build("meta", "property")
  3565. .field("meta", def("Identifier"))
  3566. .field("property", def("Identifier"));
  3567. def("ParenthesizedExpression")
  3568. .bases("Expression")
  3569. .build("expression")
  3570. .field("expression", def("Expression"));
  3571. def("ImportSpecifier")
  3572. .bases("ModuleSpecifier")
  3573. .build("imported", "local")
  3574. .field("imported", def("Identifier"));
  3575. def("ImportDefaultSpecifier")
  3576. .bases("ModuleSpecifier")
  3577. .build("local");
  3578. def("ImportNamespaceSpecifier")
  3579. .bases("ModuleSpecifier")
  3580. .build("local");
  3581. def("ExportDefaultDeclaration")
  3582. .bases("Declaration")
  3583. .build("declaration")
  3584. .field("declaration", or(def("Declaration"), def("Expression")));
  3585. def("ExportNamedDeclaration")
  3586. .bases("Declaration")
  3587. .build("declaration", "specifiers", "source")
  3588. .field("declaration", or(def("Declaration"), null))
  3589. .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray)
  3590. .field("source", or(def("Literal"), null), defaults["null"]);
  3591. def("ExportSpecifier")
  3592. .bases("ModuleSpecifier")
  3593. .build("local", "exported")
  3594. .field("exported", def("Identifier"));
  3595. def("ExportNamespaceSpecifier")
  3596. .bases("Specifier")
  3597. .build("exported")
  3598. .field("exported", def("Identifier"));
  3599. def("ExportDefaultSpecifier")
  3600. .bases("Specifier")
  3601. .build("exported")
  3602. .field("exported", def("Identifier"));
  3603. def("ExportAllDeclaration")
  3604. .bases("Declaration")
  3605. .build("exported", "source")
  3606. .field("exported", or(def("Identifier"), null))
  3607. .field("source", def("Literal"));
  3608. def("CommentBlock")
  3609. .bases("Comment")
  3610. .build("value", /*optional:*/ "leading", "trailing");
  3611. def("CommentLine")
  3612. .bases("Comment")
  3613. .build("value", /*optional:*/ "leading", "trailing");
  3614. def("Directive")
  3615. .bases("Node")
  3616. .build("value")
  3617. .field("value", def("DirectiveLiteral"));
  3618. def("DirectiveLiteral")
  3619. .bases("Node", "Expression")
  3620. .build("value")
  3621. .field("value", String, defaults["use strict"]);
  3622. def("InterpreterDirective")
  3623. .bases("Node")
  3624. .build("value")
  3625. .field("value", String);
  3626. def("BlockStatement")
  3627. .bases("Statement")
  3628. .build("body")
  3629. .field("body", [def("Statement")])
  3630. .field("directives", [def("Directive")], defaults.emptyArray);
  3631. def("Program")
  3632. .bases("Node")
  3633. .build("body")
  3634. .field("body", [def("Statement")])
  3635. .field("directives", [def("Directive")], defaults.emptyArray)
  3636. .field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]);
  3637. // Split Literal
  3638. def("StringLiteral")
  3639. .bases("Literal")
  3640. .build("value")
  3641. .field("value", String);
  3642. def("NumericLiteral")
  3643. .bases("Literal")
  3644. .build("value")
  3645. .field("value", Number)
  3646. .field("raw", or(String, null), defaults["null"])
  3647. .field("extra", {
  3648. rawValue: Number,
  3649. raw: String
  3650. }, function getDefault() {
  3651. return {
  3652. rawValue: this.value,
  3653. raw: this.value + ""
  3654. };
  3655. });
  3656. def("BigIntLiteral")
  3657. .bases("Literal")
  3658. .build("value")
  3659. // Only String really seems appropriate here, since BigInt values
  3660. // often exceed the limits of JS numbers.
  3661. .field("value", or(String, Number))
  3662. .field("extra", {
  3663. rawValue: String,
  3664. raw: String
  3665. }, function getDefault() {
  3666. return {
  3667. rawValue: String(this.value),
  3668. raw: this.value + "n"
  3669. };
  3670. });
  3671. def("NullLiteral")
  3672. .bases("Literal")
  3673. .build()
  3674. .field("value", null, defaults["null"]);
  3675. def("BooleanLiteral")
  3676. .bases("Literal")
  3677. .build("value")
  3678. .field("value", Boolean);
  3679. def("RegExpLiteral")
  3680. .bases("Literal")
  3681. .build("pattern", "flags")
  3682. .field("pattern", String)
  3683. .field("flags", String)
  3684. .field("value", RegExp, function () {
  3685. return new RegExp(this.pattern, this.flags);
  3686. });
  3687. var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement"));
  3688. // Split Property -> ObjectProperty and ObjectMethod
  3689. def("ObjectExpression")
  3690. .bases("Expression")
  3691. .build("properties")
  3692. .field("properties", [ObjectExpressionProperty]);
  3693. // ObjectMethod hoist .value properties to own properties
  3694. def("ObjectMethod")
  3695. .bases("Node", "Function")
  3696. .build("kind", "key", "params", "body", "computed")
  3697. .field("kind", or("method", "get", "set"))
  3698. .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
  3699. .field("params", [def("Pattern")])
  3700. .field("body", def("BlockStatement"))
  3701. .field("computed", Boolean, defaults["false"])
  3702. .field("generator", Boolean, defaults["false"])
  3703. .field("async", Boolean, defaults["false"])
  3704. .field("accessibility", // TypeScript
  3705. or(def("Literal"), null), defaults["null"])
  3706. .field("decorators", or([def("Decorator")], null), defaults["null"]);
  3707. def("ObjectProperty")
  3708. .bases("Node")
  3709. .build("key", "value")
  3710. .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
  3711. .field("value", or(def("Expression"), def("Pattern")))
  3712. .field("accessibility", // TypeScript
  3713. or(def("Literal"), null), defaults["null"])
  3714. .field("computed", Boolean, defaults["false"]);
  3715. var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"));
  3716. // MethodDefinition -> ClassMethod
  3717. def("ClassBody")
  3718. .bases("Declaration")
  3719. .build("body")
  3720. .field("body", [ClassBodyElement]);
  3721. def("ClassMethod")
  3722. .bases("Declaration", "Function")
  3723. .build("kind", "key", "params", "body", "computed", "static")
  3724. .field("key", or(def("Literal"), def("Identifier"), def("Expression")));
  3725. def("ClassPrivateMethod")
  3726. .bases("Declaration", "Function")
  3727. .build("key", "params", "body", "kind", "computed", "static")
  3728. .field("key", def("PrivateName"));
  3729. ["ClassMethod",
  3730. "ClassPrivateMethod",
  3731. ].forEach(function (typeName) {
  3732. def(typeName)
  3733. .field("kind", or("get", "set", "method", "constructor"), function () { return "method"; })
  3734. .field("body", def("BlockStatement"))
  3735. .field("computed", Boolean, defaults["false"])
  3736. .field("static", or(Boolean, null), defaults["null"])
  3737. .field("abstract", or(Boolean, null), defaults["null"])
  3738. .field("access", or("public", "private", "protected", null), defaults["null"])
  3739. .field("accessibility", or("public", "private", "protected", null), defaults["null"])
  3740. .field("decorators", or([def("Decorator")], null), defaults["null"])
  3741. .field("optional", or(Boolean, null), defaults["null"]);
  3742. });
  3743. def("ClassPrivateProperty")
  3744. .bases("ClassProperty")
  3745. .build("key", "value")
  3746. .field("key", def("PrivateName"))
  3747. .field("value", or(def("Expression"), null), defaults["null"]);
  3748. def("PrivateName")
  3749. .bases("Expression", "Pattern")
  3750. .build("id")
  3751. .field("id", def("Identifier"));
  3752. var ObjectPatternProperty = or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty"), // Used by Esprima
  3753. def("ObjectProperty"), // Babel 6
  3754. def("RestProperty") // Babel 6
  3755. );
  3756. // Split into RestProperty and SpreadProperty
  3757. def("ObjectPattern")
  3758. .bases("Pattern")
  3759. .build("properties")
  3760. .field("properties", [ObjectPatternProperty])
  3761. .field("decorators", or([def("Decorator")], null), defaults["null"]);
  3762. def("SpreadProperty")
  3763. .bases("Node")
  3764. .build("argument")
  3765. .field("argument", def("Expression"));
  3766. def("RestProperty")
  3767. .bases("Node")
  3768. .build("argument")
  3769. .field("argument", def("Expression"));
  3770. def("ForAwaitStatement")
  3771. .bases("Statement")
  3772. .build("left", "right", "body")
  3773. .field("left", or(def("VariableDeclaration"), def("Expression")))
  3774. .field("right", def("Expression"))
  3775. .field("body", def("Statement"));
  3776. // The callee node of a dynamic import(...) expression.
  3777. def("Import")
  3778. .bases("Expression")
  3779. .build();
  3780. }
  3781. exports.default = default_1;
  3782. module.exports = exports["default"];
  3783. });
  3784. unwrapExports(babelCore);
  3785. var babel = createCommonjsModule(function (module, exports) {
  3786. var __importDefault = (this && this.__importDefault) || function (mod) {
  3787. return (mod && mod.__esModule) ? mod : { "default": mod };
  3788. };
  3789. Object.defineProperty(exports, "__esModule", { value: true });
  3790. var babel_core_1 = __importDefault(babelCore);
  3791. var flow_1 = __importDefault(flow);
  3792. function default_1(fork) {
  3793. fork.use(babel_core_1.default);
  3794. fork.use(flow_1.default);
  3795. }
  3796. exports.default = default_1;
  3797. module.exports = exports["default"];
  3798. });
  3799. unwrapExports(babel);
  3800. var typescript = createCommonjsModule(function (module, exports) {
  3801. var __importDefault = (this && this.__importDefault) || function (mod) {
  3802. return (mod && mod.__esModule) ? mod : { "default": mod };
  3803. };
  3804. Object.defineProperty(exports, "__esModule", { value: true });
  3805. var babel_core_1 = __importDefault(babelCore);
  3806. var type_annotations_1 = __importDefault(typeAnnotations);
  3807. var types_1 = __importDefault(types);
  3808. var shared_1 = __importDefault(shared);
  3809. function default_1(fork) {
  3810. // Since TypeScript is parsed by Babylon, include the core Babylon types
  3811. // but omit the Flow-related types.
  3812. fork.use(babel_core_1.default);
  3813. fork.use(type_annotations_1.default);
  3814. var types = fork.use(types_1.default);
  3815. var n = types.namedTypes;
  3816. var def = types.Type.def;
  3817. var or = types.Type.or;
  3818. var defaults = fork.use(shared_1.default).defaults;
  3819. var StringLiteral = types.Type.from(function (value, deep) {
  3820. if (n.StringLiteral &&
  3821. n.StringLiteral.check(value, deep)) {
  3822. return true;
  3823. }
  3824. if (n.Literal &&
  3825. n.Literal.check(value, deep) &&
  3826. typeof value.value === "string") {
  3827. return true;
  3828. }
  3829. return false;
  3830. }, "StringLiteral");
  3831. def("TSType")
  3832. .bases("Node");
  3833. var TSEntityName = or(def("Identifier"), def("TSQualifiedName"));
  3834. def("TSTypeReference")
  3835. .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
  3836. .build("typeName", "typeParameters")
  3837. .field("typeName", TSEntityName);
  3838. // An abstract (non-buildable) base type that provide a commonly-needed
  3839. // optional .typeParameters field.
  3840. def("TSHasOptionalTypeParameterInstantiation")
  3841. .field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]);
  3842. // An abstract (non-buildable) base type that provide a commonly-needed
  3843. // optional .typeParameters field.
  3844. def("TSHasOptionalTypeParameters")
  3845. .field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]);
  3846. // An abstract (non-buildable) base type that provide a commonly-needed
  3847. // optional .typeAnnotation field.
  3848. def("TSHasOptionalTypeAnnotation")
  3849. .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]);
  3850. def("TSQualifiedName")
  3851. .bases("Node")
  3852. .build("left", "right")
  3853. .field("left", TSEntityName)
  3854. .field("right", TSEntityName);
  3855. def("TSAsExpression")
  3856. .bases("Expression", "Pattern")
  3857. .build("expression", "typeAnnotation")
  3858. .field("expression", def("Expression"))
  3859. .field("typeAnnotation", def("TSType"))
  3860. .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
  3861. def("TSNonNullExpression")
  3862. .bases("Expression", "Pattern")
  3863. .build("expression")
  3864. .field("expression", def("Expression"));
  3865. [
  3866. "TSAnyKeyword",
  3867. "TSBigIntKeyword",
  3868. "TSBooleanKeyword",
  3869. "TSNeverKeyword",
  3870. "TSNullKeyword",
  3871. "TSNumberKeyword",
  3872. "TSObjectKeyword",
  3873. "TSStringKeyword",
  3874. "TSSymbolKeyword",
  3875. "TSUndefinedKeyword",
  3876. "TSUnknownKeyword",
  3877. "TSVoidKeyword",
  3878. "TSThisType",
  3879. ].forEach(function (keywordType) {
  3880. def(keywordType)
  3881. .bases("TSType")
  3882. .build();
  3883. });
  3884. def("TSArrayType")
  3885. .bases("TSType")
  3886. .build("elementType")
  3887. .field("elementType", def("TSType"));
  3888. def("TSLiteralType")
  3889. .bases("TSType")
  3890. .build("literal")
  3891. .field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression")));
  3892. ["TSUnionType",
  3893. "TSIntersectionType",
  3894. ].forEach(function (typeName) {
  3895. def(typeName)
  3896. .bases("TSType")
  3897. .build("types")
  3898. .field("types", [def("TSType")]);
  3899. });
  3900. def("TSConditionalType")
  3901. .bases("TSType")
  3902. .build("checkType", "extendsType", "trueType", "falseType")
  3903. .field("checkType", def("TSType"))
  3904. .field("extendsType", def("TSType"))
  3905. .field("trueType", def("TSType"))
  3906. .field("falseType", def("TSType"));
  3907. def("TSInferType")
  3908. .bases("TSType")
  3909. .build("typeParameter")
  3910. .field("typeParameter", def("TSTypeParameter"));
  3911. def("TSParenthesizedType")
  3912. .bases("TSType")
  3913. .build("typeAnnotation")
  3914. .field("typeAnnotation", def("TSType"));
  3915. var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))];
  3916. ["TSFunctionType",
  3917. "TSConstructorType",
  3918. ].forEach(function (typeName) {
  3919. def(typeName)
  3920. .bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
  3921. .build("parameters")
  3922. .field("parameters", ParametersType);
  3923. });
  3924. def("TSDeclareFunction")
  3925. .bases("Declaration", "TSHasOptionalTypeParameters")
  3926. .build("id", "params", "returnType")
  3927. .field("declare", Boolean, defaults["false"])
  3928. .field("async", Boolean, defaults["false"])
  3929. .field("generator", Boolean, defaults["false"])
  3930. .field("id", or(def("Identifier"), null), defaults["null"])
  3931. .field("params", [def("Pattern")])
  3932. // tSFunctionTypeAnnotationCommon
  3933. .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used?
  3934. null), defaults["null"]);
  3935. def("TSDeclareMethod")
  3936. .bases("Declaration", "TSHasOptionalTypeParameters")
  3937. .build("key", "params", "returnType")
  3938. .field("async", Boolean, defaults["false"])
  3939. .field("generator", Boolean, defaults["false"])
  3940. .field("params", [def("Pattern")])
  3941. // classMethodOrPropertyCommon
  3942. .field("abstract", Boolean, defaults["false"])
  3943. .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"])
  3944. .field("static", Boolean, defaults["false"])
  3945. .field("computed", Boolean, defaults["false"])
  3946. .field("optional", Boolean, defaults["false"])
  3947. .field("key", or(def("Identifier"), def("StringLiteral"), def("NumericLiteral"),
  3948. // Only allowed if .computed is true.
  3949. def("Expression")))
  3950. // classMethodOrDeclareMethodCommon
  3951. .field("kind", or("get", "set", "method", "constructor"), function getDefault() { return "method"; })
  3952. .field("access", // Not "accessibility"?
  3953. or("public", "private", "protected", void 0), defaults["undefined"])
  3954. .field("decorators", or([def("Decorator")], null), defaults["null"])
  3955. // tSFunctionTypeAnnotationCommon
  3956. .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used?
  3957. null), defaults["null"]);
  3958. def("TSMappedType")
  3959. .bases("TSType")
  3960. .build("typeParameter", "typeAnnotation")
  3961. .field("readonly", or(Boolean, "+", "-"), defaults["false"])
  3962. .field("typeParameter", def("TSTypeParameter"))
  3963. .field("optional", or(Boolean, "+", "-"), defaults["false"])
  3964. .field("typeAnnotation", or(def("TSType"), null), defaults["null"]);
  3965. def("TSTupleType")
  3966. .bases("TSType")
  3967. .build("elementTypes")
  3968. .field("elementTypes", [def("TSType")]);
  3969. def("TSRestType")
  3970. .bases("TSType")
  3971. .build("typeAnnotation")
  3972. .field("typeAnnotation", def("TSType"));
  3973. def("TSOptionalType")
  3974. .bases("TSType")
  3975. .build("typeAnnotation")
  3976. .field("typeAnnotation", def("TSType"));
  3977. def("TSIndexedAccessType")
  3978. .bases("TSType")
  3979. .build("objectType", "indexType")
  3980. .field("objectType", def("TSType"))
  3981. .field("indexType", def("TSType"));
  3982. def("TSTypeOperator")
  3983. .bases("TSType")
  3984. .build("operator")
  3985. .field("operator", String)
  3986. .field("typeAnnotation", def("TSType"));
  3987. def("TSTypeAnnotation")
  3988. .bases("Node")
  3989. .build("typeAnnotation")
  3990. .field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation")));
  3991. def("TSIndexSignature")
  3992. .bases("Declaration", "TSHasOptionalTypeAnnotation")
  3993. .build("parameters", "typeAnnotation")
  3994. .field("parameters", [def("Identifier")]) // Length === 1
  3995. .field("readonly", Boolean, defaults["false"]);
  3996. def("TSPropertySignature")
  3997. .bases("Declaration", "TSHasOptionalTypeAnnotation")
  3998. .build("key", "typeAnnotation", "optional")
  3999. .field("key", def("Expression"))
  4000. .field("computed", Boolean, defaults["false"])
  4001. .field("readonly", Boolean, defaults["false"])
  4002. .field("optional", Boolean, defaults["false"])
  4003. .field("initializer", or(def("Expression"), null), defaults["null"]);
  4004. def("TSMethodSignature")
  4005. .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
  4006. .build("key", "parameters", "typeAnnotation")
  4007. .field("key", def("Expression"))
  4008. .field("computed", Boolean, defaults["false"])
  4009. .field("optional", Boolean, defaults["false"])
  4010. .field("parameters", ParametersType);
  4011. def("TSTypePredicate")
  4012. .bases("TSTypeAnnotation")
  4013. .build("parameterName", "typeAnnotation")
  4014. .field("parameterName", or(def("Identifier"), def("TSThisType")))
  4015. .field("typeAnnotation", def("TSTypeAnnotation"));
  4016. ["TSCallSignatureDeclaration",
  4017. "TSConstructSignatureDeclaration",
  4018. ].forEach(function (typeName) {
  4019. def(typeName)
  4020. .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
  4021. .build("parameters", "typeAnnotation")
  4022. .field("parameters", ParametersType);
  4023. });
  4024. def("TSEnumMember")
  4025. .bases("Node")
  4026. .build("id", "initializer")
  4027. .field("id", or(def("Identifier"), StringLiteral))
  4028. .field("initializer", or(def("Expression"), null), defaults["null"]);
  4029. def("TSTypeQuery")
  4030. .bases("TSType")
  4031. .build("exprName")
  4032. .field("exprName", or(TSEntityName, def("TSImportType")));
  4033. // Inferred from Babylon's tsParseTypeMember method.
  4034. var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature"));
  4035. def("TSTypeLiteral")
  4036. .bases("TSType")
  4037. .build("members")
  4038. .field("members", [TSTypeMember]);
  4039. def("TSTypeParameter")
  4040. .bases("Identifier")
  4041. .build("name", "constraint", "default")
  4042. .field("name", String)
  4043. .field("constraint", or(def("TSType"), void 0), defaults["undefined"])
  4044. .field("default", or(def("TSType"), void 0), defaults["undefined"]);
  4045. def("TSTypeAssertion")
  4046. .bases("Expression", "Pattern")
  4047. .build("typeAnnotation", "expression")
  4048. .field("typeAnnotation", def("TSType"))
  4049. .field("expression", def("Expression"))
  4050. .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
  4051. def("TSTypeParameterDeclaration")
  4052. .bases("Declaration")
  4053. .build("params")
  4054. .field("params", [def("TSTypeParameter")]);
  4055. def("TSTypeParameterInstantiation")
  4056. .bases("Node")
  4057. .build("params")
  4058. .field("params", [def("TSType")]);
  4059. def("TSEnumDeclaration")
  4060. .bases("Declaration")
  4061. .build("id", "members")
  4062. .field("id", def("Identifier"))
  4063. .field("const", Boolean, defaults["false"])
  4064. .field("declare", Boolean, defaults["false"])
  4065. .field("members", [def("TSEnumMember")])
  4066. .field("initializer", or(def("Expression"), null), defaults["null"]);
  4067. def("TSTypeAliasDeclaration")
  4068. .bases("Declaration", "TSHasOptionalTypeParameters")
  4069. .build("id", "typeAnnotation")
  4070. .field("id", def("Identifier"))
  4071. .field("declare", Boolean, defaults["false"])
  4072. .field("typeAnnotation", def("TSType"));
  4073. def("TSModuleBlock")
  4074. .bases("Node")
  4075. .build("body")
  4076. .field("body", [def("Statement")]);
  4077. def("TSModuleDeclaration")
  4078. .bases("Declaration")
  4079. .build("id", "body")
  4080. .field("id", or(StringLiteral, TSEntityName))
  4081. .field("declare", Boolean, defaults["false"])
  4082. .field("global", Boolean, defaults["false"])
  4083. .field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]);
  4084. def("TSImportType")
  4085. .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
  4086. .build("argument", "qualifier", "typeParameters")
  4087. .field("argument", StringLiteral)
  4088. .field("qualifier", or(TSEntityName, void 0), defaults["undefined"]);
  4089. def("TSImportEqualsDeclaration")
  4090. .bases("Declaration")
  4091. .build("id", "moduleReference")
  4092. .field("id", def("Identifier"))
  4093. .field("isExport", Boolean, defaults["false"])
  4094. .field("moduleReference", or(TSEntityName, def("TSExternalModuleReference")));
  4095. def("TSExternalModuleReference")
  4096. .bases("Declaration")
  4097. .build("expression")
  4098. .field("expression", StringLiteral);
  4099. def("TSExportAssignment")
  4100. .bases("Statement")
  4101. .build("expression")
  4102. .field("expression", def("Expression"));
  4103. def("TSNamespaceExportDeclaration")
  4104. .bases("Declaration")
  4105. .build("id")
  4106. .field("id", def("Identifier"));
  4107. def("TSInterfaceBody")
  4108. .bases("Node")
  4109. .build("body")
  4110. .field("body", [TSTypeMember]);
  4111. def("TSExpressionWithTypeArguments")
  4112. .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
  4113. .build("expression", "typeParameters")
  4114. .field("expression", TSEntityName);
  4115. def("TSInterfaceDeclaration")
  4116. .bases("Declaration", "TSHasOptionalTypeParameters")
  4117. .build("id", "body")
  4118. .field("id", TSEntityName)
  4119. .field("declare", Boolean, defaults["false"])
  4120. .field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"])
  4121. .field("body", def("TSInterfaceBody"));
  4122. def("TSParameterProperty")
  4123. .bases("Pattern")
  4124. .build("parameter")
  4125. .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"])
  4126. .field("readonly", Boolean, defaults["false"])
  4127. .field("parameter", or(def("Identifier"), def("AssignmentPattern")));
  4128. def("ClassProperty")
  4129. .field("access", // Not "accessibility"?
  4130. or("public", "private", "protected", void 0), defaults["undefined"]);
  4131. // Defined already in es6 and babel-core.
  4132. def("ClassBody")
  4133. .field("body", [or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"),
  4134. // Just need to add these types:
  4135. def("TSDeclareMethod"), TSTypeMember)]);
  4136. }
  4137. exports.default = default_1;
  4138. module.exports = exports["default"];
  4139. });
  4140. unwrapExports(typescript);
  4141. var esProposals = createCommonjsModule(function (module, exports) {
  4142. var __importDefault = (this && this.__importDefault) || function (mod) {
  4143. return (mod && mod.__esModule) ? mod : { "default": mod };
  4144. };
  4145. Object.defineProperty(exports, "__esModule", { value: true });
  4146. var types_1 = __importDefault(types);
  4147. var shared_1 = __importDefault(shared);
  4148. var core_1 = __importDefault(core);
  4149. function default_1(fork) {
  4150. fork.use(core_1.default);
  4151. var types = fork.use(types_1.default);
  4152. var Type = types.Type;
  4153. var def = types.Type.def;
  4154. var or = Type.or;
  4155. var shared = fork.use(shared_1.default);
  4156. var defaults = shared.defaults;
  4157. // https://github.com/tc39/proposal-optional-chaining
  4158. // `a?.b` as per https://github.com/estree/estree/issues/146
  4159. def("OptionalMemberExpression")
  4160. .bases("MemberExpression")
  4161. .build("object", "property", "computed", "optional")
  4162. .field("optional", Boolean, defaults["true"]);
  4163. // a?.b()
  4164. def("OptionalCallExpression")
  4165. .bases("CallExpression")
  4166. .build("callee", "arguments", "optional")
  4167. .field("optional", Boolean, defaults["true"]);
  4168. // https://github.com/tc39/proposal-nullish-coalescing
  4169. // `a ?? b` as per https://github.com/babel/babylon/pull/761/files
  4170. var LogicalOperator = or("||", "&&", "??");
  4171. def("LogicalExpression")
  4172. .field("operator", LogicalOperator);
  4173. }
  4174. exports.default = default_1;
  4175. module.exports = exports["default"];
  4176. });
  4177. unwrapExports(esProposals);
  4178. var namedTypes_1 = createCommonjsModule(function (module, exports) {
  4179. Object.defineProperty(exports, "__esModule", { value: true });
  4180. var namedTypes;
  4181. (function (namedTypes) {
  4182. })(namedTypes = exports.namedTypes || (exports.namedTypes = {}));
  4183. });
  4184. unwrapExports(namedTypes_1);
  4185. var namedTypes_2 = namedTypes_1.namedTypes;
  4186. var main = createCommonjsModule(function (module, exports) {
  4187. var __importDefault = (this && this.__importDefault) || function (mod) {
  4188. return (mod && mod.__esModule) ? mod : { "default": mod };
  4189. };
  4190. Object.defineProperty(exports, "__esModule", { value: true });
  4191. var fork_1 = __importDefault(fork);
  4192. var core_1 = __importDefault(core);
  4193. var es6_1 = __importDefault(es6);
  4194. var es7_1 = __importDefault(es7);
  4195. var jsx_1 = __importDefault(jsx);
  4196. var flow_1 = __importDefault(flow);
  4197. var esprima_1 = __importDefault(esprima);
  4198. var babel_1 = __importDefault(babel);
  4199. var typescript_1 = __importDefault(typescript);
  4200. var es_proposals_1 = __importDefault(esProposals);
  4201. exports.namedTypes = namedTypes_1.namedTypes;
  4202. var _a = fork_1.default([
  4203. // This core module of AST types captures ES5 as it is parsed today by
  4204. // git://github.com/ariya/esprima.git#master.
  4205. core_1.default,
  4206. // Feel free to add to or remove from this list of extension modules to
  4207. // configure the precise type hierarchy that you need.
  4208. es6_1.default,
  4209. es7_1.default,
  4210. jsx_1.default,
  4211. flow_1.default,
  4212. esprima_1.default,
  4213. babel_1.default,
  4214. typescript_1.default,
  4215. es_proposals_1.default,
  4216. ]), astNodesAreEquivalent = _a.astNodesAreEquivalent, builders = _a.builders, builtInTypes = _a.builtInTypes, defineMethod = _a.defineMethod, eachField = _a.eachField, finalize = _a.finalize, getBuilderName = _a.getBuilderName, getFieldNames = _a.getFieldNames, getFieldValue = _a.getFieldValue, getSupertypeNames = _a.getSupertypeNames, n = _a.namedTypes, NodePath = _a.NodePath, Path = _a.Path, PathVisitor = _a.PathVisitor, someField = _a.someField, Type = _a.Type, use = _a.use, visit = _a.visit;
  4217. exports.astNodesAreEquivalent = astNodesAreEquivalent;
  4218. exports.builders = builders;
  4219. exports.builtInTypes = builtInTypes;
  4220. exports.defineMethod = defineMethod;
  4221. exports.eachField = eachField;
  4222. exports.finalize = finalize;
  4223. exports.getBuilderName = getBuilderName;
  4224. exports.getFieldNames = getFieldNames;
  4225. exports.getFieldValue = getFieldValue;
  4226. exports.getSupertypeNames = getSupertypeNames;
  4227. exports.NodePath = NodePath;
  4228. exports.Path = Path;
  4229. exports.PathVisitor = PathVisitor;
  4230. exports.someField = someField;
  4231. exports.Type = Type;
  4232. exports.use = use;
  4233. exports.visit = visit;
  4234. // Populate the exported fields of the namedTypes namespace, while still
  4235. // retaining its member types.
  4236. Object.assign(namedTypes_1.namedTypes, n);
  4237. });
  4238. unwrapExports(main);
  4239. var main_1 = main.namedTypes;
  4240. var main_2 = main.astNodesAreEquivalent;
  4241. var main_3 = main.builders;
  4242. var main_4 = main.builtInTypes;
  4243. var main_5 = main.defineMethod;
  4244. var main_6 = main.eachField;
  4245. var main_7 = main.finalize;
  4246. var main_8 = main.getBuilderName;
  4247. var main_9 = main.getFieldNames;
  4248. var main_10 = main.getFieldValue;
  4249. var main_11 = main.getSupertypeNames;
  4250. var main_12 = main.NodePath;
  4251. var main_13 = main.Path;
  4252. var main_14 = main.PathVisitor;
  4253. var main_15 = main.someField;
  4254. var main_16 = main.Type;
  4255. var main_17 = main.use;
  4256. var main_18 = main.visit;
  4257. /*!
  4258. * The buffer module from node.js, for the browser.
  4259. *
  4260. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  4261. * @license MIT
  4262. */
  4263. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  4264. // The _isBuffer check is for Safari 5-7 support, because it's missing
  4265. // Object.prototype.constructor. Remove this eventually
  4266. function isBuffer(obj) {
  4267. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  4268. }
  4269. function isFastBuffer (obj) {
  4270. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  4271. }
  4272. // For Node v0.10 support. Remove this eventually.
  4273. function isSlowBuffer (obj) {
  4274. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  4275. }
  4276. var inherits;
  4277. if (typeof Object.create === 'function'){
  4278. inherits = function inherits(ctor, superCtor) {
  4279. // implementation from standard node.js 'util' module
  4280. ctor.super_ = superCtor;
  4281. ctor.prototype = Object.create(superCtor.prototype, {
  4282. constructor: {
  4283. value: ctor,
  4284. enumerable: false,
  4285. writable: true,
  4286. configurable: true
  4287. }
  4288. });
  4289. };
  4290. } else {
  4291. inherits = function inherits(ctor, superCtor) {
  4292. ctor.super_ = superCtor;
  4293. var TempCtor = function () {};
  4294. TempCtor.prototype = superCtor.prototype;
  4295. ctor.prototype = new TempCtor();
  4296. ctor.prototype.constructor = ctor;
  4297. };
  4298. }
  4299. var inherits$1 = inherits;
  4300. // Copyright Joyent, Inc. and other Node contributors.
  4301. /**
  4302. * Echos the value of a value. Trys to print the value out
  4303. * in the best way possible given the different types.
  4304. *
  4305. * @param {Object} obj The object to print out.
  4306. * @param {Object} opts Optional options object that alters the output.
  4307. */
  4308. /* legacy: obj, showHidden, depth, colors*/
  4309. function inspect(obj, opts) {
  4310. // default options
  4311. var ctx = {
  4312. seen: [],
  4313. stylize: stylizeNoColor
  4314. };
  4315. // legacy...
  4316. if (arguments.length >= 3) ctx.depth = arguments[2];
  4317. if (arguments.length >= 4) ctx.colors = arguments[3];
  4318. if (isBoolean(opts)) {
  4319. // legacy...
  4320. ctx.showHidden = opts;
  4321. } else if (opts) {
  4322. // got an "options" object
  4323. _extend(ctx, opts);
  4324. }
  4325. // set default options
  4326. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  4327. if (isUndefined(ctx.depth)) ctx.depth = 2;
  4328. if (isUndefined(ctx.colors)) ctx.colors = false;
  4329. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  4330. if (ctx.colors) ctx.stylize = stylizeWithColor;
  4331. return formatValue(ctx, obj, ctx.depth);
  4332. }
  4333. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  4334. inspect.colors = {
  4335. 'bold' : [1, 22],
  4336. 'italic' : [3, 23],
  4337. 'underline' : [4, 24],
  4338. 'inverse' : [7, 27],
  4339. 'white' : [37, 39],
  4340. 'grey' : [90, 39],
  4341. 'black' : [30, 39],
  4342. 'blue' : [34, 39],
  4343. 'cyan' : [36, 39],
  4344. 'green' : [32, 39],
  4345. 'magenta' : [35, 39],
  4346. 'red' : [31, 39],
  4347. 'yellow' : [33, 39]
  4348. };
  4349. // Don't use 'blue' not visible on cmd.exe
  4350. inspect.styles = {
  4351. 'special': 'cyan',
  4352. 'number': 'yellow',
  4353. 'boolean': 'yellow',
  4354. 'undefined': 'grey',
  4355. 'null': 'bold',
  4356. 'string': 'green',
  4357. 'date': 'magenta',
  4358. // "name": intentionally not styling
  4359. 'regexp': 'red'
  4360. };
  4361. function stylizeWithColor(str, styleType) {
  4362. var style = inspect.styles[styleType];
  4363. if (style) {
  4364. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  4365. '\u001b[' + inspect.colors[style][1] + 'm';
  4366. } else {
  4367. return str;
  4368. }
  4369. }
  4370. function stylizeNoColor(str, styleType) {
  4371. return str;
  4372. }
  4373. function arrayToHash(array) {
  4374. var hash = {};
  4375. array.forEach(function(val, idx) {
  4376. hash[val] = true;
  4377. });
  4378. return hash;
  4379. }
  4380. function formatValue(ctx, value, recurseTimes) {
  4381. // Provide a hook for user-specified inspect functions.
  4382. // Check that value is an object with an inspect function on it
  4383. if (ctx.customInspect &&
  4384. value &&
  4385. isFunction(value.inspect) &&
  4386. // Filter out the util module, it's inspect function is special
  4387. value.inspect !== inspect &&
  4388. // Also filter out any prototype objects using the circular check.
  4389. !(value.constructor && value.constructor.prototype === value)) {
  4390. var ret = value.inspect(recurseTimes, ctx);
  4391. if (!isString(ret)) {
  4392. ret = formatValue(ctx, ret, recurseTimes);
  4393. }
  4394. return ret;
  4395. }
  4396. // Primitive types cannot have properties
  4397. var primitive = formatPrimitive(ctx, value);
  4398. if (primitive) {
  4399. return primitive;
  4400. }
  4401. // Look up the keys of the object.
  4402. var keys = Object.keys(value);
  4403. var visibleKeys = arrayToHash(keys);
  4404. if (ctx.showHidden) {
  4405. keys = Object.getOwnPropertyNames(value);
  4406. }
  4407. // IE doesn't make error fields non-enumerable
  4408. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  4409. if (isError(value)
  4410. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  4411. return formatError(value);
  4412. }
  4413. // Some type of object without properties can be shortcutted.
  4414. if (keys.length === 0) {
  4415. if (isFunction(value)) {
  4416. var name = value.name ? ': ' + value.name : '';
  4417. return ctx.stylize('[Function' + name + ']', 'special');
  4418. }
  4419. if (isRegExp(value)) {
  4420. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  4421. }
  4422. if (isDate(value)) {
  4423. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  4424. }
  4425. if (isError(value)) {
  4426. return formatError(value);
  4427. }
  4428. }
  4429. var base = '', array = false, braces = ['{', '}'];
  4430. // Make Array say that they are Array
  4431. if (isArray(value)) {
  4432. array = true;
  4433. braces = ['[', ']'];
  4434. }
  4435. // Make functions say that they are functions
  4436. if (isFunction(value)) {
  4437. var n = value.name ? ': ' + value.name : '';
  4438. base = ' [Function' + n + ']';
  4439. }
  4440. // Make RegExps say that they are RegExps
  4441. if (isRegExp(value)) {
  4442. base = ' ' + RegExp.prototype.toString.call(value);
  4443. }
  4444. // Make dates with properties first say the date
  4445. if (isDate(value)) {
  4446. base = ' ' + Date.prototype.toUTCString.call(value);
  4447. }
  4448. // Make error with message first say the error
  4449. if (isError(value)) {
  4450. base = ' ' + formatError(value);
  4451. }
  4452. if (keys.length === 0 && (!array || value.length == 0)) {
  4453. return braces[0] + base + braces[1];
  4454. }
  4455. if (recurseTimes < 0) {
  4456. if (isRegExp(value)) {
  4457. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  4458. } else {
  4459. return ctx.stylize('[Object]', 'special');
  4460. }
  4461. }
  4462. ctx.seen.push(value);
  4463. var output;
  4464. if (array) {
  4465. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  4466. } else {
  4467. output = keys.map(function(key) {
  4468. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  4469. });
  4470. }
  4471. ctx.seen.pop();
  4472. return reduceToSingleString(output, base, braces);
  4473. }
  4474. function formatPrimitive(ctx, value) {
  4475. if (isUndefined(value))
  4476. return ctx.stylize('undefined', 'undefined');
  4477. if (isString(value)) {
  4478. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  4479. .replace(/'/g, "\\'")
  4480. .replace(/\\"/g, '"') + '\'';
  4481. return ctx.stylize(simple, 'string');
  4482. }
  4483. if (isNumber(value))
  4484. return ctx.stylize('' + value, 'number');
  4485. if (isBoolean(value))
  4486. return ctx.stylize('' + value, 'boolean');
  4487. // For some reason typeof null is "object", so special case here.
  4488. if (isNull(value))
  4489. return ctx.stylize('null', 'null');
  4490. }
  4491. function formatError(value) {
  4492. return '[' + Error.prototype.toString.call(value) + ']';
  4493. }
  4494. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  4495. var output = [];
  4496. for (var i = 0, l = value.length; i < l; ++i) {
  4497. if (hasOwnProperty(value, String(i))) {
  4498. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  4499. String(i), true));
  4500. } else {
  4501. output.push('');
  4502. }
  4503. }
  4504. keys.forEach(function(key) {
  4505. if (!key.match(/^\d+$/)) {
  4506. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  4507. key, true));
  4508. }
  4509. });
  4510. return output;
  4511. }
  4512. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  4513. var name, str, desc;
  4514. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  4515. if (desc.get) {
  4516. if (desc.set) {
  4517. str = ctx.stylize('[Getter/Setter]', 'special');
  4518. } else {
  4519. str = ctx.stylize('[Getter]', 'special');
  4520. }
  4521. } else {
  4522. if (desc.set) {
  4523. str = ctx.stylize('[Setter]', 'special');
  4524. }
  4525. }
  4526. if (!hasOwnProperty(visibleKeys, key)) {
  4527. name = '[' + key + ']';
  4528. }
  4529. if (!str) {
  4530. if (ctx.seen.indexOf(desc.value) < 0) {
  4531. if (isNull(recurseTimes)) {
  4532. str = formatValue(ctx, desc.value, null);
  4533. } else {
  4534. str = formatValue(ctx, desc.value, recurseTimes - 1);
  4535. }
  4536. if (str.indexOf('\n') > -1) {
  4537. if (array) {
  4538. str = str.split('\n').map(function(line) {
  4539. return ' ' + line;
  4540. }).join('\n').substr(2);
  4541. } else {
  4542. str = '\n' + str.split('\n').map(function(line) {
  4543. return ' ' + line;
  4544. }).join('\n');
  4545. }
  4546. }
  4547. } else {
  4548. str = ctx.stylize('[Circular]', 'special');
  4549. }
  4550. }
  4551. if (isUndefined(name)) {
  4552. if (array && key.match(/^\d+$/)) {
  4553. return str;
  4554. }
  4555. name = JSON.stringify('' + key);
  4556. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  4557. name = name.substr(1, name.length - 2);
  4558. name = ctx.stylize(name, 'name');
  4559. } else {
  4560. name = name.replace(/'/g, "\\'")
  4561. .replace(/\\"/g, '"')
  4562. .replace(/(^"|"$)/g, "'");
  4563. name = ctx.stylize(name, 'string');
  4564. }
  4565. }
  4566. return name + ': ' + str;
  4567. }
  4568. function reduceToSingleString(output, base, braces) {
  4569. var length = output.reduce(function(prev, cur) {
  4570. if (cur.indexOf('\n') >= 0) ;
  4571. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  4572. }, 0);
  4573. if (length > 60) {
  4574. return braces[0] +
  4575. (base === '' ? '' : base + '\n ') +
  4576. ' ' +
  4577. output.join(',\n ') +
  4578. ' ' +
  4579. braces[1];
  4580. }
  4581. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  4582. }
  4583. // NOTE: These type checking functions intentionally don't use `instanceof`
  4584. // because it is fragile and can be easily faked with `Object.create()`.
  4585. function isArray(ar) {
  4586. return Array.isArray(ar);
  4587. }
  4588. function isBoolean(arg) {
  4589. return typeof arg === 'boolean';
  4590. }
  4591. function isNull(arg) {
  4592. return arg === null;
  4593. }
  4594. function isNumber(arg) {
  4595. return typeof arg === 'number';
  4596. }
  4597. function isString(arg) {
  4598. return typeof arg === 'string';
  4599. }
  4600. function isUndefined(arg) {
  4601. return arg === void 0;
  4602. }
  4603. function isRegExp(re) {
  4604. return isObject(re) && objectToString(re) === '[object RegExp]';
  4605. }
  4606. function isObject(arg) {
  4607. return typeof arg === 'object' && arg !== null;
  4608. }
  4609. function isDate(d) {
  4610. return isObject(d) && objectToString(d) === '[object Date]';
  4611. }
  4612. function isError(e) {
  4613. return isObject(e) &&
  4614. (objectToString(e) === '[object Error]' || e instanceof Error);
  4615. }
  4616. function isFunction(arg) {
  4617. return typeof arg === 'function';
  4618. }
  4619. function isPrimitive(arg) {
  4620. return arg === null ||
  4621. typeof arg === 'boolean' ||
  4622. typeof arg === 'number' ||
  4623. typeof arg === 'string' ||
  4624. typeof arg === 'symbol' || // ES6 symbol
  4625. typeof arg === 'undefined';
  4626. }
  4627. function objectToString(o) {
  4628. return Object.prototype.toString.call(o);
  4629. }
  4630. function _extend(origin, add) {
  4631. // Don't do anything if add isn't an object
  4632. if (!add || !isObject(add)) return origin;
  4633. var keys = Object.keys(add);
  4634. var i = keys.length;
  4635. while (i--) {
  4636. origin[keys[i]] = add[keys[i]];
  4637. }
  4638. return origin;
  4639. }
  4640. function hasOwnProperty(obj, prop) {
  4641. return Object.prototype.hasOwnProperty.call(obj, prop);
  4642. }
  4643. function compare(a, b) {
  4644. if (a === b) {
  4645. return 0;
  4646. }
  4647. var x = a.length;
  4648. var y = b.length;
  4649. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  4650. if (a[i] !== b[i]) {
  4651. x = a[i];
  4652. y = b[i];
  4653. break;
  4654. }
  4655. }
  4656. if (x < y) {
  4657. return -1;
  4658. }
  4659. if (y < x) {
  4660. return 1;
  4661. }
  4662. return 0;
  4663. }
  4664. var hasOwn = Object.prototype.hasOwnProperty;
  4665. var objectKeys = Object.keys || function (obj) {
  4666. var keys = [];
  4667. for (var key in obj) {
  4668. if (hasOwn.call(obj, key)) keys.push(key);
  4669. }
  4670. return keys;
  4671. };
  4672. var pSlice = Array.prototype.slice;
  4673. var _functionsHaveNames;
  4674. function functionsHaveNames() {
  4675. if (typeof _functionsHaveNames !== 'undefined') {
  4676. return _functionsHaveNames;
  4677. }
  4678. return _functionsHaveNames = (function () {
  4679. return function foo() {}.name === 'foo';
  4680. }());
  4681. }
  4682. function pToString (obj) {
  4683. return Object.prototype.toString.call(obj);
  4684. }
  4685. function isView(arrbuf) {
  4686. if (isBuffer(arrbuf)) {
  4687. return false;
  4688. }
  4689. if (typeof global.ArrayBuffer !== 'function') {
  4690. return false;
  4691. }
  4692. if (typeof ArrayBuffer.isView === 'function') {
  4693. return ArrayBuffer.isView(arrbuf);
  4694. }
  4695. if (!arrbuf) {
  4696. return false;
  4697. }
  4698. if (arrbuf instanceof DataView) {
  4699. return true;
  4700. }
  4701. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  4702. return true;
  4703. }
  4704. return false;
  4705. }
  4706. // 1. The assert module provides functions that throw
  4707. // AssertionError's when particular conditions are not met. The
  4708. // assert module must conform to the following interface.
  4709. function assert(value, message) {
  4710. if (!value) fail(value, true, message, '==', ok);
  4711. }
  4712. // 2. The AssertionError is defined in assert.
  4713. // new assert.AssertionError({ message: message,
  4714. // actual: actual,
  4715. // expected: expected })
  4716. var regex = /\s*function\s+([^\(\s]*)\s*/;
  4717. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  4718. function getName(func) {
  4719. if (!isFunction(func)) {
  4720. return;
  4721. }
  4722. if (functionsHaveNames()) {
  4723. return func.name;
  4724. }
  4725. var str = func.toString();
  4726. var match = str.match(regex);
  4727. return match && match[1];
  4728. }
  4729. assert.AssertionError = AssertionError;
  4730. function AssertionError(options) {
  4731. this.name = 'AssertionError';
  4732. this.actual = options.actual;
  4733. this.expected = options.expected;
  4734. this.operator = options.operator;
  4735. if (options.message) {
  4736. this.message = options.message;
  4737. this.generatedMessage = false;
  4738. } else {
  4739. this.message = getMessage(this);
  4740. this.generatedMessage = true;
  4741. }
  4742. var stackStartFunction = options.stackStartFunction || fail;
  4743. if (Error.captureStackTrace) {
  4744. Error.captureStackTrace(this, stackStartFunction);
  4745. } else {
  4746. // non v8 browsers so we can have a stacktrace
  4747. var err = new Error();
  4748. if (err.stack) {
  4749. var out = err.stack;
  4750. // try to strip useless frames
  4751. var fn_name = getName(stackStartFunction);
  4752. var idx = out.indexOf('\n' + fn_name);
  4753. if (idx >= 0) {
  4754. // once we have located the function frame
  4755. // we need to strip out everything before it (and its line)
  4756. var next_line = out.indexOf('\n', idx + 1);
  4757. out = out.substring(next_line + 1);
  4758. }
  4759. this.stack = out;
  4760. }
  4761. }
  4762. }
  4763. // assert.AssertionError instanceof Error
  4764. inherits$1(AssertionError, Error);
  4765. function truncate(s, n) {
  4766. if (typeof s === 'string') {
  4767. return s.length < n ? s : s.slice(0, n);
  4768. } else {
  4769. return s;
  4770. }
  4771. }
  4772. function inspect$1(something) {
  4773. if (functionsHaveNames() || !isFunction(something)) {
  4774. return inspect(something);
  4775. }
  4776. var rawname = getName(something);
  4777. var name = rawname ? ': ' + rawname : '';
  4778. return '[Function' + name + ']';
  4779. }
  4780. function getMessage(self) {
  4781. return truncate(inspect$1(self.actual), 128) + ' ' +
  4782. self.operator + ' ' +
  4783. truncate(inspect$1(self.expected), 128);
  4784. }
  4785. // At present only the three keys mentioned above are used and
  4786. // understood by the spec. Implementations or sub modules can pass
  4787. // other keys to the AssertionError's constructor - they will be
  4788. // ignored.
  4789. // 3. All of the following functions must throw an AssertionError
  4790. // when a corresponding condition is not met, with a message that
  4791. // may be undefined if not provided. All assertion methods provide
  4792. // both the actual and expected values to the assertion error for
  4793. // display purposes.
  4794. function fail(actual, expected, message, operator, stackStartFunction) {
  4795. throw new AssertionError({
  4796. message: message,
  4797. actual: actual,
  4798. expected: expected,
  4799. operator: operator,
  4800. stackStartFunction: stackStartFunction
  4801. });
  4802. }
  4803. // EXTENSION! allows for well behaved errors defined elsewhere.
  4804. assert.fail = fail;
  4805. // 4. Pure assertion tests whether a value is truthy, as determined
  4806. // by !!guard.
  4807. // assert.ok(guard, message_opt);
  4808. // This statement is equivalent to assert.equal(true, !!guard,
  4809. // message_opt);. To test strictly for the value true, use
  4810. // assert.strictEqual(true, guard, message_opt);.
  4811. function ok(value, message) {
  4812. if (!value) fail(value, true, message, '==', ok);
  4813. }
  4814. assert.ok = ok;
  4815. // 5. The equality assertion tests shallow, coercive equality with
  4816. // ==.
  4817. // assert.equal(actual, expected, message_opt);
  4818. assert.equal = equal;
  4819. function equal(actual, expected, message) {
  4820. if (actual != expected) fail(actual, expected, message, '==', equal);
  4821. }
  4822. // 6. The non-equality assertion tests for whether two objects are not equal
  4823. // with != assert.notEqual(actual, expected, message_opt);
  4824. assert.notEqual = notEqual;
  4825. function notEqual(actual, expected, message) {
  4826. if (actual == expected) {
  4827. fail(actual, expected, message, '!=', notEqual);
  4828. }
  4829. }
  4830. // 7. The equivalence assertion tests a deep equality relation.
  4831. // assert.deepEqual(actual, expected, message_opt);
  4832. assert.deepEqual = deepEqual;
  4833. function deepEqual(actual, expected, message) {
  4834. if (!_deepEqual(actual, expected, false)) {
  4835. fail(actual, expected, message, 'deepEqual', deepEqual);
  4836. }
  4837. }
  4838. assert.deepStrictEqual = deepStrictEqual;
  4839. function deepStrictEqual(actual, expected, message) {
  4840. if (!_deepEqual(actual, expected, true)) {
  4841. fail(actual, expected, message, 'deepStrictEqual', deepStrictEqual);
  4842. }
  4843. }
  4844. function _deepEqual(actual, expected, strict, memos) {
  4845. // 7.1. All identical values are equivalent, as determined by ===.
  4846. if (actual === expected) {
  4847. return true;
  4848. } else if (isBuffer(actual) && isBuffer(expected)) {
  4849. return compare(actual, expected) === 0;
  4850. // 7.2. If the expected value is a Date object, the actual value is
  4851. // equivalent if it is also a Date object that refers to the same time.
  4852. } else if (isDate(actual) && isDate(expected)) {
  4853. return actual.getTime() === expected.getTime();
  4854. // 7.3 If the expected value is a RegExp object, the actual value is
  4855. // equivalent if it is also a RegExp object with the same source and
  4856. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  4857. } else if (isRegExp(actual) && isRegExp(expected)) {
  4858. return actual.source === expected.source &&
  4859. actual.global === expected.global &&
  4860. actual.multiline === expected.multiline &&
  4861. actual.lastIndex === expected.lastIndex &&
  4862. actual.ignoreCase === expected.ignoreCase;
  4863. // 7.4. Other pairs that do not both pass typeof value == 'object',
  4864. // equivalence is determined by ==.
  4865. } else if ((actual === null || typeof actual !== 'object') &&
  4866. (expected === null || typeof expected !== 'object')) {
  4867. return strict ? actual === expected : actual == expected;
  4868. // If both values are instances of typed arrays, wrap their underlying
  4869. // ArrayBuffers in a Buffer each to increase performance
  4870. // This optimization requires the arrays to have the same type as checked by
  4871. // Object.prototype.toString (aka pToString). Never perform binary
  4872. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  4873. // bit patterns are not identical.
  4874. } else if (isView(actual) && isView(expected) &&
  4875. pToString(actual) === pToString(expected) &&
  4876. !(actual instanceof Float32Array ||
  4877. actual instanceof Float64Array)) {
  4878. return compare(new Uint8Array(actual.buffer),
  4879. new Uint8Array(expected.buffer)) === 0;
  4880. // 7.5 For all other Object pairs, including Array objects, equivalence is
  4881. // determined by having the same number of owned properties (as verified
  4882. // with Object.prototype.hasOwnProperty.call), the same set of keys
  4883. // (although not necessarily the same order), equivalent values for every
  4884. // corresponding key, and an identical 'prototype' property. Note: this
  4885. // accounts for both named and indexed properties on Arrays.
  4886. } else if (isBuffer(actual) !== isBuffer(expected)) {
  4887. return false;
  4888. } else {
  4889. memos = memos || {actual: [], expected: []};
  4890. var actualIndex = memos.actual.indexOf(actual);
  4891. if (actualIndex !== -1) {
  4892. if (actualIndex === memos.expected.indexOf(expected)) {
  4893. return true;
  4894. }
  4895. }
  4896. memos.actual.push(actual);
  4897. memos.expected.push(expected);
  4898. return objEquiv(actual, expected, strict, memos);
  4899. }
  4900. }
  4901. function isArguments(object) {
  4902. return Object.prototype.toString.call(object) == '[object Arguments]';
  4903. }
  4904. function objEquiv(a, b, strict, actualVisitedObjects) {
  4905. if (a === null || a === undefined || b === null || b === undefined)
  4906. return false;
  4907. // if one is a primitive, the other must be same
  4908. if (isPrimitive(a) || isPrimitive(b))
  4909. return a === b;
  4910. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  4911. return false;
  4912. var aIsArgs = isArguments(a);
  4913. var bIsArgs = isArguments(b);
  4914. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  4915. return false;
  4916. if (aIsArgs) {
  4917. a = pSlice.call(a);
  4918. b = pSlice.call(b);
  4919. return _deepEqual(a, b, strict);
  4920. }
  4921. var ka = objectKeys(a);
  4922. var kb = objectKeys(b);
  4923. var key, i;
  4924. // having the same number of owned properties (keys incorporates
  4925. // hasOwnProperty)
  4926. if (ka.length !== kb.length)
  4927. return false;
  4928. //the same set of keys (although not necessarily the same order),
  4929. ka.sort();
  4930. kb.sort();
  4931. //~~~cheap key test
  4932. for (i = ka.length - 1; i >= 0; i--) {
  4933. if (ka[i] !== kb[i])
  4934. return false;
  4935. }
  4936. //equivalent values for every corresponding key, and
  4937. //~~~possibly expensive deep test
  4938. for (i = ka.length - 1; i >= 0; i--) {
  4939. key = ka[i];
  4940. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  4941. return false;
  4942. }
  4943. return true;
  4944. }
  4945. // 8. The non-equivalence assertion tests for any deep inequality.
  4946. // assert.notDeepEqual(actual, expected, message_opt);
  4947. assert.notDeepEqual = notDeepEqual;
  4948. function notDeepEqual(actual, expected, message) {
  4949. if (_deepEqual(actual, expected, false)) {
  4950. fail(actual, expected, message, 'notDeepEqual', notDeepEqual);
  4951. }
  4952. }
  4953. assert.notDeepStrictEqual = notDeepStrictEqual;
  4954. function notDeepStrictEqual(actual, expected, message) {
  4955. if (_deepEqual(actual, expected, true)) {
  4956. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  4957. }
  4958. }
  4959. // 9. The strict equality assertion tests strict equality, as determined by ===.
  4960. // assert.strictEqual(actual, expected, message_opt);
  4961. assert.strictEqual = strictEqual;
  4962. function strictEqual(actual, expected, message) {
  4963. if (actual !== expected) {
  4964. fail(actual, expected, message, '===', strictEqual);
  4965. }
  4966. }
  4967. // 10. The strict non-equality assertion tests for strict inequality, as
  4968. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  4969. assert.notStrictEqual = notStrictEqual;
  4970. function notStrictEqual(actual, expected, message) {
  4971. if (actual === expected) {
  4972. fail(actual, expected, message, '!==', notStrictEqual);
  4973. }
  4974. }
  4975. function expectedException(actual, expected) {
  4976. if (!actual || !expected) {
  4977. return false;
  4978. }
  4979. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  4980. return expected.test(actual);
  4981. }
  4982. try {
  4983. if (actual instanceof expected) {
  4984. return true;
  4985. }
  4986. } catch (e) {
  4987. // Ignore. The instanceof check doesn't work for arrow functions.
  4988. }
  4989. if (Error.isPrototypeOf(expected)) {
  4990. return false;
  4991. }
  4992. return expected.call({}, actual) === true;
  4993. }
  4994. function _tryBlock(block) {
  4995. var error;
  4996. try {
  4997. block();
  4998. } catch (e) {
  4999. error = e;
  5000. }
  5001. return error;
  5002. }
  5003. function _throws(shouldThrow, block, expected, message) {
  5004. var actual;
  5005. if (typeof block !== 'function') {
  5006. throw new TypeError('"block" argument must be a function');
  5007. }
  5008. if (typeof expected === 'string') {
  5009. message = expected;
  5010. expected = null;
  5011. }
  5012. actual = _tryBlock(block);
  5013. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  5014. (message ? ' ' + message : '.');
  5015. if (shouldThrow && !actual) {
  5016. fail(actual, expected, 'Missing expected exception' + message);
  5017. }
  5018. var userProvidedMessage = typeof message === 'string';
  5019. var isUnwantedException = !shouldThrow && isError(actual);
  5020. var isUnexpectedException = !shouldThrow && actual && !expected;
  5021. if ((isUnwantedException &&
  5022. userProvidedMessage &&
  5023. expectedException(actual, expected)) ||
  5024. isUnexpectedException) {
  5025. fail(actual, expected, 'Got unwanted exception' + message);
  5026. }
  5027. if ((shouldThrow && actual && expected &&
  5028. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  5029. throw actual;
  5030. }
  5031. }
  5032. // 11. Expected to throw an error:
  5033. // assert.throws(block, Error_opt, message_opt);
  5034. assert.throws = throws;
  5035. function throws(block, /*optional*/error, /*optional*/message) {
  5036. _throws(true, block, error, message);
  5037. }
  5038. // EXTENSION! This is annoying to write outside this module.
  5039. assert.doesNotThrow = doesNotThrow;
  5040. function doesNotThrow(block, /*optional*/error, /*optional*/message) {
  5041. _throws(false, block, error, message);
  5042. }
  5043. assert.ifError = ifError;
  5044. function ifError(err) {
  5045. if (err) throw err;
  5046. }
  5047. /* -*- Mode: js; js-indent-level: 2; -*- */
  5048. /*
  5049. * Copyright 2011 Mozilla Foundation and contributors
  5050. * Licensed under the New BSD license. See LICENSE or:
  5051. * http://opensource.org/licenses/BSD-3-Clause
  5052. */
  5053. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  5054. /**
  5055. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  5056. */
  5057. var encode = function (number) {
  5058. if (0 <= number && number < intToCharMap.length) {
  5059. return intToCharMap[number];
  5060. }
  5061. throw new TypeError("Must be between 0 and 63: " + number);
  5062. };
  5063. /**
  5064. * Decode a single base 64 character code digit to an integer. Returns -1 on
  5065. * failure.
  5066. */
  5067. var decode = function (charCode) {
  5068. var bigA = 65; // 'A'
  5069. var bigZ = 90; // 'Z'
  5070. var littleA = 97; // 'a'
  5071. var littleZ = 122; // 'z'
  5072. var zero = 48; // '0'
  5073. var nine = 57; // '9'
  5074. var plus = 43; // '+'
  5075. var slash = 47; // '/'
  5076. var littleOffset = 26;
  5077. var numberOffset = 52;
  5078. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  5079. if (bigA <= charCode && charCode <= bigZ) {
  5080. return (charCode - bigA);
  5081. }
  5082. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  5083. if (littleA <= charCode && charCode <= littleZ) {
  5084. return (charCode - littleA + littleOffset);
  5085. }
  5086. // 52 - 61: 0123456789
  5087. if (zero <= charCode && charCode <= nine) {
  5088. return (charCode - zero + numberOffset);
  5089. }
  5090. // 62: +
  5091. if (charCode == plus) {
  5092. return 62;
  5093. }
  5094. // 63: /
  5095. if (charCode == slash) {
  5096. return 63;
  5097. }
  5098. // Invalid base64 digit.
  5099. return -1;
  5100. };
  5101. var base64 = {
  5102. encode: encode,
  5103. decode: decode
  5104. };
  5105. /* -*- Mode: js; js-indent-level: 2; -*- */
  5106. /*
  5107. * Copyright 2011 Mozilla Foundation and contributors
  5108. * Licensed under the New BSD license. See LICENSE or:
  5109. * http://opensource.org/licenses/BSD-3-Clause
  5110. *
  5111. * Based on the Base 64 VLQ implementation in Closure Compiler:
  5112. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  5113. *
  5114. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  5115. * Redistribution and use in source and binary forms, with or without
  5116. * modification, are permitted provided that the following conditions are
  5117. * met:
  5118. *
  5119. * * Redistributions of source code must retain the above copyright
  5120. * notice, this list of conditions and the following disclaimer.
  5121. * * Redistributions in binary form must reproduce the above
  5122. * copyright notice, this list of conditions and the following
  5123. * disclaimer in the documentation and/or other materials provided
  5124. * with the distribution.
  5125. * * Neither the name of Google Inc. nor the names of its
  5126. * contributors may be used to endorse or promote products derived
  5127. * from this software without specific prior written permission.
  5128. *
  5129. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5130. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5131. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5132. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5133. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5134. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5135. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5136. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5137. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5138. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5139. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5140. */
  5141. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  5142. // length quantities we use in the source map spec, the first bit is the sign,
  5143. // the next four bits are the actual value, and the 6th bit is the
  5144. // continuation bit. The continuation bit tells us whether there are more
  5145. // digits in this value following this digit.
  5146. //
  5147. // Continuation
  5148. // | Sign
  5149. // | |
  5150. // V V
  5151. // 101011
  5152. var VLQ_BASE_SHIFT = 5;
  5153. // binary: 100000
  5154. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  5155. // binary: 011111
  5156. var VLQ_BASE_MASK = VLQ_BASE - 1;
  5157. // binary: 100000
  5158. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  5159. /**
  5160. * Converts from a two-complement value to a value where the sign bit is
  5161. * placed in the least significant bit. For example, as decimals:
  5162. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  5163. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  5164. */
  5165. function toVLQSigned(aValue) {
  5166. return aValue < 0
  5167. ? ((-aValue) << 1) + 1
  5168. : (aValue << 1) + 0;
  5169. }
  5170. /**
  5171. * Converts to a two-complement value from a value where the sign bit is
  5172. * placed in the least significant bit. For example, as decimals:
  5173. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  5174. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  5175. */
  5176. function fromVLQSigned(aValue) {
  5177. var isNegative = (aValue & 1) === 1;
  5178. var shifted = aValue >> 1;
  5179. return isNegative
  5180. ? -shifted
  5181. : shifted;
  5182. }
  5183. /**
  5184. * Returns the base 64 VLQ encoded value.
  5185. */
  5186. var encode$1 = function base64VLQ_encode(aValue) {
  5187. var encoded = "";
  5188. var digit;
  5189. var vlq = toVLQSigned(aValue);
  5190. do {
  5191. digit = vlq & VLQ_BASE_MASK;
  5192. vlq >>>= VLQ_BASE_SHIFT;
  5193. if (vlq > 0) {
  5194. // There are still more digits in this value, so we must make sure the
  5195. // continuation bit is marked.
  5196. digit |= VLQ_CONTINUATION_BIT;
  5197. }
  5198. encoded += base64.encode(digit);
  5199. } while (vlq > 0);
  5200. return encoded;
  5201. };
  5202. /**
  5203. * Decodes the next base 64 VLQ value from the given string and returns the
  5204. * value and the rest of the string via the out parameter.
  5205. */
  5206. var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  5207. var strLen = aStr.length;
  5208. var result = 0;
  5209. var shift = 0;
  5210. var continuation, digit;
  5211. do {
  5212. if (aIndex >= strLen) {
  5213. throw new Error("Expected more digits in base 64 VLQ value.");
  5214. }
  5215. digit = base64.decode(aStr.charCodeAt(aIndex++));
  5216. if (digit === -1) {
  5217. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  5218. }
  5219. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  5220. digit &= VLQ_BASE_MASK;
  5221. result = result + (digit << shift);
  5222. shift += VLQ_BASE_SHIFT;
  5223. } while (continuation);
  5224. aOutParam.value = fromVLQSigned(result);
  5225. aOutParam.rest = aIndex;
  5226. };
  5227. var base64Vlq = {
  5228. encode: encode$1,
  5229. decode: decode$1
  5230. };
  5231. var util = createCommonjsModule(function (module, exports) {
  5232. /* -*- Mode: js; js-indent-level: 2; -*- */
  5233. /*
  5234. * Copyright 2011 Mozilla Foundation and contributors
  5235. * Licensed under the New BSD license. See LICENSE or:
  5236. * http://opensource.org/licenses/BSD-3-Clause
  5237. */
  5238. /**
  5239. * This is a helper function for getting values from parameter/options
  5240. * objects.
  5241. *
  5242. * @param args The object we are extracting values from
  5243. * @param name The name of the property we are getting.
  5244. * @param defaultValue An optional value to return if the property is missing
  5245. * from the object. If this is not specified and the property is missing, an
  5246. * error will be thrown.
  5247. */
  5248. function getArg(aArgs, aName, aDefaultValue) {
  5249. if (aName in aArgs) {
  5250. return aArgs[aName];
  5251. } else if (arguments.length === 3) {
  5252. return aDefaultValue;
  5253. } else {
  5254. throw new Error('"' + aName + '" is a required argument.');
  5255. }
  5256. }
  5257. exports.getArg = getArg;
  5258. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  5259. var dataUrlRegexp = /^data:.+\,.+$/;
  5260. function urlParse(aUrl) {
  5261. var match = aUrl.match(urlRegexp);
  5262. if (!match) {
  5263. return null;
  5264. }
  5265. return {
  5266. scheme: match[1],
  5267. auth: match[2],
  5268. host: match[3],
  5269. port: match[4],
  5270. path: match[5]
  5271. };
  5272. }
  5273. exports.urlParse = urlParse;
  5274. function urlGenerate(aParsedUrl) {
  5275. var url = '';
  5276. if (aParsedUrl.scheme) {
  5277. url += aParsedUrl.scheme + ':';
  5278. }
  5279. url += '//';
  5280. if (aParsedUrl.auth) {
  5281. url += aParsedUrl.auth + '@';
  5282. }
  5283. if (aParsedUrl.host) {
  5284. url += aParsedUrl.host;
  5285. }
  5286. if (aParsedUrl.port) {
  5287. url += ":" + aParsedUrl.port;
  5288. }
  5289. if (aParsedUrl.path) {
  5290. url += aParsedUrl.path;
  5291. }
  5292. return url;
  5293. }
  5294. exports.urlGenerate = urlGenerate;
  5295. /**
  5296. * Normalizes a path, or the path portion of a URL:
  5297. *
  5298. * - Replaces consecutive slashes with one slash.
  5299. * - Removes unnecessary '.' parts.
  5300. * - Removes unnecessary '<dir>/..' parts.
  5301. *
  5302. * Based on code in the Node.js 'path' core module.
  5303. *
  5304. * @param aPath The path or url to normalize.
  5305. */
  5306. function normalize(aPath) {
  5307. var path = aPath;
  5308. var url = urlParse(aPath);
  5309. if (url) {
  5310. if (!url.path) {
  5311. return aPath;
  5312. }
  5313. path = url.path;
  5314. }
  5315. var isAbsolute = exports.isAbsolute(path);
  5316. var parts = path.split(/\/+/);
  5317. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  5318. part = parts[i];
  5319. if (part === '.') {
  5320. parts.splice(i, 1);
  5321. } else if (part === '..') {
  5322. up++;
  5323. } else if (up > 0) {
  5324. if (part === '') {
  5325. // The first part is blank if the path is absolute. Trying to go
  5326. // above the root is a no-op. Therefore we can remove all '..' parts
  5327. // directly after the root.
  5328. parts.splice(i + 1, up);
  5329. up = 0;
  5330. } else {
  5331. parts.splice(i, 2);
  5332. up--;
  5333. }
  5334. }
  5335. }
  5336. path = parts.join('/');
  5337. if (path === '') {
  5338. path = isAbsolute ? '/' : '.';
  5339. }
  5340. if (url) {
  5341. url.path = path;
  5342. return urlGenerate(url);
  5343. }
  5344. return path;
  5345. }
  5346. exports.normalize = normalize;
  5347. /**
  5348. * Joins two paths/URLs.
  5349. *
  5350. * @param aRoot The root path or URL.
  5351. * @param aPath The path or URL to be joined with the root.
  5352. *
  5353. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  5354. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  5355. * first.
  5356. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  5357. * is updated with the result and aRoot is returned. Otherwise the result
  5358. * is returned.
  5359. * - If aPath is absolute, the result is aPath.
  5360. * - Otherwise the two paths are joined with a slash.
  5361. * - Joining for example 'http://' and 'www.example.com' is also supported.
  5362. */
  5363. function join(aRoot, aPath) {
  5364. if (aRoot === "") {
  5365. aRoot = ".";
  5366. }
  5367. if (aPath === "") {
  5368. aPath = ".";
  5369. }
  5370. var aPathUrl = urlParse(aPath);
  5371. var aRootUrl = urlParse(aRoot);
  5372. if (aRootUrl) {
  5373. aRoot = aRootUrl.path || '/';
  5374. }
  5375. // `join(foo, '//www.example.org')`
  5376. if (aPathUrl && !aPathUrl.scheme) {
  5377. if (aRootUrl) {
  5378. aPathUrl.scheme = aRootUrl.scheme;
  5379. }
  5380. return urlGenerate(aPathUrl);
  5381. }
  5382. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  5383. return aPath;
  5384. }
  5385. // `join('http://', 'www.example.com')`
  5386. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  5387. aRootUrl.host = aPath;
  5388. return urlGenerate(aRootUrl);
  5389. }
  5390. var joined = aPath.charAt(0) === '/'
  5391. ? aPath
  5392. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  5393. if (aRootUrl) {
  5394. aRootUrl.path = joined;
  5395. return urlGenerate(aRootUrl);
  5396. }
  5397. return joined;
  5398. }
  5399. exports.join = join;
  5400. exports.isAbsolute = function (aPath) {
  5401. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  5402. };
  5403. /**
  5404. * Make a path relative to a URL or another path.
  5405. *
  5406. * @param aRoot The root path or URL.
  5407. * @param aPath The path or URL to be made relative to aRoot.
  5408. */
  5409. function relative(aRoot, aPath) {
  5410. if (aRoot === "") {
  5411. aRoot = ".";
  5412. }
  5413. aRoot = aRoot.replace(/\/$/, '');
  5414. // It is possible for the path to be above the root. In this case, simply
  5415. // checking whether the root is a prefix of the path won't work. Instead, we
  5416. // need to remove components from the root one by one, until either we find
  5417. // a prefix that fits, or we run out of components to remove.
  5418. var level = 0;
  5419. while (aPath.indexOf(aRoot + '/') !== 0) {
  5420. var index = aRoot.lastIndexOf("/");
  5421. if (index < 0) {
  5422. return aPath;
  5423. }
  5424. // If the only part of the root that is left is the scheme (i.e. http://,
  5425. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  5426. // have exhausted all components, so the path is not relative to the root.
  5427. aRoot = aRoot.slice(0, index);
  5428. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  5429. return aPath;
  5430. }
  5431. ++level;
  5432. }
  5433. // Make sure we add a "../" for each component we removed from the root.
  5434. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  5435. }
  5436. exports.relative = relative;
  5437. var supportsNullProto = (function () {
  5438. var obj = Object.create(null);
  5439. return !('__proto__' in obj);
  5440. }());
  5441. function identity (s) {
  5442. return s;
  5443. }
  5444. /**
  5445. * Because behavior goes wacky when you set `__proto__` on objects, we
  5446. * have to prefix all the strings in our set with an arbitrary character.
  5447. *
  5448. * See https://github.com/mozilla/source-map/pull/31 and
  5449. * https://github.com/mozilla/source-map/issues/30
  5450. *
  5451. * @param String aStr
  5452. */
  5453. function toSetString(aStr) {
  5454. if (isProtoString(aStr)) {
  5455. return '$' + aStr;
  5456. }
  5457. return aStr;
  5458. }
  5459. exports.toSetString = supportsNullProto ? identity : toSetString;
  5460. function fromSetString(aStr) {
  5461. if (isProtoString(aStr)) {
  5462. return aStr.slice(1);
  5463. }
  5464. return aStr;
  5465. }
  5466. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  5467. function isProtoString(s) {
  5468. if (!s) {
  5469. return false;
  5470. }
  5471. var length = s.length;
  5472. if (length < 9 /* "__proto__".length */) {
  5473. return false;
  5474. }
  5475. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  5476. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  5477. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  5478. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  5479. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  5480. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  5481. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  5482. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  5483. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  5484. return false;
  5485. }
  5486. for (var i = length - 10; i >= 0; i--) {
  5487. if (s.charCodeAt(i) !== 36 /* '$' */) {
  5488. return false;
  5489. }
  5490. }
  5491. return true;
  5492. }
  5493. /**
  5494. * Comparator between two mappings where the original positions are compared.
  5495. *
  5496. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  5497. * mappings with the same original source/line/column, but different generated
  5498. * line and column the same. Useful when searching for a mapping with a
  5499. * stubbed out mapping.
  5500. */
  5501. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  5502. var cmp = strcmp(mappingA.source, mappingB.source);
  5503. if (cmp !== 0) {
  5504. return cmp;
  5505. }
  5506. cmp = mappingA.originalLine - mappingB.originalLine;
  5507. if (cmp !== 0) {
  5508. return cmp;
  5509. }
  5510. cmp = mappingA.originalColumn - mappingB.originalColumn;
  5511. if (cmp !== 0 || onlyCompareOriginal) {
  5512. return cmp;
  5513. }
  5514. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  5515. if (cmp !== 0) {
  5516. return cmp;
  5517. }
  5518. cmp = mappingA.generatedLine - mappingB.generatedLine;
  5519. if (cmp !== 0) {
  5520. return cmp;
  5521. }
  5522. return strcmp(mappingA.name, mappingB.name);
  5523. }
  5524. exports.compareByOriginalPositions = compareByOriginalPositions;
  5525. /**
  5526. * Comparator between two mappings with deflated source and name indices where
  5527. * the generated positions are compared.
  5528. *
  5529. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  5530. * mappings with the same generated line and column, but different
  5531. * source/name/original line and column the same. Useful when searching for a
  5532. * mapping with a stubbed out mapping.
  5533. */
  5534. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  5535. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  5536. if (cmp !== 0) {
  5537. return cmp;
  5538. }
  5539. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  5540. if (cmp !== 0 || onlyCompareGenerated) {
  5541. return cmp;
  5542. }
  5543. cmp = strcmp(mappingA.source, mappingB.source);
  5544. if (cmp !== 0) {
  5545. return cmp;
  5546. }
  5547. cmp = mappingA.originalLine - mappingB.originalLine;
  5548. if (cmp !== 0) {
  5549. return cmp;
  5550. }
  5551. cmp = mappingA.originalColumn - mappingB.originalColumn;
  5552. if (cmp !== 0) {
  5553. return cmp;
  5554. }
  5555. return strcmp(mappingA.name, mappingB.name);
  5556. }
  5557. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  5558. function strcmp(aStr1, aStr2) {
  5559. if (aStr1 === aStr2) {
  5560. return 0;
  5561. }
  5562. if (aStr1 === null) {
  5563. return 1; // aStr2 !== null
  5564. }
  5565. if (aStr2 === null) {
  5566. return -1; // aStr1 !== null
  5567. }
  5568. if (aStr1 > aStr2) {
  5569. return 1;
  5570. }
  5571. return -1;
  5572. }
  5573. /**
  5574. * Comparator between two mappings with inflated source and name strings where
  5575. * the generated positions are compared.
  5576. */
  5577. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  5578. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  5579. if (cmp !== 0) {
  5580. return cmp;
  5581. }
  5582. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  5583. if (cmp !== 0) {
  5584. return cmp;
  5585. }
  5586. cmp = strcmp(mappingA.source, mappingB.source);
  5587. if (cmp !== 0) {
  5588. return cmp;
  5589. }
  5590. cmp = mappingA.originalLine - mappingB.originalLine;
  5591. if (cmp !== 0) {
  5592. return cmp;
  5593. }
  5594. cmp = mappingA.originalColumn - mappingB.originalColumn;
  5595. if (cmp !== 0) {
  5596. return cmp;
  5597. }
  5598. return strcmp(mappingA.name, mappingB.name);
  5599. }
  5600. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  5601. /**
  5602. * Strip any JSON XSSI avoidance prefix from the string (as documented
  5603. * in the source maps specification), and then parse the string as
  5604. * JSON.
  5605. */
  5606. function parseSourceMapInput(str) {
  5607. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  5608. }
  5609. exports.parseSourceMapInput = parseSourceMapInput;
  5610. /**
  5611. * Compute the URL of a source given the the source root, the source's
  5612. * URL, and the source map's URL.
  5613. */
  5614. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  5615. sourceURL = sourceURL || '';
  5616. if (sourceRoot) {
  5617. // This follows what Chrome does.
  5618. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  5619. sourceRoot += '/';
  5620. }
  5621. // The spec says:
  5622. // Line 4: An optional source root, useful for relocating source
  5623. // files on a server or removing repeated values in the
  5624. // “sources” entry. This value is prepended to the individual
  5625. // entries in the “source” field.
  5626. sourceURL = sourceRoot + sourceURL;
  5627. }
  5628. // Historically, SourceMapConsumer did not take the sourceMapURL as
  5629. // a parameter. This mode is still somewhat supported, which is why
  5630. // this code block is conditional. However, it's preferable to pass
  5631. // the source map URL to SourceMapConsumer, so that this function
  5632. // can implement the source URL resolution algorithm as outlined in
  5633. // the spec. This block is basically the equivalent of:
  5634. // new URL(sourceURL, sourceMapURL).toString()
  5635. // ... except it avoids using URL, which wasn't available in the
  5636. // older releases of node still supported by this library.
  5637. //
  5638. // The spec says:
  5639. // If the sources are not absolute URLs after prepending of the
  5640. // “sourceRoot”, the sources are resolved relative to the
  5641. // SourceMap (like resolving script src in a html document).
  5642. if (sourceMapURL) {
  5643. var parsed = urlParse(sourceMapURL);
  5644. if (!parsed) {
  5645. throw new Error("sourceMapURL could not be parsed");
  5646. }
  5647. if (parsed.path) {
  5648. // Strip the last path component, but keep the "/".
  5649. var index = parsed.path.lastIndexOf('/');
  5650. if (index >= 0) {
  5651. parsed.path = parsed.path.substring(0, index + 1);
  5652. }
  5653. }
  5654. sourceURL = join(urlGenerate(parsed), sourceURL);
  5655. }
  5656. return normalize(sourceURL);
  5657. }
  5658. exports.computeSourceURL = computeSourceURL;
  5659. });
  5660. var util_1 = util.getArg;
  5661. var util_2 = util.urlParse;
  5662. var util_3 = util.urlGenerate;
  5663. var util_4 = util.normalize;
  5664. var util_5 = util.join;
  5665. var util_6 = util.isAbsolute;
  5666. var util_7 = util.relative;
  5667. var util_8 = util.toSetString;
  5668. var util_9 = util.fromSetString;
  5669. var util_10 = util.compareByOriginalPositions;
  5670. var util_11 = util.compareByGeneratedPositionsDeflated;
  5671. var util_12 = util.compareByGeneratedPositionsInflated;
  5672. var util_13 = util.parseSourceMapInput;
  5673. var util_14 = util.computeSourceURL;
  5674. /* -*- Mode: js; js-indent-level: 2; -*- */
  5675. /*
  5676. * Copyright 2011 Mozilla Foundation and contributors
  5677. * Licensed under the New BSD license. See LICENSE or:
  5678. * http://opensource.org/licenses/BSD-3-Clause
  5679. */
  5680. var has = Object.prototype.hasOwnProperty;
  5681. var hasNativeMap = typeof Map !== "undefined";
  5682. /**
  5683. * A data structure which is a combination of an array and a set. Adding a new
  5684. * member is O(1), testing for membership is O(1), and finding the index of an
  5685. * element is O(1). Removing elements from the set is not supported. Only
  5686. * strings are supported for membership.
  5687. */
  5688. function ArraySet() {
  5689. this._array = [];
  5690. this._set = hasNativeMap ? new Map() : Object.create(null);
  5691. }
  5692. /**
  5693. * Static method for creating ArraySet instances from an existing array.
  5694. */
  5695. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  5696. var set = new ArraySet();
  5697. for (var i = 0, len = aArray.length; i < len; i++) {
  5698. set.add(aArray[i], aAllowDuplicates);
  5699. }
  5700. return set;
  5701. };
  5702. /**
  5703. * Return how many unique items are in this ArraySet. If duplicates have been
  5704. * added, than those do not count towards the size.
  5705. *
  5706. * @returns Number
  5707. */
  5708. ArraySet.prototype.size = function ArraySet_size() {
  5709. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  5710. };
  5711. /**
  5712. * Add the given string to this set.
  5713. *
  5714. * @param String aStr
  5715. */
  5716. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  5717. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  5718. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  5719. var idx = this._array.length;
  5720. if (!isDuplicate || aAllowDuplicates) {
  5721. this._array.push(aStr);
  5722. }
  5723. if (!isDuplicate) {
  5724. if (hasNativeMap) {
  5725. this._set.set(aStr, idx);
  5726. } else {
  5727. this._set[sStr] = idx;
  5728. }
  5729. }
  5730. };
  5731. /**
  5732. * Is the given string a member of this set?
  5733. *
  5734. * @param String aStr
  5735. */
  5736. ArraySet.prototype.has = function ArraySet_has(aStr) {
  5737. if (hasNativeMap) {
  5738. return this._set.has(aStr);
  5739. } else {
  5740. var sStr = util.toSetString(aStr);
  5741. return has.call(this._set, sStr);
  5742. }
  5743. };
  5744. /**
  5745. * What is the index of the given string in the array?
  5746. *
  5747. * @param String aStr
  5748. */
  5749. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  5750. if (hasNativeMap) {
  5751. var idx = this._set.get(aStr);
  5752. if (idx >= 0) {
  5753. return idx;
  5754. }
  5755. } else {
  5756. var sStr = util.toSetString(aStr);
  5757. if (has.call(this._set, sStr)) {
  5758. return this._set[sStr];
  5759. }
  5760. }
  5761. throw new Error('"' + aStr + '" is not in the set.');
  5762. };
  5763. /**
  5764. * What is the element at the given index?
  5765. *
  5766. * @param Number aIdx
  5767. */
  5768. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  5769. if (aIdx >= 0 && aIdx < this._array.length) {
  5770. return this._array[aIdx];
  5771. }
  5772. throw new Error('No element indexed by ' + aIdx);
  5773. };
  5774. /**
  5775. * Returns the array representation of this set (which has the proper indices
  5776. * indicated by indexOf). Note that this is a copy of the internal array used
  5777. * for storing the members so that no one can mess with internal state.
  5778. */
  5779. ArraySet.prototype.toArray = function ArraySet_toArray() {
  5780. return this._array.slice();
  5781. };
  5782. var ArraySet_1 = ArraySet;
  5783. var arraySet = {
  5784. ArraySet: ArraySet_1
  5785. };
  5786. /* -*- Mode: js; js-indent-level: 2; -*- */
  5787. /*
  5788. * Copyright 2014 Mozilla Foundation and contributors
  5789. * Licensed under the New BSD license. See LICENSE or:
  5790. * http://opensource.org/licenses/BSD-3-Clause
  5791. */
  5792. /**
  5793. * Determine whether mappingB is after mappingA with respect to generated
  5794. * position.
  5795. */
  5796. function generatedPositionAfter(mappingA, mappingB) {
  5797. // Optimized for most common case
  5798. var lineA = mappingA.generatedLine;
  5799. var lineB = mappingB.generatedLine;
  5800. var columnA = mappingA.generatedColumn;
  5801. var columnB = mappingB.generatedColumn;
  5802. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  5803. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  5804. }
  5805. /**
  5806. * A data structure to provide a sorted view of accumulated mappings in a
  5807. * performance conscious manner. It trades a neglibable overhead in general
  5808. * case for a large speedup in case of mappings being added in order.
  5809. */
  5810. function MappingList() {
  5811. this._array = [];
  5812. this._sorted = true;
  5813. // Serves as infimum
  5814. this._last = {generatedLine: -1, generatedColumn: 0};
  5815. }
  5816. /**
  5817. * Iterate through internal items. This method takes the same arguments that
  5818. * `Array.prototype.forEach` takes.
  5819. *
  5820. * NOTE: The order of the mappings is NOT guaranteed.
  5821. */
  5822. MappingList.prototype.unsortedForEach =
  5823. function MappingList_forEach(aCallback, aThisArg) {
  5824. this._array.forEach(aCallback, aThisArg);
  5825. };
  5826. /**
  5827. * Add the given source mapping.
  5828. *
  5829. * @param Object aMapping
  5830. */
  5831. MappingList.prototype.add = function MappingList_add(aMapping) {
  5832. if (generatedPositionAfter(this._last, aMapping)) {
  5833. this._last = aMapping;
  5834. this._array.push(aMapping);
  5835. } else {
  5836. this._sorted = false;
  5837. this._array.push(aMapping);
  5838. }
  5839. };
  5840. /**
  5841. * Returns the flat, sorted array of mappings. The mappings are sorted by
  5842. * generated position.
  5843. *
  5844. * WARNING: This method returns internal data without copying, for
  5845. * performance. The return value must NOT be mutated, and should be treated as
  5846. * an immutable borrow. If you want to take ownership, you must make your own
  5847. * copy.
  5848. */
  5849. MappingList.prototype.toArray = function MappingList_toArray() {
  5850. if (!this._sorted) {
  5851. this._array.sort(util.compareByGeneratedPositionsInflated);
  5852. this._sorted = true;
  5853. }
  5854. return this._array;
  5855. };
  5856. var MappingList_1 = MappingList;
  5857. var mappingList = {
  5858. MappingList: MappingList_1
  5859. };
  5860. /* -*- Mode: js; js-indent-level: 2; -*- */
  5861. /*
  5862. * Copyright 2011 Mozilla Foundation and contributors
  5863. * Licensed under the New BSD license. See LICENSE or:
  5864. * http://opensource.org/licenses/BSD-3-Clause
  5865. */
  5866. var ArraySet$1 = arraySet.ArraySet;
  5867. var MappingList$1 = mappingList.MappingList;
  5868. /**
  5869. * An instance of the SourceMapGenerator represents a source map which is
  5870. * being built incrementally. You may pass an object with the following
  5871. * properties:
  5872. *
  5873. * - file: The filename of the generated source.
  5874. * - sourceRoot: A root for all relative URLs in this source map.
  5875. */
  5876. function SourceMapGenerator(aArgs) {
  5877. if (!aArgs) {
  5878. aArgs = {};
  5879. }
  5880. this._file = util.getArg(aArgs, 'file', null);
  5881. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  5882. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  5883. this._sources = new ArraySet$1();
  5884. this._names = new ArraySet$1();
  5885. this._mappings = new MappingList$1();
  5886. this._sourcesContents = null;
  5887. }
  5888. SourceMapGenerator.prototype._version = 3;
  5889. /**
  5890. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  5891. *
  5892. * @param aSourceMapConsumer The SourceMap.
  5893. */
  5894. SourceMapGenerator.fromSourceMap =
  5895. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  5896. var sourceRoot = aSourceMapConsumer.sourceRoot;
  5897. var generator = new SourceMapGenerator({
  5898. file: aSourceMapConsumer.file,
  5899. sourceRoot: sourceRoot
  5900. });
  5901. aSourceMapConsumer.eachMapping(function (mapping) {
  5902. var newMapping = {
  5903. generated: {
  5904. line: mapping.generatedLine,
  5905. column: mapping.generatedColumn
  5906. }
  5907. };
  5908. if (mapping.source != null) {
  5909. newMapping.source = mapping.source;
  5910. if (sourceRoot != null) {
  5911. newMapping.source = util.relative(sourceRoot, newMapping.source);
  5912. }
  5913. newMapping.original = {
  5914. line: mapping.originalLine,
  5915. column: mapping.originalColumn
  5916. };
  5917. if (mapping.name != null) {
  5918. newMapping.name = mapping.name;
  5919. }
  5920. }
  5921. generator.addMapping(newMapping);
  5922. });
  5923. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  5924. var sourceRelative = sourceFile;
  5925. if (sourceRoot !== null) {
  5926. sourceRelative = util.relative(sourceRoot, sourceFile);
  5927. }
  5928. if (!generator._sources.has(sourceRelative)) {
  5929. generator._sources.add(sourceRelative);
  5930. }
  5931. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  5932. if (content != null) {
  5933. generator.setSourceContent(sourceFile, content);
  5934. }
  5935. });
  5936. return generator;
  5937. };
  5938. /**
  5939. * Add a single mapping from original source line and column to the generated
  5940. * source's line and column for this source map being created. The mapping
  5941. * object should have the following properties:
  5942. *
  5943. * - generated: An object with the generated line and column positions.
  5944. * - original: An object with the original line and column positions.
  5945. * - source: The original source file (relative to the sourceRoot).
  5946. * - name: An optional original token name for this mapping.
  5947. */
  5948. SourceMapGenerator.prototype.addMapping =
  5949. function SourceMapGenerator_addMapping(aArgs) {
  5950. var generated = util.getArg(aArgs, 'generated');
  5951. var original = util.getArg(aArgs, 'original', null);
  5952. var source = util.getArg(aArgs, 'source', null);
  5953. var name = util.getArg(aArgs, 'name', null);
  5954. if (!this._skipValidation) {
  5955. this._validateMapping(generated, original, source, name);
  5956. }
  5957. if (source != null) {
  5958. source = String(source);
  5959. if (!this._sources.has(source)) {
  5960. this._sources.add(source);
  5961. }
  5962. }
  5963. if (name != null) {
  5964. name = String(name);
  5965. if (!this._names.has(name)) {
  5966. this._names.add(name);
  5967. }
  5968. }
  5969. this._mappings.add({
  5970. generatedLine: generated.line,
  5971. generatedColumn: generated.column,
  5972. originalLine: original != null && original.line,
  5973. originalColumn: original != null && original.column,
  5974. source: source,
  5975. name: name
  5976. });
  5977. };
  5978. /**
  5979. * Set the source content for a source file.
  5980. */
  5981. SourceMapGenerator.prototype.setSourceContent =
  5982. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  5983. var source = aSourceFile;
  5984. if (this._sourceRoot != null) {
  5985. source = util.relative(this._sourceRoot, source);
  5986. }
  5987. if (aSourceContent != null) {
  5988. // Add the source content to the _sourcesContents map.
  5989. // Create a new _sourcesContents map if the property is null.
  5990. if (!this._sourcesContents) {
  5991. this._sourcesContents = Object.create(null);
  5992. }
  5993. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  5994. } else if (this._sourcesContents) {
  5995. // Remove the source file from the _sourcesContents map.
  5996. // If the _sourcesContents map is empty, set the property to null.
  5997. delete this._sourcesContents[util.toSetString(source)];
  5998. if (Object.keys(this._sourcesContents).length === 0) {
  5999. this._sourcesContents = null;
  6000. }
  6001. }
  6002. };
  6003. /**
  6004. * Applies the mappings of a sub-source-map for a specific source file to the
  6005. * source map being generated. Each mapping to the supplied source file is
  6006. * rewritten using the supplied source map. Note: The resolution for the
  6007. * resulting mappings is the minimium of this map and the supplied map.
  6008. *
  6009. * @param aSourceMapConsumer The source map to be applied.
  6010. * @param aSourceFile Optional. The filename of the source file.
  6011. * If omitted, SourceMapConsumer's file property will be used.
  6012. * @param aSourceMapPath Optional. The dirname of the path to the source map
  6013. * to be applied. If relative, it is relative to the SourceMapConsumer.
  6014. * This parameter is needed when the two source maps aren't in the same
  6015. * directory, and the source map to be applied contains relative source
  6016. * paths. If so, those relative source paths need to be rewritten
  6017. * relative to the SourceMapGenerator.
  6018. */
  6019. SourceMapGenerator.prototype.applySourceMap =
  6020. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  6021. var sourceFile = aSourceFile;
  6022. // If aSourceFile is omitted, we will use the file property of the SourceMap
  6023. if (aSourceFile == null) {
  6024. if (aSourceMapConsumer.file == null) {
  6025. throw new Error(
  6026. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  6027. 'or the source map\'s "file" property. Both were omitted.'
  6028. );
  6029. }
  6030. sourceFile = aSourceMapConsumer.file;
  6031. }
  6032. var sourceRoot = this._sourceRoot;
  6033. // Make "sourceFile" relative if an absolute Url is passed.
  6034. if (sourceRoot != null) {
  6035. sourceFile = util.relative(sourceRoot, sourceFile);
  6036. }
  6037. // Applying the SourceMap can add and remove items from the sources and
  6038. // the names array.
  6039. var newSources = new ArraySet$1();
  6040. var newNames = new ArraySet$1();
  6041. // Find mappings for the "sourceFile"
  6042. this._mappings.unsortedForEach(function (mapping) {
  6043. if (mapping.source === sourceFile && mapping.originalLine != null) {
  6044. // Check if it can be mapped by the source map, then update the mapping.
  6045. var original = aSourceMapConsumer.originalPositionFor({
  6046. line: mapping.originalLine,
  6047. column: mapping.originalColumn
  6048. });
  6049. if (original.source != null) {
  6050. // Copy mapping
  6051. mapping.source = original.source;
  6052. if (aSourceMapPath != null) {
  6053. mapping.source = util.join(aSourceMapPath, mapping.source);
  6054. }
  6055. if (sourceRoot != null) {
  6056. mapping.source = util.relative(sourceRoot, mapping.source);
  6057. }
  6058. mapping.originalLine = original.line;
  6059. mapping.originalColumn = original.column;
  6060. if (original.name != null) {
  6061. mapping.name = original.name;
  6062. }
  6063. }
  6064. }
  6065. var source = mapping.source;
  6066. if (source != null && !newSources.has(source)) {
  6067. newSources.add(source);
  6068. }
  6069. var name = mapping.name;
  6070. if (name != null && !newNames.has(name)) {
  6071. newNames.add(name);
  6072. }
  6073. }, this);
  6074. this._sources = newSources;
  6075. this._names = newNames;
  6076. // Copy sourcesContents of applied map.
  6077. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  6078. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  6079. if (content != null) {
  6080. if (aSourceMapPath != null) {
  6081. sourceFile = util.join(aSourceMapPath, sourceFile);
  6082. }
  6083. if (sourceRoot != null) {
  6084. sourceFile = util.relative(sourceRoot, sourceFile);
  6085. }
  6086. this.setSourceContent(sourceFile, content);
  6087. }
  6088. }, this);
  6089. };
  6090. /**
  6091. * A mapping can have one of the three levels of data:
  6092. *
  6093. * 1. Just the generated position.
  6094. * 2. The Generated position, original position, and original source.
  6095. * 3. Generated and original position, original source, as well as a name
  6096. * token.
  6097. *
  6098. * To maintain consistency, we validate that any new mapping being added falls
  6099. * in to one of these categories.
  6100. */
  6101. SourceMapGenerator.prototype._validateMapping =
  6102. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  6103. aName) {
  6104. // When aOriginal is truthy but has empty values for .line and .column,
  6105. // it is most likely a programmer error. In this case we throw a very
  6106. // specific error message to try to guide them the right way.
  6107. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  6108. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  6109. throw new Error(
  6110. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  6111. 'the original mapping entirely and only map the generated position. If so, pass ' +
  6112. 'null for the original mapping instead of an object with empty or null values.'
  6113. );
  6114. }
  6115. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  6116. && aGenerated.line > 0 && aGenerated.column >= 0
  6117. && !aOriginal && !aSource && !aName) {
  6118. // Case 1.
  6119. return;
  6120. }
  6121. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  6122. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  6123. && aGenerated.line > 0 && aGenerated.column >= 0
  6124. && aOriginal.line > 0 && aOriginal.column >= 0
  6125. && aSource) {
  6126. // Cases 2 and 3.
  6127. return;
  6128. }
  6129. else {
  6130. throw new Error('Invalid mapping: ' + JSON.stringify({
  6131. generated: aGenerated,
  6132. source: aSource,
  6133. original: aOriginal,
  6134. name: aName
  6135. }));
  6136. }
  6137. };
  6138. /**
  6139. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  6140. * specified by the source map format.
  6141. */
  6142. SourceMapGenerator.prototype._serializeMappings =
  6143. function SourceMapGenerator_serializeMappings() {
  6144. var previousGeneratedColumn = 0;
  6145. var previousGeneratedLine = 1;
  6146. var previousOriginalColumn = 0;
  6147. var previousOriginalLine = 0;
  6148. var previousName = 0;
  6149. var previousSource = 0;
  6150. var result = '';
  6151. var next;
  6152. var mapping;
  6153. var nameIdx;
  6154. var sourceIdx;
  6155. var mappings = this._mappings.toArray();
  6156. for (var i = 0, len = mappings.length; i < len; i++) {
  6157. mapping = mappings[i];
  6158. next = '';
  6159. if (mapping.generatedLine !== previousGeneratedLine) {
  6160. previousGeneratedColumn = 0;
  6161. while (mapping.generatedLine !== previousGeneratedLine) {
  6162. next += ';';
  6163. previousGeneratedLine++;
  6164. }
  6165. }
  6166. else {
  6167. if (i > 0) {
  6168. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  6169. continue;
  6170. }
  6171. next += ',';
  6172. }
  6173. }
  6174. next += base64Vlq.encode(mapping.generatedColumn
  6175. - previousGeneratedColumn);
  6176. previousGeneratedColumn = mapping.generatedColumn;
  6177. if (mapping.source != null) {
  6178. sourceIdx = this._sources.indexOf(mapping.source);
  6179. next += base64Vlq.encode(sourceIdx - previousSource);
  6180. previousSource = sourceIdx;
  6181. // lines are stored 0-based in SourceMap spec version 3
  6182. next += base64Vlq.encode(mapping.originalLine - 1
  6183. - previousOriginalLine);
  6184. previousOriginalLine = mapping.originalLine - 1;
  6185. next += base64Vlq.encode(mapping.originalColumn
  6186. - previousOriginalColumn);
  6187. previousOriginalColumn = mapping.originalColumn;
  6188. if (mapping.name != null) {
  6189. nameIdx = this._names.indexOf(mapping.name);
  6190. next += base64Vlq.encode(nameIdx - previousName);
  6191. previousName = nameIdx;
  6192. }
  6193. }
  6194. result += next;
  6195. }
  6196. return result;
  6197. };
  6198. SourceMapGenerator.prototype._generateSourcesContent =
  6199. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  6200. return aSources.map(function (source) {
  6201. if (!this._sourcesContents) {
  6202. return null;
  6203. }
  6204. if (aSourceRoot != null) {
  6205. source = util.relative(aSourceRoot, source);
  6206. }
  6207. var key = util.toSetString(source);
  6208. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  6209. ? this._sourcesContents[key]
  6210. : null;
  6211. }, this);
  6212. };
  6213. /**
  6214. * Externalize the source map.
  6215. */
  6216. SourceMapGenerator.prototype.toJSON =
  6217. function SourceMapGenerator_toJSON() {
  6218. var map = {
  6219. version: this._version,
  6220. sources: this._sources.toArray(),
  6221. names: this._names.toArray(),
  6222. mappings: this._serializeMappings()
  6223. };
  6224. if (this._file != null) {
  6225. map.file = this._file;
  6226. }
  6227. if (this._sourceRoot != null) {
  6228. map.sourceRoot = this._sourceRoot;
  6229. }
  6230. if (this._sourcesContents) {
  6231. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  6232. }
  6233. return map;
  6234. };
  6235. /**
  6236. * Render the source map being generated to a string.
  6237. */
  6238. SourceMapGenerator.prototype.toString =
  6239. function SourceMapGenerator_toString() {
  6240. return JSON.stringify(this.toJSON());
  6241. };
  6242. var SourceMapGenerator_1 = SourceMapGenerator;
  6243. var sourceMapGenerator = {
  6244. SourceMapGenerator: SourceMapGenerator_1
  6245. };
  6246. var binarySearch = createCommonjsModule(function (module, exports) {
  6247. /* -*- Mode: js; js-indent-level: 2; -*- */
  6248. /*
  6249. * Copyright 2011 Mozilla Foundation and contributors
  6250. * Licensed under the New BSD license. See LICENSE or:
  6251. * http://opensource.org/licenses/BSD-3-Clause
  6252. */
  6253. exports.GREATEST_LOWER_BOUND = 1;
  6254. exports.LEAST_UPPER_BOUND = 2;
  6255. /**
  6256. * Recursive implementation of binary search.
  6257. *
  6258. * @param aLow Indices here and lower do not contain the needle.
  6259. * @param aHigh Indices here and higher do not contain the needle.
  6260. * @param aNeedle The element being searched for.
  6261. * @param aHaystack The non-empty array being searched.
  6262. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  6263. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  6264. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  6265. * closest element that is smaller than or greater than the one we are
  6266. * searching for, respectively, if the exact element cannot be found.
  6267. */
  6268. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  6269. // This function terminates when one of the following is true:
  6270. //
  6271. // 1. We find the exact element we are looking for.
  6272. //
  6273. // 2. We did not find the exact element, but we can return the index of
  6274. // the next-closest element.
  6275. //
  6276. // 3. We did not find the exact element, and there is no next-closest
  6277. // element than the one we are searching for, so we return -1.
  6278. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  6279. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  6280. if (cmp === 0) {
  6281. // Found the element we are looking for.
  6282. return mid;
  6283. }
  6284. else if (cmp > 0) {
  6285. // Our needle is greater than aHaystack[mid].
  6286. if (aHigh - mid > 1) {
  6287. // The element is in the upper half.
  6288. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  6289. }
  6290. // The exact needle element was not found in this haystack. Determine if
  6291. // we are in termination case (3) or (2) and return the appropriate thing.
  6292. if (aBias == exports.LEAST_UPPER_BOUND) {
  6293. return aHigh < aHaystack.length ? aHigh : -1;
  6294. } else {
  6295. return mid;
  6296. }
  6297. }
  6298. else {
  6299. // Our needle is less than aHaystack[mid].
  6300. if (mid - aLow > 1) {
  6301. // The element is in the lower half.
  6302. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  6303. }
  6304. // we are in termination case (3) or (2) and return the appropriate thing.
  6305. if (aBias == exports.LEAST_UPPER_BOUND) {
  6306. return mid;
  6307. } else {
  6308. return aLow < 0 ? -1 : aLow;
  6309. }
  6310. }
  6311. }
  6312. /**
  6313. * This is an implementation of binary search which will always try and return
  6314. * the index of the closest element if there is no exact hit. This is because
  6315. * mappings between original and generated line/col pairs are single points,
  6316. * and there is an implicit region between each of them, so a miss just means
  6317. * that you aren't on the very start of a region.
  6318. *
  6319. * @param aNeedle The element you are looking for.
  6320. * @param aHaystack The array that is being searched.
  6321. * @param aCompare A function which takes the needle and an element in the
  6322. * array and returns -1, 0, or 1 depending on whether the needle is less
  6323. * than, equal to, or greater than the element, respectively.
  6324. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  6325. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  6326. * closest element that is smaller than or greater than the one we are
  6327. * searching for, respectively, if the exact element cannot be found.
  6328. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  6329. */
  6330. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  6331. if (aHaystack.length === 0) {
  6332. return -1;
  6333. }
  6334. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  6335. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  6336. if (index < 0) {
  6337. return -1;
  6338. }
  6339. // We have found either the exact element, or the next-closest element than
  6340. // the one we are searching for. However, there may be more than one such
  6341. // element. Make sure we always return the smallest of these.
  6342. while (index - 1 >= 0) {
  6343. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  6344. break;
  6345. }
  6346. --index;
  6347. }
  6348. return index;
  6349. };
  6350. });
  6351. var binarySearch_1 = binarySearch.GREATEST_LOWER_BOUND;
  6352. var binarySearch_2 = binarySearch.LEAST_UPPER_BOUND;
  6353. var binarySearch_3 = binarySearch.search;
  6354. /* -*- Mode: js; js-indent-level: 2; -*- */
  6355. /*
  6356. * Copyright 2011 Mozilla Foundation and contributors
  6357. * Licensed under the New BSD license. See LICENSE or:
  6358. * http://opensource.org/licenses/BSD-3-Clause
  6359. */
  6360. // It turns out that some (most?) JavaScript engines don't self-host
  6361. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  6362. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  6363. // custom comparator function, calling back and forth between the VM's C++ and
  6364. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  6365. // worse generated code for the comparator function than would be optimal. In
  6366. // fact, when sorting with a comparator, these costs outweigh the benefits of
  6367. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  6368. // a ~3500ms mean speed-up in `bench/bench.html`.
  6369. /**
  6370. * Swap the elements indexed by `x` and `y` in the array `ary`.
  6371. *
  6372. * @param {Array} ary
  6373. * The array.
  6374. * @param {Number} x
  6375. * The index of the first item.
  6376. * @param {Number} y
  6377. * The index of the second item.
  6378. */
  6379. function swap(ary, x, y) {
  6380. var temp = ary[x];
  6381. ary[x] = ary[y];
  6382. ary[y] = temp;
  6383. }
  6384. /**
  6385. * Returns a random integer within the range `low .. high` inclusive.
  6386. *
  6387. * @param {Number} low
  6388. * The lower bound on the range.
  6389. * @param {Number} high
  6390. * The upper bound on the range.
  6391. */
  6392. function randomIntInRange(low, high) {
  6393. return Math.round(low + (Math.random() * (high - low)));
  6394. }
  6395. /**
  6396. * The Quick Sort algorithm.
  6397. *
  6398. * @param {Array} ary
  6399. * An array to sort.
  6400. * @param {function} comparator
  6401. * Function to use to compare two items.
  6402. * @param {Number} p
  6403. * Start index of the array
  6404. * @param {Number} r
  6405. * End index of the array
  6406. */
  6407. function doQuickSort(ary, comparator, p, r) {
  6408. // If our lower bound is less than our upper bound, we (1) partition the
  6409. // array into two pieces and (2) recurse on each half. If it is not, this is
  6410. // the empty array and our base case.
  6411. if (p < r) {
  6412. // (1) Partitioning.
  6413. //
  6414. // The partitioning chooses a pivot between `p` and `r` and moves all
  6415. // elements that are less than or equal to the pivot to the before it, and
  6416. // all the elements that are greater than it after it. The effect is that
  6417. // once partition is done, the pivot is in the exact place it will be when
  6418. // the array is put in sorted order, and it will not need to be moved
  6419. // again. This runs in O(n) time.
  6420. // Always choose a random pivot so that an input array which is reverse
  6421. // sorted does not cause O(n^2) running time.
  6422. var pivotIndex = randomIntInRange(p, r);
  6423. var i = p - 1;
  6424. swap(ary, pivotIndex, r);
  6425. var pivot = ary[r];
  6426. // Immediately after `j` is incremented in this loop, the following hold
  6427. // true:
  6428. //
  6429. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  6430. //
  6431. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  6432. for (var j = p; j < r; j++) {
  6433. if (comparator(ary[j], pivot) <= 0) {
  6434. i += 1;
  6435. swap(ary, i, j);
  6436. }
  6437. }
  6438. swap(ary, i + 1, j);
  6439. var q = i + 1;
  6440. // (2) Recurse on each half.
  6441. doQuickSort(ary, comparator, p, q - 1);
  6442. doQuickSort(ary, comparator, q + 1, r);
  6443. }
  6444. }
  6445. /**
  6446. * Sort the given array in-place with the given comparator function.
  6447. *
  6448. * @param {Array} ary
  6449. * An array to sort.
  6450. * @param {function} comparator
  6451. * Function to use to compare two items.
  6452. */
  6453. var quickSort_1 = function (ary, comparator) {
  6454. doQuickSort(ary, comparator, 0, ary.length - 1);
  6455. };
  6456. var quickSort = {
  6457. quickSort: quickSort_1
  6458. };
  6459. /* -*- Mode: js; js-indent-level: 2; -*- */
  6460. /*
  6461. * Copyright 2011 Mozilla Foundation and contributors
  6462. * Licensed under the New BSD license. See LICENSE or:
  6463. * http://opensource.org/licenses/BSD-3-Clause
  6464. */
  6465. var ArraySet$2 = arraySet.ArraySet;
  6466. var quickSort$1 = quickSort.quickSort;
  6467. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  6468. var sourceMap = aSourceMap;
  6469. if (typeof aSourceMap === 'string') {
  6470. sourceMap = util.parseSourceMapInput(aSourceMap);
  6471. }
  6472. return sourceMap.sections != null
  6473. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  6474. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  6475. }
  6476. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  6477. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  6478. };
  6479. /**
  6480. * The version of the source mapping spec that we are consuming.
  6481. */
  6482. SourceMapConsumer.prototype._version = 3;
  6483. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  6484. // parsed mapping coordinates from the source map's "mappings" attribute. They
  6485. // are lazily instantiated, accessed via the `_generatedMappings` and
  6486. // `_originalMappings` getters respectively, and we only parse the mappings
  6487. // and create these arrays once queried for a source location. We jump through
  6488. // these hoops because there can be many thousands of mappings, and parsing
  6489. // them is expensive, so we only want to do it if we must.
  6490. //
  6491. // Each object in the arrays is of the form:
  6492. //
  6493. // {
  6494. // generatedLine: The line number in the generated code,
  6495. // generatedColumn: The column number in the generated code,
  6496. // source: The path to the original source file that generated this
  6497. // chunk of code,
  6498. // originalLine: The line number in the original source that
  6499. // corresponds to this chunk of generated code,
  6500. // originalColumn: The column number in the original source that
  6501. // corresponds to this chunk of generated code,
  6502. // name: The name of the original symbol which generated this chunk of
  6503. // code.
  6504. // }
  6505. //
  6506. // All properties except for `generatedLine` and `generatedColumn` can be
  6507. // `null`.
  6508. //
  6509. // `_generatedMappings` is ordered by the generated positions.
  6510. //
  6511. // `_originalMappings` is ordered by the original positions.
  6512. SourceMapConsumer.prototype.__generatedMappings = null;
  6513. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  6514. configurable: true,
  6515. enumerable: true,
  6516. get: function () {
  6517. if (!this.__generatedMappings) {
  6518. this._parseMappings(this._mappings, this.sourceRoot);
  6519. }
  6520. return this.__generatedMappings;
  6521. }
  6522. });
  6523. SourceMapConsumer.prototype.__originalMappings = null;
  6524. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  6525. configurable: true,
  6526. enumerable: true,
  6527. get: function () {
  6528. if (!this.__originalMappings) {
  6529. this._parseMappings(this._mappings, this.sourceRoot);
  6530. }
  6531. return this.__originalMappings;
  6532. }
  6533. });
  6534. SourceMapConsumer.prototype._charIsMappingSeparator =
  6535. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  6536. var c = aStr.charAt(index);
  6537. return c === ";" || c === ",";
  6538. };
  6539. /**
  6540. * Parse the mappings in a string in to a data structure which we can easily
  6541. * query (the ordered arrays in the `this.__generatedMappings` and
  6542. * `this.__originalMappings` properties).
  6543. */
  6544. SourceMapConsumer.prototype._parseMappings =
  6545. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  6546. throw new Error("Subclasses must implement _parseMappings");
  6547. };
  6548. SourceMapConsumer.GENERATED_ORDER = 1;
  6549. SourceMapConsumer.ORIGINAL_ORDER = 2;
  6550. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  6551. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  6552. /**
  6553. * Iterate over each mapping between an original source/line/column and a
  6554. * generated line/column in this source map.
  6555. *
  6556. * @param Function aCallback
  6557. * The function that is called with each mapping.
  6558. * @param Object aContext
  6559. * Optional. If specified, this object will be the value of `this` every
  6560. * time that `aCallback` is called.
  6561. * @param aOrder
  6562. * Either `SourceMapConsumer.GENERATED_ORDER` or
  6563. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  6564. * iterate over the mappings sorted by the generated file's line/column
  6565. * order or the original's source/line/column order, respectively. Defaults to
  6566. * `SourceMapConsumer.GENERATED_ORDER`.
  6567. */
  6568. SourceMapConsumer.prototype.eachMapping =
  6569. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  6570. var context = aContext || null;
  6571. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  6572. var mappings;
  6573. switch (order) {
  6574. case SourceMapConsumer.GENERATED_ORDER:
  6575. mappings = this._generatedMappings;
  6576. break;
  6577. case SourceMapConsumer.ORIGINAL_ORDER:
  6578. mappings = this._originalMappings;
  6579. break;
  6580. default:
  6581. throw new Error("Unknown order of iteration.");
  6582. }
  6583. var sourceRoot = this.sourceRoot;
  6584. mappings.map(function (mapping) {
  6585. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  6586. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  6587. return {
  6588. source: source,
  6589. generatedLine: mapping.generatedLine,
  6590. generatedColumn: mapping.generatedColumn,
  6591. originalLine: mapping.originalLine,
  6592. originalColumn: mapping.originalColumn,
  6593. name: mapping.name === null ? null : this._names.at(mapping.name)
  6594. };
  6595. }, this).forEach(aCallback, context);
  6596. };
  6597. /**
  6598. * Returns all generated line and column information for the original source,
  6599. * line, and column provided. If no column is provided, returns all mappings
  6600. * corresponding to a either the line we are searching for or the next
  6601. * closest line that has any mappings. Otherwise, returns all mappings
  6602. * corresponding to the given line and either the column we are searching for
  6603. * or the next closest column that has any offsets.
  6604. *
  6605. * The only argument is an object with the following properties:
  6606. *
  6607. * - source: The filename of the original source.
  6608. * - line: The line number in the original source. The line number is 1-based.
  6609. * - column: Optional. the column number in the original source.
  6610. * The column number is 0-based.
  6611. *
  6612. * and an array of objects is returned, each with the following properties:
  6613. *
  6614. * - line: The line number in the generated source, or null. The
  6615. * line number is 1-based.
  6616. * - column: The column number in the generated source, or null.
  6617. * The column number is 0-based.
  6618. */
  6619. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  6620. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  6621. var line = util.getArg(aArgs, 'line');
  6622. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  6623. // returns the index of the closest mapping less than the needle. By
  6624. // setting needle.originalColumn to 0, we thus find the last mapping for
  6625. // the given line, provided such a mapping exists.
  6626. var needle = {
  6627. source: util.getArg(aArgs, 'source'),
  6628. originalLine: line,
  6629. originalColumn: util.getArg(aArgs, 'column', 0)
  6630. };
  6631. needle.source = this._findSourceIndex(needle.source);
  6632. if (needle.source < 0) {
  6633. return [];
  6634. }
  6635. var mappings = [];
  6636. var index = this._findMapping(needle,
  6637. this._originalMappings,
  6638. "originalLine",
  6639. "originalColumn",
  6640. util.compareByOriginalPositions,
  6641. binarySearch.LEAST_UPPER_BOUND);
  6642. if (index >= 0) {
  6643. var mapping = this._originalMappings[index];
  6644. if (aArgs.column === undefined) {
  6645. var originalLine = mapping.originalLine;
  6646. // Iterate until either we run out of mappings, or we run into
  6647. // a mapping for a different line than the one we found. Since
  6648. // mappings are sorted, this is guaranteed to find all mappings for
  6649. // the line we found.
  6650. while (mapping && mapping.originalLine === originalLine) {
  6651. mappings.push({
  6652. line: util.getArg(mapping, 'generatedLine', null),
  6653. column: util.getArg(mapping, 'generatedColumn', null),
  6654. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  6655. });
  6656. mapping = this._originalMappings[++index];
  6657. }
  6658. } else {
  6659. var originalColumn = mapping.originalColumn;
  6660. // Iterate until either we run out of mappings, or we run into
  6661. // a mapping for a different line than the one we were searching for.
  6662. // Since mappings are sorted, this is guaranteed to find all mappings for
  6663. // the line we are searching for.
  6664. while (mapping &&
  6665. mapping.originalLine === line &&
  6666. mapping.originalColumn == originalColumn) {
  6667. mappings.push({
  6668. line: util.getArg(mapping, 'generatedLine', null),
  6669. column: util.getArg(mapping, 'generatedColumn', null),
  6670. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  6671. });
  6672. mapping = this._originalMappings[++index];
  6673. }
  6674. }
  6675. }
  6676. return mappings;
  6677. };
  6678. var SourceMapConsumer_1 = SourceMapConsumer;
  6679. /**
  6680. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  6681. * query for information about the original file positions by giving it a file
  6682. * position in the generated source.
  6683. *
  6684. * The first parameter is the raw source map (either as a JSON string, or
  6685. * already parsed to an object). According to the spec, source maps have the
  6686. * following attributes:
  6687. *
  6688. * - version: Which version of the source map spec this map is following.
  6689. * - sources: An array of URLs to the original source files.
  6690. * - names: An array of identifiers which can be referrenced by individual mappings.
  6691. * - sourceRoot: Optional. The URL root from which all sources are relative.
  6692. * - sourcesContent: Optional. An array of contents of the original source files.
  6693. * - mappings: A string of base64 VLQs which contain the actual mappings.
  6694. * - file: Optional. The generated file this source map is associated with.
  6695. *
  6696. * Here is an example source map, taken from the source map spec[0]:
  6697. *
  6698. * {
  6699. * version : 3,
  6700. * file: "out.js",
  6701. * sourceRoot : "",
  6702. * sources: ["foo.js", "bar.js"],
  6703. * names: ["src", "maps", "are", "fun"],
  6704. * mappings: "AA,AB;;ABCDE;"
  6705. * }
  6706. *
  6707. * The second parameter, if given, is a string whose value is the URL
  6708. * at which the source map was found. This URL is used to compute the
  6709. * sources array.
  6710. *
  6711. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  6712. */
  6713. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  6714. var sourceMap = aSourceMap;
  6715. if (typeof aSourceMap === 'string') {
  6716. sourceMap = util.parseSourceMapInput(aSourceMap);
  6717. }
  6718. var version = util.getArg(sourceMap, 'version');
  6719. var sources = util.getArg(sourceMap, 'sources');
  6720. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  6721. // requires the array) to play nice here.
  6722. var names = util.getArg(sourceMap, 'names', []);
  6723. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  6724. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  6725. var mappings = util.getArg(sourceMap, 'mappings');
  6726. var file = util.getArg(sourceMap, 'file', null);
  6727. // Once again, Sass deviates from the spec and supplies the version as a
  6728. // string rather than a number, so we use loose equality checking here.
  6729. if (version != this._version) {
  6730. throw new Error('Unsupported version: ' + version);
  6731. }
  6732. if (sourceRoot) {
  6733. sourceRoot = util.normalize(sourceRoot);
  6734. }
  6735. sources = sources
  6736. .map(String)
  6737. // Some source maps produce relative source paths like "./foo.js" instead of
  6738. // "foo.js". Normalize these first so that future comparisons will succeed.
  6739. // See bugzil.la/1090768.
  6740. .map(util.normalize)
  6741. // Always ensure that absolute sources are internally stored relative to
  6742. // the source root, if the source root is absolute. Not doing this would
  6743. // be particularly problematic when the source root is a prefix of the
  6744. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  6745. .map(function (source) {
  6746. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  6747. ? util.relative(sourceRoot, source)
  6748. : source;
  6749. });
  6750. // Pass `true` below to allow duplicate names and sources. While source maps
  6751. // are intended to be compressed and deduplicated, the TypeScript compiler
  6752. // sometimes generates source maps with duplicates in them. See Github issue
  6753. // #72 and bugzil.la/889492.
  6754. this._names = ArraySet$2.fromArray(names.map(String), true);
  6755. this._sources = ArraySet$2.fromArray(sources, true);
  6756. this._absoluteSources = this._sources.toArray().map(function (s) {
  6757. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  6758. });
  6759. this.sourceRoot = sourceRoot;
  6760. this.sourcesContent = sourcesContent;
  6761. this._mappings = mappings;
  6762. this._sourceMapURL = aSourceMapURL;
  6763. this.file = file;
  6764. }
  6765. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  6766. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  6767. /**
  6768. * Utility function to find the index of a source. Returns -1 if not
  6769. * found.
  6770. */
  6771. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  6772. var relativeSource = aSource;
  6773. if (this.sourceRoot != null) {
  6774. relativeSource = util.relative(this.sourceRoot, relativeSource);
  6775. }
  6776. if (this._sources.has(relativeSource)) {
  6777. return this._sources.indexOf(relativeSource);
  6778. }
  6779. // Maybe aSource is an absolute URL as returned by |sources|. In
  6780. // this case we can't simply undo the transform.
  6781. var i;
  6782. for (i = 0; i < this._absoluteSources.length; ++i) {
  6783. if (this._absoluteSources[i] == aSource) {
  6784. return i;
  6785. }
  6786. }
  6787. return -1;
  6788. };
  6789. /**
  6790. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  6791. *
  6792. * @param SourceMapGenerator aSourceMap
  6793. * The source map that will be consumed.
  6794. * @param String aSourceMapURL
  6795. * The URL at which the source map can be found (optional)
  6796. * @returns BasicSourceMapConsumer
  6797. */
  6798. BasicSourceMapConsumer.fromSourceMap =
  6799. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  6800. var smc = Object.create(BasicSourceMapConsumer.prototype);
  6801. var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
  6802. var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
  6803. smc.sourceRoot = aSourceMap._sourceRoot;
  6804. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  6805. smc.sourceRoot);
  6806. smc.file = aSourceMap._file;
  6807. smc._sourceMapURL = aSourceMapURL;
  6808. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  6809. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  6810. });
  6811. // Because we are modifying the entries (by converting string sources and
  6812. // names to indices into the sources and names ArraySets), we have to make
  6813. // a copy of the entry or else bad things happen. Shared mutable state
  6814. // strikes again! See github issue #191.
  6815. var generatedMappings = aSourceMap._mappings.toArray().slice();
  6816. var destGeneratedMappings = smc.__generatedMappings = [];
  6817. var destOriginalMappings = smc.__originalMappings = [];
  6818. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  6819. var srcMapping = generatedMappings[i];
  6820. var destMapping = new Mapping;
  6821. destMapping.generatedLine = srcMapping.generatedLine;
  6822. destMapping.generatedColumn = srcMapping.generatedColumn;
  6823. if (srcMapping.source) {
  6824. destMapping.source = sources.indexOf(srcMapping.source);
  6825. destMapping.originalLine = srcMapping.originalLine;
  6826. destMapping.originalColumn = srcMapping.originalColumn;
  6827. if (srcMapping.name) {
  6828. destMapping.name = names.indexOf(srcMapping.name);
  6829. }
  6830. destOriginalMappings.push(destMapping);
  6831. }
  6832. destGeneratedMappings.push(destMapping);
  6833. }
  6834. quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
  6835. return smc;
  6836. };
  6837. /**
  6838. * The version of the source mapping spec that we are consuming.
  6839. */
  6840. BasicSourceMapConsumer.prototype._version = 3;
  6841. /**
  6842. * The list of original sources.
  6843. */
  6844. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  6845. get: function () {
  6846. return this._absoluteSources.slice();
  6847. }
  6848. });
  6849. /**
  6850. * Provide the JIT with a nice shape / hidden class.
  6851. */
  6852. function Mapping() {
  6853. this.generatedLine = 0;
  6854. this.generatedColumn = 0;
  6855. this.source = null;
  6856. this.originalLine = null;
  6857. this.originalColumn = null;
  6858. this.name = null;
  6859. }
  6860. /**
  6861. * Parse the mappings in a string in to a data structure which we can easily
  6862. * query (the ordered arrays in the `this.__generatedMappings` and
  6863. * `this.__originalMappings` properties).
  6864. */
  6865. BasicSourceMapConsumer.prototype._parseMappings =
  6866. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  6867. var generatedLine = 1;
  6868. var previousGeneratedColumn = 0;
  6869. var previousOriginalLine = 0;
  6870. var previousOriginalColumn = 0;
  6871. var previousSource = 0;
  6872. var previousName = 0;
  6873. var length = aStr.length;
  6874. var index = 0;
  6875. var cachedSegments = {};
  6876. var temp = {};
  6877. var originalMappings = [];
  6878. var generatedMappings = [];
  6879. var mapping, str, segment, end, value;
  6880. while (index < length) {
  6881. if (aStr.charAt(index) === ';') {
  6882. generatedLine++;
  6883. index++;
  6884. previousGeneratedColumn = 0;
  6885. }
  6886. else if (aStr.charAt(index) === ',') {
  6887. index++;
  6888. }
  6889. else {
  6890. mapping = new Mapping();
  6891. mapping.generatedLine = generatedLine;
  6892. // Because each offset is encoded relative to the previous one,
  6893. // many segments often have the same encoding. We can exploit this
  6894. // fact by caching the parsed variable length fields of each segment,
  6895. // allowing us to avoid a second parse if we encounter the same
  6896. // segment again.
  6897. for (end = index; end < length; end++) {
  6898. if (this._charIsMappingSeparator(aStr, end)) {
  6899. break;
  6900. }
  6901. }
  6902. str = aStr.slice(index, end);
  6903. segment = cachedSegments[str];
  6904. if (segment) {
  6905. index += str.length;
  6906. } else {
  6907. segment = [];
  6908. while (index < end) {
  6909. base64Vlq.decode(aStr, index, temp);
  6910. value = temp.value;
  6911. index = temp.rest;
  6912. segment.push(value);
  6913. }
  6914. if (segment.length === 2) {
  6915. throw new Error('Found a source, but no line and column');
  6916. }
  6917. if (segment.length === 3) {
  6918. throw new Error('Found a source and line, but no column');
  6919. }
  6920. cachedSegments[str] = segment;
  6921. }
  6922. // Generated column.
  6923. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  6924. previousGeneratedColumn = mapping.generatedColumn;
  6925. if (segment.length > 1) {
  6926. // Original source.
  6927. mapping.source = previousSource + segment[1];
  6928. previousSource += segment[1];
  6929. // Original line.
  6930. mapping.originalLine = previousOriginalLine + segment[2];
  6931. previousOriginalLine = mapping.originalLine;
  6932. // Lines are stored 0-based
  6933. mapping.originalLine += 1;
  6934. // Original column.
  6935. mapping.originalColumn = previousOriginalColumn + segment[3];
  6936. previousOriginalColumn = mapping.originalColumn;
  6937. if (segment.length > 4) {
  6938. // Original name.
  6939. mapping.name = previousName + segment[4];
  6940. previousName += segment[4];
  6941. }
  6942. }
  6943. generatedMappings.push(mapping);
  6944. if (typeof mapping.originalLine === 'number') {
  6945. originalMappings.push(mapping);
  6946. }
  6947. }
  6948. }
  6949. quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
  6950. this.__generatedMappings = generatedMappings;
  6951. quickSort$1(originalMappings, util.compareByOriginalPositions);
  6952. this.__originalMappings = originalMappings;
  6953. };
  6954. /**
  6955. * Find the mapping that best matches the hypothetical "needle" mapping that
  6956. * we are searching for in the given "haystack" of mappings.
  6957. */
  6958. BasicSourceMapConsumer.prototype._findMapping =
  6959. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  6960. aColumnName, aComparator, aBias) {
  6961. // To return the position we are searching for, we must first find the
  6962. // mapping for the given position and then return the opposite position it
  6963. // points to. Because the mappings are sorted, we can use binary search to
  6964. // find the best mapping.
  6965. if (aNeedle[aLineName] <= 0) {
  6966. throw new TypeError('Line must be greater than or equal to 1, got '
  6967. + aNeedle[aLineName]);
  6968. }
  6969. if (aNeedle[aColumnName] < 0) {
  6970. throw new TypeError('Column must be greater than or equal to 0, got '
  6971. + aNeedle[aColumnName]);
  6972. }
  6973. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  6974. };
  6975. /**
  6976. * Compute the last column for each generated mapping. The last column is
  6977. * inclusive.
  6978. */
  6979. BasicSourceMapConsumer.prototype.computeColumnSpans =
  6980. function SourceMapConsumer_computeColumnSpans() {
  6981. for (var index = 0; index < this._generatedMappings.length; ++index) {
  6982. var mapping = this._generatedMappings[index];
  6983. // Mappings do not contain a field for the last generated columnt. We
  6984. // can come up with an optimistic estimate, however, by assuming that
  6985. // mappings are contiguous (i.e. given two consecutive mappings, the
  6986. // first mapping ends where the second one starts).
  6987. if (index + 1 < this._generatedMappings.length) {
  6988. var nextMapping = this._generatedMappings[index + 1];
  6989. if (mapping.generatedLine === nextMapping.generatedLine) {
  6990. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  6991. continue;
  6992. }
  6993. }
  6994. // The last mapping for each line spans the entire line.
  6995. mapping.lastGeneratedColumn = Infinity;
  6996. }
  6997. };
  6998. /**
  6999. * Returns the original source, line, and column information for the generated
  7000. * source's line and column positions provided. The only argument is an object
  7001. * with the following properties:
  7002. *
  7003. * - line: The line number in the generated source. The line number
  7004. * is 1-based.
  7005. * - column: The column number in the generated source. The column
  7006. * number is 0-based.
  7007. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  7008. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  7009. * closest element that is smaller than or greater than the one we are
  7010. * searching for, respectively, if the exact element cannot be found.
  7011. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  7012. *
  7013. * and an object is returned with the following properties:
  7014. *
  7015. * - source: The original source file, or null.
  7016. * - line: The line number in the original source, or null. The
  7017. * line number is 1-based.
  7018. * - column: The column number in the original source, or null. The
  7019. * column number is 0-based.
  7020. * - name: The original identifier, or null.
  7021. */
  7022. BasicSourceMapConsumer.prototype.originalPositionFor =
  7023. function SourceMapConsumer_originalPositionFor(aArgs) {
  7024. var needle = {
  7025. generatedLine: util.getArg(aArgs, 'line'),
  7026. generatedColumn: util.getArg(aArgs, 'column')
  7027. };
  7028. var index = this._findMapping(
  7029. needle,
  7030. this._generatedMappings,
  7031. "generatedLine",
  7032. "generatedColumn",
  7033. util.compareByGeneratedPositionsDeflated,
  7034. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  7035. );
  7036. if (index >= 0) {
  7037. var mapping = this._generatedMappings[index];
  7038. if (mapping.generatedLine === needle.generatedLine) {
  7039. var source = util.getArg(mapping, 'source', null);
  7040. if (source !== null) {
  7041. source = this._sources.at(source);
  7042. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  7043. }
  7044. var name = util.getArg(mapping, 'name', null);
  7045. if (name !== null) {
  7046. name = this._names.at(name);
  7047. }
  7048. return {
  7049. source: source,
  7050. line: util.getArg(mapping, 'originalLine', null),
  7051. column: util.getArg(mapping, 'originalColumn', null),
  7052. name: name
  7053. };
  7054. }
  7055. }
  7056. return {
  7057. source: null,
  7058. line: null,
  7059. column: null,
  7060. name: null
  7061. };
  7062. };
  7063. /**
  7064. * Return true if we have the source content for every source in the source
  7065. * map, false otherwise.
  7066. */
  7067. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  7068. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  7069. if (!this.sourcesContent) {
  7070. return false;
  7071. }
  7072. return this.sourcesContent.length >= this._sources.size() &&
  7073. !this.sourcesContent.some(function (sc) { return sc == null; });
  7074. };
  7075. /**
  7076. * Returns the original source content. The only argument is the url of the
  7077. * original source file. Returns null if no original source content is
  7078. * available.
  7079. */
  7080. BasicSourceMapConsumer.prototype.sourceContentFor =
  7081. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  7082. if (!this.sourcesContent) {
  7083. return null;
  7084. }
  7085. var index = this._findSourceIndex(aSource);
  7086. if (index >= 0) {
  7087. return this.sourcesContent[index];
  7088. }
  7089. var relativeSource = aSource;
  7090. if (this.sourceRoot != null) {
  7091. relativeSource = util.relative(this.sourceRoot, relativeSource);
  7092. }
  7093. var url;
  7094. if (this.sourceRoot != null
  7095. && (url = util.urlParse(this.sourceRoot))) {
  7096. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  7097. // many users. We can help them out when they expect file:// URIs to
  7098. // behave like it would if they were running a local HTTP server. See
  7099. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  7100. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  7101. if (url.scheme == "file"
  7102. && this._sources.has(fileUriAbsPath)) {
  7103. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  7104. }
  7105. if ((!url.path || url.path == "/")
  7106. && this._sources.has("/" + relativeSource)) {
  7107. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  7108. }
  7109. }
  7110. // This function is used recursively from
  7111. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  7112. // don't want to throw if we can't find the source - we just want to
  7113. // return null, so we provide a flag to exit gracefully.
  7114. if (nullOnMissing) {
  7115. return null;
  7116. }
  7117. else {
  7118. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  7119. }
  7120. };
  7121. /**
  7122. * Returns the generated line and column information for the original source,
  7123. * line, and column positions provided. The only argument is an object with
  7124. * the following properties:
  7125. *
  7126. * - source: The filename of the original source.
  7127. * - line: The line number in the original source. The line number
  7128. * is 1-based.
  7129. * - column: The column number in the original source. The column
  7130. * number is 0-based.
  7131. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  7132. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  7133. * closest element that is smaller than or greater than the one we are
  7134. * searching for, respectively, if the exact element cannot be found.
  7135. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  7136. *
  7137. * and an object is returned with the following properties:
  7138. *
  7139. * - line: The line number in the generated source, or null. The
  7140. * line number is 1-based.
  7141. * - column: The column number in the generated source, or null.
  7142. * The column number is 0-based.
  7143. */
  7144. BasicSourceMapConsumer.prototype.generatedPositionFor =
  7145. function SourceMapConsumer_generatedPositionFor(aArgs) {
  7146. var source = util.getArg(aArgs, 'source');
  7147. source = this._findSourceIndex(source);
  7148. if (source < 0) {
  7149. return {
  7150. line: null,
  7151. column: null,
  7152. lastColumn: null
  7153. };
  7154. }
  7155. var needle = {
  7156. source: source,
  7157. originalLine: util.getArg(aArgs, 'line'),
  7158. originalColumn: util.getArg(aArgs, 'column')
  7159. };
  7160. var index = this._findMapping(
  7161. needle,
  7162. this._originalMappings,
  7163. "originalLine",
  7164. "originalColumn",
  7165. util.compareByOriginalPositions,
  7166. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  7167. );
  7168. if (index >= 0) {
  7169. var mapping = this._originalMappings[index];
  7170. if (mapping.source === needle.source) {
  7171. return {
  7172. line: util.getArg(mapping, 'generatedLine', null),
  7173. column: util.getArg(mapping, 'generatedColumn', null),
  7174. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  7175. };
  7176. }
  7177. }
  7178. return {
  7179. line: null,
  7180. column: null,
  7181. lastColumn: null
  7182. };
  7183. };
  7184. var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
  7185. /**
  7186. * An IndexedSourceMapConsumer instance represents a parsed source map which
  7187. * we can query for information. It differs from BasicSourceMapConsumer in
  7188. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  7189. * input.
  7190. *
  7191. * The first parameter is a raw source map (either as a JSON string, or already
  7192. * parsed to an object). According to the spec for indexed source maps, they
  7193. * have the following attributes:
  7194. *
  7195. * - version: Which version of the source map spec this map is following.
  7196. * - file: Optional. The generated file this source map is associated with.
  7197. * - sections: A list of section definitions.
  7198. *
  7199. * Each value under the "sections" field has two fields:
  7200. * - offset: The offset into the original specified at which this section
  7201. * begins to apply, defined as an object with a "line" and "column"
  7202. * field.
  7203. * - map: A source map definition. This source map could also be indexed,
  7204. * but doesn't have to be.
  7205. *
  7206. * Instead of the "map" field, it's also possible to have a "url" field
  7207. * specifying a URL to retrieve a source map from, but that's currently
  7208. * unsupported.
  7209. *
  7210. * Here's an example source map, taken from the source map spec[0], but
  7211. * modified to omit a section which uses the "url" field.
  7212. *
  7213. * {
  7214. * version : 3,
  7215. * file: "app.js",
  7216. * sections: [{
  7217. * offset: {line:100, column:10},
  7218. * map: {
  7219. * version : 3,
  7220. * file: "section.js",
  7221. * sources: ["foo.js", "bar.js"],
  7222. * names: ["src", "maps", "are", "fun"],
  7223. * mappings: "AAAA,E;;ABCDE;"
  7224. * }
  7225. * }],
  7226. * }
  7227. *
  7228. * The second parameter, if given, is a string whose value is the URL
  7229. * at which the source map was found. This URL is used to compute the
  7230. * sources array.
  7231. *
  7232. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  7233. */
  7234. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  7235. var sourceMap = aSourceMap;
  7236. if (typeof aSourceMap === 'string') {
  7237. sourceMap = util.parseSourceMapInput(aSourceMap);
  7238. }
  7239. var version = util.getArg(sourceMap, 'version');
  7240. var sections = util.getArg(sourceMap, 'sections');
  7241. if (version != this._version) {
  7242. throw new Error('Unsupported version: ' + version);
  7243. }
  7244. this._sources = new ArraySet$2();
  7245. this._names = new ArraySet$2();
  7246. var lastOffset = {
  7247. line: -1,
  7248. column: 0
  7249. };
  7250. this._sections = sections.map(function (s) {
  7251. if (s.url) {
  7252. // The url field will require support for asynchronicity.
  7253. // See https://github.com/mozilla/source-map/issues/16
  7254. throw new Error('Support for url field in sections not implemented.');
  7255. }
  7256. var offset = util.getArg(s, 'offset');
  7257. var offsetLine = util.getArg(offset, 'line');
  7258. var offsetColumn = util.getArg(offset, 'column');
  7259. if (offsetLine < lastOffset.line ||
  7260. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  7261. throw new Error('Section offsets must be ordered and non-overlapping.');
  7262. }
  7263. lastOffset = offset;
  7264. return {
  7265. generatedOffset: {
  7266. // The offset fields are 0-based, but we use 1-based indices when
  7267. // encoding/decoding from VLQ.
  7268. generatedLine: offsetLine + 1,
  7269. generatedColumn: offsetColumn + 1
  7270. },
  7271. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  7272. }
  7273. });
  7274. }
  7275. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  7276. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  7277. /**
  7278. * The version of the source mapping spec that we are consuming.
  7279. */
  7280. IndexedSourceMapConsumer.prototype._version = 3;
  7281. /**
  7282. * The list of original sources.
  7283. */
  7284. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  7285. get: function () {
  7286. var sources = [];
  7287. for (var i = 0; i < this._sections.length; i++) {
  7288. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  7289. sources.push(this._sections[i].consumer.sources[j]);
  7290. }
  7291. }
  7292. return sources;
  7293. }
  7294. });
  7295. /**
  7296. * Returns the original source, line, and column information for the generated
  7297. * source's line and column positions provided. The only argument is an object
  7298. * with the following properties:
  7299. *
  7300. * - line: The line number in the generated source. The line number
  7301. * is 1-based.
  7302. * - column: The column number in the generated source. The column
  7303. * number is 0-based.
  7304. *
  7305. * and an object is returned with the following properties:
  7306. *
  7307. * - source: The original source file, or null.
  7308. * - line: The line number in the original source, or null. The
  7309. * line number is 1-based.
  7310. * - column: The column number in the original source, or null. The
  7311. * column number is 0-based.
  7312. * - name: The original identifier, or null.
  7313. */
  7314. IndexedSourceMapConsumer.prototype.originalPositionFor =
  7315. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  7316. var needle = {
  7317. generatedLine: util.getArg(aArgs, 'line'),
  7318. generatedColumn: util.getArg(aArgs, 'column')
  7319. };
  7320. // Find the section containing the generated position we're trying to map
  7321. // to an original position.
  7322. var sectionIndex = binarySearch.search(needle, this._sections,
  7323. function(needle, section) {
  7324. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  7325. if (cmp) {
  7326. return cmp;
  7327. }
  7328. return (needle.generatedColumn -
  7329. section.generatedOffset.generatedColumn);
  7330. });
  7331. var section = this._sections[sectionIndex];
  7332. if (!section) {
  7333. return {
  7334. source: null,
  7335. line: null,
  7336. column: null,
  7337. name: null
  7338. };
  7339. }
  7340. return section.consumer.originalPositionFor({
  7341. line: needle.generatedLine -
  7342. (section.generatedOffset.generatedLine - 1),
  7343. column: needle.generatedColumn -
  7344. (section.generatedOffset.generatedLine === needle.generatedLine
  7345. ? section.generatedOffset.generatedColumn - 1
  7346. : 0),
  7347. bias: aArgs.bias
  7348. });
  7349. };
  7350. /**
  7351. * Return true if we have the source content for every source in the source
  7352. * map, false otherwise.
  7353. */
  7354. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  7355. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  7356. return this._sections.every(function (s) {
  7357. return s.consumer.hasContentsOfAllSources();
  7358. });
  7359. };
  7360. /**
  7361. * Returns the original source content. The only argument is the url of the
  7362. * original source file. Returns null if no original source content is
  7363. * available.
  7364. */
  7365. IndexedSourceMapConsumer.prototype.sourceContentFor =
  7366. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  7367. for (var i = 0; i < this._sections.length; i++) {
  7368. var section = this._sections[i];
  7369. var content = section.consumer.sourceContentFor(aSource, true);
  7370. if (content) {
  7371. return content;
  7372. }
  7373. }
  7374. if (nullOnMissing) {
  7375. return null;
  7376. }
  7377. else {
  7378. throw new Error('"' + aSource + '" is not in the SourceMap.');
  7379. }
  7380. };
  7381. /**
  7382. * Returns the generated line and column information for the original source,
  7383. * line, and column positions provided. The only argument is an object with
  7384. * the following properties:
  7385. *
  7386. * - source: The filename of the original source.
  7387. * - line: The line number in the original source. The line number
  7388. * is 1-based.
  7389. * - column: The column number in the original source. The column
  7390. * number is 0-based.
  7391. *
  7392. * and an object is returned with the following properties:
  7393. *
  7394. * - line: The line number in the generated source, or null. The
  7395. * line number is 1-based.
  7396. * - column: The column number in the generated source, or null.
  7397. * The column number is 0-based.
  7398. */
  7399. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  7400. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  7401. for (var i = 0; i < this._sections.length; i++) {
  7402. var section = this._sections[i];
  7403. // Only consider this section if the requested source is in the list of
  7404. // sources of the consumer.
  7405. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  7406. continue;
  7407. }
  7408. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  7409. if (generatedPosition) {
  7410. var ret = {
  7411. line: generatedPosition.line +
  7412. (section.generatedOffset.generatedLine - 1),
  7413. column: generatedPosition.column +
  7414. (section.generatedOffset.generatedLine === generatedPosition.line
  7415. ? section.generatedOffset.generatedColumn - 1
  7416. : 0)
  7417. };
  7418. return ret;
  7419. }
  7420. }
  7421. return {
  7422. line: null,
  7423. column: null
  7424. };
  7425. };
  7426. /**
  7427. * Parse the mappings in a string in to a data structure which we can easily
  7428. * query (the ordered arrays in the `this.__generatedMappings` and
  7429. * `this.__originalMappings` properties).
  7430. */
  7431. IndexedSourceMapConsumer.prototype._parseMappings =
  7432. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  7433. this.__generatedMappings = [];
  7434. this.__originalMappings = [];
  7435. for (var i = 0; i < this._sections.length; i++) {
  7436. var section = this._sections[i];
  7437. var sectionMappings = section.consumer._generatedMappings;
  7438. for (var j = 0; j < sectionMappings.length; j++) {
  7439. var mapping = sectionMappings[j];
  7440. var source = section.consumer._sources.at(mapping.source);
  7441. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  7442. this._sources.add(source);
  7443. source = this._sources.indexOf(source);
  7444. var name = null;
  7445. if (mapping.name) {
  7446. name = section.consumer._names.at(mapping.name);
  7447. this._names.add(name);
  7448. name = this._names.indexOf(name);
  7449. }
  7450. // The mappings coming from the consumer for the section have
  7451. // generated positions relative to the start of the section, so we
  7452. // need to offset them to be relative to the start of the concatenated
  7453. // generated file.
  7454. var adjustedMapping = {
  7455. source: source,
  7456. generatedLine: mapping.generatedLine +
  7457. (section.generatedOffset.generatedLine - 1),
  7458. generatedColumn: mapping.generatedColumn +
  7459. (section.generatedOffset.generatedLine === mapping.generatedLine
  7460. ? section.generatedOffset.generatedColumn - 1
  7461. : 0),
  7462. originalLine: mapping.originalLine,
  7463. originalColumn: mapping.originalColumn,
  7464. name: name
  7465. };
  7466. this.__generatedMappings.push(adjustedMapping);
  7467. if (typeof adjustedMapping.originalLine === 'number') {
  7468. this.__originalMappings.push(adjustedMapping);
  7469. }
  7470. }
  7471. }
  7472. quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  7473. quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
  7474. };
  7475. var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
  7476. var sourceMapConsumer = {
  7477. SourceMapConsumer: SourceMapConsumer_1,
  7478. BasicSourceMapConsumer: BasicSourceMapConsumer_1,
  7479. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
  7480. };
  7481. /* -*- Mode: js; js-indent-level: 2; -*- */
  7482. /*
  7483. * Copyright 2011 Mozilla Foundation and contributors
  7484. * Licensed under the New BSD license. See LICENSE or:
  7485. * http://opensource.org/licenses/BSD-3-Clause
  7486. */
  7487. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  7488. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  7489. // operating systems these days (capturing the result).
  7490. var REGEX_NEWLINE = /(\r?\n)/;
  7491. // Newline character code for charCodeAt() comparisons
  7492. var NEWLINE_CODE = 10;
  7493. // Private symbol for identifying `SourceNode`s when multiple versions of
  7494. // the source-map library are loaded. This MUST NOT CHANGE across
  7495. // versions!
  7496. var isSourceNode = "$$$isSourceNode$$$";
  7497. /**
  7498. * SourceNodes provide a way to abstract over interpolating/concatenating
  7499. * snippets of generated JavaScript source code while maintaining the line and
  7500. * column information associated with the original source code.
  7501. *
  7502. * @param aLine The original line number.
  7503. * @param aColumn The original column number.
  7504. * @param aSource The original source's filename.
  7505. * @param aChunks Optional. An array of strings which are snippets of
  7506. * generated JS, or other SourceNodes.
  7507. * @param aName The original identifier.
  7508. */
  7509. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  7510. this.children = [];
  7511. this.sourceContents = {};
  7512. this.line = aLine == null ? null : aLine;
  7513. this.column = aColumn == null ? null : aColumn;
  7514. this.source = aSource == null ? null : aSource;
  7515. this.name = aName == null ? null : aName;
  7516. this[isSourceNode] = true;
  7517. if (aChunks != null) this.add(aChunks);
  7518. }
  7519. /**
  7520. * Creates a SourceNode from generated code and a SourceMapConsumer.
  7521. *
  7522. * @param aGeneratedCode The generated code
  7523. * @param aSourceMapConsumer The SourceMap for the generated code
  7524. * @param aRelativePath Optional. The path that relative sources in the
  7525. * SourceMapConsumer should be relative to.
  7526. */
  7527. SourceNode.fromStringWithSourceMap =
  7528. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  7529. // The SourceNode we want to fill with the generated code
  7530. // and the SourceMap
  7531. var node = new SourceNode();
  7532. // All even indices of this array are one line of the generated code,
  7533. // while all odd indices are the newlines between two adjacent lines
  7534. // (since `REGEX_NEWLINE` captures its match).
  7535. // Processed fragments are accessed by calling `shiftNextLine`.
  7536. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  7537. var remainingLinesIndex = 0;
  7538. var shiftNextLine = function() {
  7539. var lineContents = getNextLine();
  7540. // The last line of a file might not have a newline.
  7541. var newLine = getNextLine() || "";
  7542. return lineContents + newLine;
  7543. function getNextLine() {
  7544. return remainingLinesIndex < remainingLines.length ?
  7545. remainingLines[remainingLinesIndex++] : undefined;
  7546. }
  7547. };
  7548. // We need to remember the position of "remainingLines"
  7549. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  7550. // The generate SourceNodes we need a code range.
  7551. // To extract it current and last mapping is used.
  7552. // Here we store the last mapping.
  7553. var lastMapping = null;
  7554. aSourceMapConsumer.eachMapping(function (mapping) {
  7555. if (lastMapping !== null) {
  7556. // We add the code from "lastMapping" to "mapping":
  7557. // First check if there is a new line in between.
  7558. if (lastGeneratedLine < mapping.generatedLine) {
  7559. // Associate first line with "lastMapping"
  7560. addMappingWithCode(lastMapping, shiftNextLine());
  7561. lastGeneratedLine++;
  7562. lastGeneratedColumn = 0;
  7563. // The remaining code is added without mapping
  7564. } else {
  7565. // There is no new line in between.
  7566. // Associate the code between "lastGeneratedColumn" and
  7567. // "mapping.generatedColumn" with "lastMapping"
  7568. var nextLine = remainingLines[remainingLinesIndex] || '';
  7569. var code = nextLine.substr(0, mapping.generatedColumn -
  7570. lastGeneratedColumn);
  7571. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  7572. lastGeneratedColumn);
  7573. lastGeneratedColumn = mapping.generatedColumn;
  7574. addMappingWithCode(lastMapping, code);
  7575. // No more remaining code, continue
  7576. lastMapping = mapping;
  7577. return;
  7578. }
  7579. }
  7580. // We add the generated code until the first mapping
  7581. // to the SourceNode without any mapping.
  7582. // Each line is added as separate string.
  7583. while (lastGeneratedLine < mapping.generatedLine) {
  7584. node.add(shiftNextLine());
  7585. lastGeneratedLine++;
  7586. }
  7587. if (lastGeneratedColumn < mapping.generatedColumn) {
  7588. var nextLine = remainingLines[remainingLinesIndex] || '';
  7589. node.add(nextLine.substr(0, mapping.generatedColumn));
  7590. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  7591. lastGeneratedColumn = mapping.generatedColumn;
  7592. }
  7593. lastMapping = mapping;
  7594. }, this);
  7595. // We have processed all mappings.
  7596. if (remainingLinesIndex < remainingLines.length) {
  7597. if (lastMapping) {
  7598. // Associate the remaining code in the current line with "lastMapping"
  7599. addMappingWithCode(lastMapping, shiftNextLine());
  7600. }
  7601. // and add the remaining lines without any mapping
  7602. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  7603. }
  7604. // Copy sourcesContent into SourceNode
  7605. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  7606. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  7607. if (content != null) {
  7608. if (aRelativePath != null) {
  7609. sourceFile = util.join(aRelativePath, sourceFile);
  7610. }
  7611. node.setSourceContent(sourceFile, content);
  7612. }
  7613. });
  7614. return node;
  7615. function addMappingWithCode(mapping, code) {
  7616. if (mapping === null || mapping.source === undefined) {
  7617. node.add(code);
  7618. } else {
  7619. var source = aRelativePath
  7620. ? util.join(aRelativePath, mapping.source)
  7621. : mapping.source;
  7622. node.add(new SourceNode(mapping.originalLine,
  7623. mapping.originalColumn,
  7624. source,
  7625. code,
  7626. mapping.name));
  7627. }
  7628. }
  7629. };
  7630. /**
  7631. * Add a chunk of generated JS to this source node.
  7632. *
  7633. * @param aChunk A string snippet of generated JS code, another instance of
  7634. * SourceNode, or an array where each member is one of those things.
  7635. */
  7636. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  7637. if (Array.isArray(aChunk)) {
  7638. aChunk.forEach(function (chunk) {
  7639. this.add(chunk);
  7640. }, this);
  7641. }
  7642. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  7643. if (aChunk) {
  7644. this.children.push(aChunk);
  7645. }
  7646. }
  7647. else {
  7648. throw new TypeError(
  7649. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  7650. );
  7651. }
  7652. return this;
  7653. };
  7654. /**
  7655. * Add a chunk of generated JS to the beginning of this source node.
  7656. *
  7657. * @param aChunk A string snippet of generated JS code, another instance of
  7658. * SourceNode, or an array where each member is one of those things.
  7659. */
  7660. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  7661. if (Array.isArray(aChunk)) {
  7662. for (var i = aChunk.length-1; i >= 0; i--) {
  7663. this.prepend(aChunk[i]);
  7664. }
  7665. }
  7666. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  7667. this.children.unshift(aChunk);
  7668. }
  7669. else {
  7670. throw new TypeError(
  7671. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  7672. );
  7673. }
  7674. return this;
  7675. };
  7676. /**
  7677. * Walk over the tree of JS snippets in this node and its children. The
  7678. * walking function is called once for each snippet of JS and is passed that
  7679. * snippet and the its original associated source's line/column location.
  7680. *
  7681. * @param aFn The traversal function.
  7682. */
  7683. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  7684. var chunk;
  7685. for (var i = 0, len = this.children.length; i < len; i++) {
  7686. chunk = this.children[i];
  7687. if (chunk[isSourceNode]) {
  7688. chunk.walk(aFn);
  7689. }
  7690. else {
  7691. if (chunk !== '') {
  7692. aFn(chunk, { source: this.source,
  7693. line: this.line,
  7694. column: this.column,
  7695. name: this.name });
  7696. }
  7697. }
  7698. }
  7699. };
  7700. /**
  7701. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  7702. * each of `this.children`.
  7703. *
  7704. * @param aSep The separator.
  7705. */
  7706. SourceNode.prototype.join = function SourceNode_join(aSep) {
  7707. var newChildren;
  7708. var i;
  7709. var len = this.children.length;
  7710. if (len > 0) {
  7711. newChildren = [];
  7712. for (i = 0; i < len-1; i++) {
  7713. newChildren.push(this.children[i]);
  7714. newChildren.push(aSep);
  7715. }
  7716. newChildren.push(this.children[i]);
  7717. this.children = newChildren;
  7718. }
  7719. return this;
  7720. };
  7721. /**
  7722. * Call String.prototype.replace on the very right-most source snippet. Useful
  7723. * for trimming whitespace from the end of a source node, etc.
  7724. *
  7725. * @param aPattern The pattern to replace.
  7726. * @param aReplacement The thing to replace the pattern with.
  7727. */
  7728. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  7729. var lastChild = this.children[this.children.length - 1];
  7730. if (lastChild[isSourceNode]) {
  7731. lastChild.replaceRight(aPattern, aReplacement);
  7732. }
  7733. else if (typeof lastChild === 'string') {
  7734. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  7735. }
  7736. else {
  7737. this.children.push(''.replace(aPattern, aReplacement));
  7738. }
  7739. return this;
  7740. };
  7741. /**
  7742. * Set the source content for a source file. This will be added to the SourceMapGenerator
  7743. * in the sourcesContent field.
  7744. *
  7745. * @param aSourceFile The filename of the source file
  7746. * @param aSourceContent The content of the source file
  7747. */
  7748. SourceNode.prototype.setSourceContent =
  7749. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  7750. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  7751. };
  7752. /**
  7753. * Walk over the tree of SourceNodes. The walking function is called for each
  7754. * source file content and is passed the filename and source content.
  7755. *
  7756. * @param aFn The traversal function.
  7757. */
  7758. SourceNode.prototype.walkSourceContents =
  7759. function SourceNode_walkSourceContents(aFn) {
  7760. for (var i = 0, len = this.children.length; i < len; i++) {
  7761. if (this.children[i][isSourceNode]) {
  7762. this.children[i].walkSourceContents(aFn);
  7763. }
  7764. }
  7765. var sources = Object.keys(this.sourceContents);
  7766. for (var i = 0, len = sources.length; i < len; i++) {
  7767. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  7768. }
  7769. };
  7770. /**
  7771. * Return the string representation of this source node. Walks over the tree
  7772. * and concatenates all the various snippets together to one string.
  7773. */
  7774. SourceNode.prototype.toString = function SourceNode_toString() {
  7775. var str = "";
  7776. this.walk(function (chunk) {
  7777. str += chunk;
  7778. });
  7779. return str;
  7780. };
  7781. /**
  7782. * Returns the string representation of this source node along with a source
  7783. * map.
  7784. */
  7785. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  7786. var generated = {
  7787. code: "",
  7788. line: 1,
  7789. column: 0
  7790. };
  7791. var map = new SourceMapGenerator$1(aArgs);
  7792. var sourceMappingActive = false;
  7793. var lastOriginalSource = null;
  7794. var lastOriginalLine = null;
  7795. var lastOriginalColumn = null;
  7796. var lastOriginalName = null;
  7797. this.walk(function (chunk, original) {
  7798. generated.code += chunk;
  7799. if (original.source !== null
  7800. && original.line !== null
  7801. && original.column !== null) {
  7802. if(lastOriginalSource !== original.source
  7803. || lastOriginalLine !== original.line
  7804. || lastOriginalColumn !== original.column
  7805. || lastOriginalName !== original.name) {
  7806. map.addMapping({
  7807. source: original.source,
  7808. original: {
  7809. line: original.line,
  7810. column: original.column
  7811. },
  7812. generated: {
  7813. line: generated.line,
  7814. column: generated.column
  7815. },
  7816. name: original.name
  7817. });
  7818. }
  7819. lastOriginalSource = original.source;
  7820. lastOriginalLine = original.line;
  7821. lastOriginalColumn = original.column;
  7822. lastOriginalName = original.name;
  7823. sourceMappingActive = true;
  7824. } else if (sourceMappingActive) {
  7825. map.addMapping({
  7826. generated: {
  7827. line: generated.line,
  7828. column: generated.column
  7829. }
  7830. });
  7831. lastOriginalSource = null;
  7832. sourceMappingActive = false;
  7833. }
  7834. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  7835. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  7836. generated.line++;
  7837. generated.column = 0;
  7838. // Mappings end at eol
  7839. if (idx + 1 === length) {
  7840. lastOriginalSource = null;
  7841. sourceMappingActive = false;
  7842. } else if (sourceMappingActive) {
  7843. map.addMapping({
  7844. source: original.source,
  7845. original: {
  7846. line: original.line,
  7847. column: original.column
  7848. },
  7849. generated: {
  7850. line: generated.line,
  7851. column: generated.column
  7852. },
  7853. name: original.name
  7854. });
  7855. }
  7856. } else {
  7857. generated.column++;
  7858. }
  7859. }
  7860. });
  7861. this.walkSourceContents(function (sourceFile, sourceContent) {
  7862. map.setSourceContent(sourceFile, sourceContent);
  7863. });
  7864. return { code: generated.code, map: map };
  7865. };
  7866. var SourceNode_1 = SourceNode;
  7867. var sourceNode = {
  7868. SourceNode: SourceNode_1
  7869. };
  7870. /*
  7871. * Copyright 2009-2011 Mozilla Foundation and contributors
  7872. * Licensed under the New BSD license. See LICENSE.txt or:
  7873. * http://opensource.org/licenses/BSD-3-Clause
  7874. */
  7875. var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
  7876. var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
  7877. var SourceNode$1 = sourceNode.SourceNode;
  7878. var sourceMap = {
  7879. SourceMapGenerator: SourceMapGenerator$2,
  7880. SourceMapConsumer: SourceMapConsumer$1,
  7881. SourceNode: SourceNode$1
  7882. };
  7883. var util$1 = createCommonjsModule(function (module, exports) {
  7884. var __importDefault = (this && this.__importDefault) || function (mod) {
  7885. return (mod && mod.__esModule) ? mod : { "default": mod };
  7886. };
  7887. var __importStar = (this && this.__importStar) || function (mod) {
  7888. if (mod && mod.__esModule) return mod;
  7889. var result = {};
  7890. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  7891. result["default"] = mod;
  7892. return result;
  7893. };
  7894. Object.defineProperty(exports, "__esModule", { value: true });
  7895. var assert_1 = __importDefault(assert);
  7896. var types = __importStar(main);
  7897. var n = types.namedTypes;
  7898. var source_map_1 = __importDefault(sourceMap);
  7899. var SourceMapConsumer = source_map_1.default.SourceMapConsumer;
  7900. var SourceMapGenerator = source_map_1.default.SourceMapGenerator;
  7901. var hasOwn = Object.prototype.hasOwnProperty;
  7902. function getOption(options, key, defaultValue) {
  7903. if (options && hasOwn.call(options, key)) {
  7904. return options[key];
  7905. }
  7906. return defaultValue;
  7907. }
  7908. exports.getOption = getOption;
  7909. function getUnionOfKeys() {
  7910. var args = [];
  7911. for (var _i = 0; _i < arguments.length; _i++) {
  7912. args[_i] = arguments[_i];
  7913. }
  7914. var result = {};
  7915. var argc = args.length;
  7916. for (var i = 0; i < argc; ++i) {
  7917. var keys = Object.keys(args[i]);
  7918. var keyCount = keys.length;
  7919. for (var j = 0; j < keyCount; ++j) {
  7920. result[keys[j]] = true;
  7921. }
  7922. }
  7923. return result;
  7924. }
  7925. exports.getUnionOfKeys = getUnionOfKeys;
  7926. function comparePos(pos1, pos2) {
  7927. return (pos1.line - pos2.line) || (pos1.column - pos2.column);
  7928. }
  7929. exports.comparePos = comparePos;
  7930. function copyPos(pos) {
  7931. return {
  7932. line: pos.line,
  7933. column: pos.column
  7934. };
  7935. }
  7936. exports.copyPos = copyPos;
  7937. function composeSourceMaps(formerMap, latterMap) {
  7938. if (formerMap) {
  7939. if (!latterMap) {
  7940. return formerMap;
  7941. }
  7942. }
  7943. else {
  7944. return latterMap || null;
  7945. }
  7946. var smcFormer = new SourceMapConsumer(formerMap);
  7947. var smcLatter = new SourceMapConsumer(latterMap);
  7948. var smg = new SourceMapGenerator({
  7949. file: latterMap.file,
  7950. sourceRoot: latterMap.sourceRoot
  7951. });
  7952. var sourcesToContents = {};
  7953. smcLatter.eachMapping(function (mapping) {
  7954. var origPos = smcFormer.originalPositionFor({
  7955. line: mapping.originalLine,
  7956. column: mapping.originalColumn
  7957. });
  7958. var sourceName = origPos.source;
  7959. if (sourceName === null) {
  7960. return;
  7961. }
  7962. smg.addMapping({
  7963. source: sourceName,
  7964. original: copyPos(origPos),
  7965. generated: {
  7966. line: mapping.generatedLine,
  7967. column: mapping.generatedColumn
  7968. },
  7969. name: mapping.name
  7970. });
  7971. var sourceContent = smcFormer.sourceContentFor(sourceName);
  7972. if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) {
  7973. sourcesToContents[sourceName] = sourceContent;
  7974. smg.setSourceContent(sourceName, sourceContent);
  7975. }
  7976. });
  7977. return smg.toJSON();
  7978. }
  7979. exports.composeSourceMaps = composeSourceMaps;
  7980. function getTrueLoc(node, lines) {
  7981. // It's possible that node is newly-created (not parsed by Esprima),
  7982. // in which case it probably won't have a .loc property (or an
  7983. // .original property for that matter). That's fine; we'll just
  7984. // pretty-print it as usual.
  7985. if (!node.loc) {
  7986. return null;
  7987. }
  7988. var result = {
  7989. start: node.loc.start,
  7990. end: node.loc.end
  7991. };
  7992. function include(node) {
  7993. expandLoc(result, node.loc);
  7994. }
  7995. // If the node is an export declaration and its .declaration has any
  7996. // decorators, their locations might contribute to the true start/end
  7997. // positions of the export declaration node.
  7998. if (node.declaration &&
  7999. node.declaration.decorators &&
  8000. isExportDeclaration(node)) {
  8001. node.declaration.decorators.forEach(include);
  8002. }
  8003. if (comparePos(result.start, result.end) < 0) {
  8004. // Trim leading whitespace.
  8005. result.start = copyPos(result.start);
  8006. lines.skipSpaces(result.start, false, true);
  8007. if (comparePos(result.start, result.end) < 0) {
  8008. // Trim trailing whitespace, if the end location is not already the
  8009. // same as the start location.
  8010. result.end = copyPos(result.end);
  8011. lines.skipSpaces(result.end, true, true);
  8012. }
  8013. }
  8014. // If the node has any comments, their locations might contribute to
  8015. // the true start/end positions of the node.
  8016. if (node.comments) {
  8017. node.comments.forEach(include);
  8018. }
  8019. return result;
  8020. }
  8021. exports.getTrueLoc = getTrueLoc;
  8022. function expandLoc(parentLoc, childLoc) {
  8023. if (parentLoc && childLoc) {
  8024. if (comparePos(childLoc.start, parentLoc.start) < 0) {
  8025. parentLoc.start = childLoc.start;
  8026. }
  8027. if (comparePos(parentLoc.end, childLoc.end) < 0) {
  8028. parentLoc.end = childLoc.end;
  8029. }
  8030. }
  8031. }
  8032. function fixFaultyLocations(node, lines) {
  8033. var loc = node.loc;
  8034. if (loc) {
  8035. if (loc.start.line < 1) {
  8036. loc.start.line = 1;
  8037. }
  8038. if (loc.end.line < 1) {
  8039. loc.end.line = 1;
  8040. }
  8041. }
  8042. if (node.type === "File") {
  8043. // Babylon returns File nodes whose .loc.{start,end} do not include
  8044. // leading or trailing whitespace.
  8045. loc.start = lines.firstPos();
  8046. loc.end = lines.lastPos();
  8047. }
  8048. fixForLoopHead(node, lines);
  8049. fixTemplateLiteral(node, lines);
  8050. if (loc && node.decorators) {
  8051. // Expand the .loc of the node responsible for printing the decorators
  8052. // (here, the decorated node) so that it includes node.decorators.
  8053. node.decorators.forEach(function (decorator) {
  8054. expandLoc(loc, decorator.loc);
  8055. });
  8056. }
  8057. else if (node.declaration && isExportDeclaration(node)) {
  8058. // Nullify .loc information for the child declaration so that we never
  8059. // try to reprint it without also reprinting the export declaration.
  8060. node.declaration.loc = null;
  8061. // Expand the .loc of the node responsible for printing the decorators
  8062. // (here, the export declaration) so that it includes node.decorators.
  8063. var decorators = node.declaration.decorators;
  8064. if (decorators) {
  8065. decorators.forEach(function (decorator) {
  8066. expandLoc(loc, decorator.loc);
  8067. });
  8068. }
  8069. }
  8070. else if ((n.MethodDefinition && n.MethodDefinition.check(node)) ||
  8071. (n.Property.check(node) && (node.method || node.shorthand))) {
  8072. // If the node is a MethodDefinition or a .method or .shorthand
  8073. // Property, then the location information stored in
  8074. // node.value.loc is very likely untrustworthy (just the {body}
  8075. // part of a method, or nothing in the case of shorthand
  8076. // properties), so we null out that information to prevent
  8077. // accidental reuse of bogus source code during reprinting.
  8078. node.value.loc = null;
  8079. if (n.FunctionExpression.check(node.value)) {
  8080. // FunctionExpression method values should be anonymous,
  8081. // because their .id fields are ignored anyway.
  8082. node.value.id = null;
  8083. }
  8084. }
  8085. else if (node.type === "ObjectTypeProperty") {
  8086. var loc = node.loc;
  8087. var end = loc && loc.end;
  8088. if (end) {
  8089. end = copyPos(end);
  8090. if (lines.prevPos(end) &&
  8091. lines.charAt(end) === ",") {
  8092. // Some parsers accidentally include trailing commas in the
  8093. // .loc.end information for ObjectTypeProperty nodes.
  8094. if ((end = lines.skipSpaces(end, true, true))) {
  8095. loc.end = end;
  8096. }
  8097. }
  8098. }
  8099. }
  8100. }
  8101. exports.fixFaultyLocations = fixFaultyLocations;
  8102. function fixForLoopHead(node, lines) {
  8103. if (node.type !== "ForStatement") {
  8104. return;
  8105. }
  8106. function fix(child) {
  8107. var loc = child && child.loc;
  8108. var start = loc && loc.start;
  8109. var end = loc && copyPos(loc.end);
  8110. while (start && end && comparePos(start, end) < 0) {
  8111. lines.prevPos(end);
  8112. if (lines.charAt(end) === ";") {
  8113. // Update child.loc.end to *exclude* the ';' character.
  8114. loc.end.line = end.line;
  8115. loc.end.column = end.column;
  8116. }
  8117. else {
  8118. break;
  8119. }
  8120. }
  8121. }
  8122. fix(node.init);
  8123. fix(node.test);
  8124. fix(node.update);
  8125. }
  8126. function fixTemplateLiteral(node, lines) {
  8127. if (node.type !== "TemplateLiteral") {
  8128. return;
  8129. }
  8130. if (node.quasis.length === 0) {
  8131. // If there are no quasi elements, then there is nothing to fix.
  8132. return;
  8133. }
  8134. // node.loc is not present when using export default with a template literal
  8135. if (node.loc) {
  8136. // First we need to exclude the opening ` from the .loc of the first
  8137. // quasi element, in case the parser accidentally decided to include it.
  8138. var afterLeftBackTickPos = copyPos(node.loc.start);
  8139. assert_1.default.strictEqual(lines.charAt(afterLeftBackTickPos), "`");
  8140. assert_1.default.ok(lines.nextPos(afterLeftBackTickPos));
  8141. var firstQuasi = node.quasis[0];
  8142. if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) {
  8143. firstQuasi.loc.start = afterLeftBackTickPos;
  8144. }
  8145. // Next we need to exclude the closing ` from the .loc of the last quasi
  8146. // element, in case the parser accidentally decided to include it.
  8147. var rightBackTickPos = copyPos(node.loc.end);
  8148. assert_1.default.ok(lines.prevPos(rightBackTickPos));
  8149. assert_1.default.strictEqual(lines.charAt(rightBackTickPos), "`");
  8150. var lastQuasi = node.quasis[node.quasis.length - 1];
  8151. if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) {
  8152. lastQuasi.loc.end = rightBackTickPos;
  8153. }
  8154. }
  8155. // Now we need to exclude ${ and } characters from the .loc's of all
  8156. // quasi elements, since some parsers accidentally include them.
  8157. node.expressions.forEach(function (expr, i) {
  8158. // Rewind from expr.loc.start over any whitespace and the ${ that
  8159. // precedes the expression. The position of the $ should be the same
  8160. // as the .loc.end of the preceding quasi element, but some parsers
  8161. // accidentally include the ${ in the .loc of the quasi element.
  8162. var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false);
  8163. if (lines.prevPos(dollarCurlyPos) &&
  8164. lines.charAt(dollarCurlyPos) === "{" &&
  8165. lines.prevPos(dollarCurlyPos) &&
  8166. lines.charAt(dollarCurlyPos) === "$") {
  8167. var quasiBefore = node.quasis[i];
  8168. if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) {
  8169. quasiBefore.loc.end = dollarCurlyPos;
  8170. }
  8171. }
  8172. // Likewise, some parsers accidentally include the } that follows
  8173. // the expression in the .loc of the following quasi element.
  8174. var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false);
  8175. if (lines.charAt(rightCurlyPos) === "}") {
  8176. assert_1.default.ok(lines.nextPos(rightCurlyPos));
  8177. // Now rightCurlyPos is technically the position just after the }.
  8178. var quasiAfter = node.quasis[i + 1];
  8179. if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) {
  8180. quasiAfter.loc.start = rightCurlyPos;
  8181. }
  8182. }
  8183. });
  8184. }
  8185. function isExportDeclaration(node) {
  8186. if (node)
  8187. switch (node.type) {
  8188. case "ExportDeclaration":
  8189. case "ExportDefaultDeclaration":
  8190. case "ExportDefaultSpecifier":
  8191. case "DeclareExportDeclaration":
  8192. case "ExportNamedDeclaration":
  8193. case "ExportAllDeclaration":
  8194. return true;
  8195. }
  8196. return false;
  8197. }
  8198. exports.isExportDeclaration = isExportDeclaration;
  8199. function getParentExportDeclaration(path) {
  8200. var parentNode = path.getParentNode();
  8201. if (path.getName() === "declaration" &&
  8202. isExportDeclaration(parentNode)) {
  8203. return parentNode;
  8204. }
  8205. return null;
  8206. }
  8207. exports.getParentExportDeclaration = getParentExportDeclaration;
  8208. function isTrailingCommaEnabled(options, context) {
  8209. var trailingComma = options.trailingComma;
  8210. if (typeof trailingComma === "object") {
  8211. return !!trailingComma[context];
  8212. }
  8213. return !!trailingComma;
  8214. }
  8215. exports.isTrailingCommaEnabled = isTrailingCommaEnabled;
  8216. });
  8217. unwrapExports(util$1);
  8218. var util_1$1 = util$1.getOption;
  8219. var util_2$1 = util$1.getUnionOfKeys;
  8220. var util_3$1 = util$1.comparePos;
  8221. var util_4$1 = util$1.copyPos;
  8222. var util_5$1 = util$1.composeSourceMaps;
  8223. var util_6$1 = util$1.getTrueLoc;
  8224. var util_7$1 = util$1.fixFaultyLocations;
  8225. var util_8$1 = util$1.isExportDeclaration;
  8226. var util_9$1 = util$1.getParentExportDeclaration;
  8227. var util_10$1 = util$1.isTrailingCommaEnabled;
  8228. var esprima$1 = createCommonjsModule(function (module, exports) {
  8229. (function webpackUniversalModuleDefinition(root, factory) {
  8230. /* istanbul ignore next */
  8231. module.exports = factory();
  8232. })(this, function() {
  8233. return /******/ (function(modules) { // webpackBootstrap
  8234. /******/ // The module cache
  8235. /******/ var installedModules = {};
  8236. /******/ // The require function
  8237. /******/ function __webpack_require__(moduleId) {
  8238. /******/ // Check if module is in cache
  8239. /* istanbul ignore if */
  8240. /******/ if(installedModules[moduleId])
  8241. /******/ return installedModules[moduleId].exports;
  8242. /******/ // Create a new module (and put it into the cache)
  8243. /******/ var module = installedModules[moduleId] = {
  8244. /******/ exports: {},
  8245. /******/ id: moduleId,
  8246. /******/ loaded: false
  8247. /******/ };
  8248. /******/ // Execute the module function
  8249. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8250. /******/ // Flag the module as loaded
  8251. /******/ module.loaded = true;
  8252. /******/ // Return the exports of the module
  8253. /******/ return module.exports;
  8254. /******/ }
  8255. /******/ // expose the modules object (__webpack_modules__)
  8256. /******/ __webpack_require__.m = modules;
  8257. /******/ // expose the module cache
  8258. /******/ __webpack_require__.c = installedModules;
  8259. /******/ // __webpack_public_path__
  8260. /******/ __webpack_require__.p = "";
  8261. /******/ // Load entry module and return exports
  8262. /******/ return __webpack_require__(0);
  8263. /******/ })
  8264. /************************************************************************/
  8265. /******/ ([
  8266. /* 0 */
  8267. /***/ function(module, exports, __webpack_require__) {
  8268. /*
  8269. Copyright JS Foundation and other contributors, https://js.foundation/
  8270. Redistribution and use in source and binary forms, with or without
  8271. modification, are permitted provided that the following conditions are met:
  8272. * Redistributions of source code must retain the above copyright
  8273. notice, this list of conditions and the following disclaimer.
  8274. * Redistributions in binary form must reproduce the above copyright
  8275. notice, this list of conditions and the following disclaimer in the
  8276. documentation and/or other materials provided with the distribution.
  8277. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  8278. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8279. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  8280. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  8281. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  8282. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  8283. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  8284. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8285. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  8286. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8287. */
  8288. Object.defineProperty(exports, "__esModule", { value: true });
  8289. var comment_handler_1 = __webpack_require__(1);
  8290. var jsx_parser_1 = __webpack_require__(3);
  8291. var parser_1 = __webpack_require__(8);
  8292. var tokenizer_1 = __webpack_require__(15);
  8293. function parse(code, options, delegate) {
  8294. var commentHandler = null;
  8295. var proxyDelegate = function (node, metadata) {
  8296. if (delegate) {
  8297. delegate(node, metadata);
  8298. }
  8299. if (commentHandler) {
  8300. commentHandler.visit(node, metadata);
  8301. }
  8302. };
  8303. var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null;
  8304. var collectComment = false;
  8305. if (options) {
  8306. collectComment = (typeof options.comment === 'boolean' && options.comment);
  8307. var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment);
  8308. if (collectComment || attachComment) {
  8309. commentHandler = new comment_handler_1.CommentHandler();
  8310. commentHandler.attach = attachComment;
  8311. options.comment = true;
  8312. parserDelegate = proxyDelegate;
  8313. }
  8314. }
  8315. var isModule = false;
  8316. if (options && typeof options.sourceType === 'string') {
  8317. isModule = (options.sourceType === 'module');
  8318. }
  8319. var parser;
  8320. if (options && typeof options.jsx === 'boolean' && options.jsx) {
  8321. parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
  8322. }
  8323. else {
  8324. parser = new parser_1.Parser(code, options, parserDelegate);
  8325. }
  8326. var program = isModule ? parser.parseModule() : parser.parseScript();
  8327. var ast = program;
  8328. if (collectComment && commentHandler) {
  8329. ast.comments = commentHandler.comments;
  8330. }
  8331. if (parser.config.tokens) {
  8332. ast.tokens = parser.tokens;
  8333. }
  8334. if (parser.config.tolerant) {
  8335. ast.errors = parser.errorHandler.errors;
  8336. }
  8337. return ast;
  8338. }
  8339. exports.parse = parse;
  8340. function parseModule(code, options, delegate) {
  8341. var parsingOptions = options || {};
  8342. parsingOptions.sourceType = 'module';
  8343. return parse(code, parsingOptions, delegate);
  8344. }
  8345. exports.parseModule = parseModule;
  8346. function parseScript(code, options, delegate) {
  8347. var parsingOptions = options || {};
  8348. parsingOptions.sourceType = 'script';
  8349. return parse(code, parsingOptions, delegate);
  8350. }
  8351. exports.parseScript = parseScript;
  8352. function tokenize(code, options, delegate) {
  8353. var tokenizer = new tokenizer_1.Tokenizer(code, options);
  8354. var tokens;
  8355. tokens = [];
  8356. try {
  8357. while (true) {
  8358. var token = tokenizer.getNextToken();
  8359. if (!token) {
  8360. break;
  8361. }
  8362. if (delegate) {
  8363. token = delegate(token);
  8364. }
  8365. tokens.push(token);
  8366. }
  8367. }
  8368. catch (e) {
  8369. tokenizer.errorHandler.tolerate(e);
  8370. }
  8371. if (tokenizer.errorHandler.tolerant) {
  8372. tokens.errors = tokenizer.errors();
  8373. }
  8374. return tokens;
  8375. }
  8376. exports.tokenize = tokenize;
  8377. var syntax_1 = __webpack_require__(2);
  8378. exports.Syntax = syntax_1.Syntax;
  8379. // Sync with *.json manifests.
  8380. exports.version = '4.0.1';
  8381. /***/ },
  8382. /* 1 */
  8383. /***/ function(module, exports, __webpack_require__) {
  8384. Object.defineProperty(exports, "__esModule", { value: true });
  8385. var syntax_1 = __webpack_require__(2);
  8386. var CommentHandler = (function () {
  8387. function CommentHandler() {
  8388. this.attach = false;
  8389. this.comments = [];
  8390. this.stack = [];
  8391. this.leading = [];
  8392. this.trailing = [];
  8393. }
  8394. CommentHandler.prototype.insertInnerComments = function (node, metadata) {
  8395. // innnerComments for properties empty block
  8396. // `function a() {/** comments **\/}`
  8397. if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
  8398. var innerComments = [];
  8399. for (var i = this.leading.length - 1; i >= 0; --i) {
  8400. var entry = this.leading[i];
  8401. if (metadata.end.offset >= entry.start) {
  8402. innerComments.unshift(entry.comment);
  8403. this.leading.splice(i, 1);
  8404. this.trailing.splice(i, 1);
  8405. }
  8406. }
  8407. if (innerComments.length) {
  8408. node.innerComments = innerComments;
  8409. }
  8410. }
  8411. };
  8412. CommentHandler.prototype.findTrailingComments = function (metadata) {
  8413. var trailingComments = [];
  8414. if (this.trailing.length > 0) {
  8415. for (var i = this.trailing.length - 1; i >= 0; --i) {
  8416. var entry_1 = this.trailing[i];
  8417. if (entry_1.start >= metadata.end.offset) {
  8418. trailingComments.unshift(entry_1.comment);
  8419. }
  8420. }
  8421. this.trailing.length = 0;
  8422. return trailingComments;
  8423. }
  8424. var entry = this.stack[this.stack.length - 1];
  8425. if (entry && entry.node.trailingComments) {
  8426. var firstComment = entry.node.trailingComments[0];
  8427. if (firstComment && firstComment.range[0] >= metadata.end.offset) {
  8428. trailingComments = entry.node.trailingComments;
  8429. delete entry.node.trailingComments;
  8430. }
  8431. }
  8432. return trailingComments;
  8433. };
  8434. CommentHandler.prototype.findLeadingComments = function (metadata) {
  8435. var leadingComments = [];
  8436. var target;
  8437. while (this.stack.length > 0) {
  8438. var entry = this.stack[this.stack.length - 1];
  8439. if (entry && entry.start >= metadata.start.offset) {
  8440. target = entry.node;
  8441. this.stack.pop();
  8442. }
  8443. else {
  8444. break;
  8445. }
  8446. }
  8447. if (target) {
  8448. var count = target.leadingComments ? target.leadingComments.length : 0;
  8449. for (var i = count - 1; i >= 0; --i) {
  8450. var comment = target.leadingComments[i];
  8451. if (comment.range[1] <= metadata.start.offset) {
  8452. leadingComments.unshift(comment);
  8453. target.leadingComments.splice(i, 1);
  8454. }
  8455. }
  8456. if (target.leadingComments && target.leadingComments.length === 0) {
  8457. delete target.leadingComments;
  8458. }
  8459. return leadingComments;
  8460. }
  8461. for (var i = this.leading.length - 1; i >= 0; --i) {
  8462. var entry = this.leading[i];
  8463. if (entry.start <= metadata.start.offset) {
  8464. leadingComments.unshift(entry.comment);
  8465. this.leading.splice(i, 1);
  8466. }
  8467. }
  8468. return leadingComments;
  8469. };
  8470. CommentHandler.prototype.visitNode = function (node, metadata) {
  8471. if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
  8472. return;
  8473. }
  8474. this.insertInnerComments(node, metadata);
  8475. var trailingComments = this.findTrailingComments(metadata);
  8476. var leadingComments = this.findLeadingComments(metadata);
  8477. if (leadingComments.length > 0) {
  8478. node.leadingComments = leadingComments;
  8479. }
  8480. if (trailingComments.length > 0) {
  8481. node.trailingComments = trailingComments;
  8482. }
  8483. this.stack.push({
  8484. node: node,
  8485. start: metadata.start.offset
  8486. });
  8487. };
  8488. CommentHandler.prototype.visitComment = function (node, metadata) {
  8489. var type = (node.type[0] === 'L') ? 'Line' : 'Block';
  8490. var comment = {
  8491. type: type,
  8492. value: node.value
  8493. };
  8494. if (node.range) {
  8495. comment.range = node.range;
  8496. }
  8497. if (node.loc) {
  8498. comment.loc = node.loc;
  8499. }
  8500. this.comments.push(comment);
  8501. if (this.attach) {
  8502. var entry = {
  8503. comment: {
  8504. type: type,
  8505. value: node.value,
  8506. range: [metadata.start.offset, metadata.end.offset]
  8507. },
  8508. start: metadata.start.offset
  8509. };
  8510. if (node.loc) {
  8511. entry.comment.loc = node.loc;
  8512. }
  8513. node.type = type;
  8514. this.leading.push(entry);
  8515. this.trailing.push(entry);
  8516. }
  8517. };
  8518. CommentHandler.prototype.visit = function (node, metadata) {
  8519. if (node.type === 'LineComment') {
  8520. this.visitComment(node, metadata);
  8521. }
  8522. else if (node.type === 'BlockComment') {
  8523. this.visitComment(node, metadata);
  8524. }
  8525. else if (this.attach) {
  8526. this.visitNode(node, metadata);
  8527. }
  8528. };
  8529. return CommentHandler;
  8530. }());
  8531. exports.CommentHandler = CommentHandler;
  8532. /***/ },
  8533. /* 2 */
  8534. /***/ function(module, exports) {
  8535. Object.defineProperty(exports, "__esModule", { value: true });
  8536. exports.Syntax = {
  8537. AssignmentExpression: 'AssignmentExpression',
  8538. AssignmentPattern: 'AssignmentPattern',
  8539. ArrayExpression: 'ArrayExpression',
  8540. ArrayPattern: 'ArrayPattern',
  8541. ArrowFunctionExpression: 'ArrowFunctionExpression',
  8542. AwaitExpression: 'AwaitExpression',
  8543. BlockStatement: 'BlockStatement',
  8544. BinaryExpression: 'BinaryExpression',
  8545. BreakStatement: 'BreakStatement',
  8546. CallExpression: 'CallExpression',
  8547. CatchClause: 'CatchClause',
  8548. ClassBody: 'ClassBody',
  8549. ClassDeclaration: 'ClassDeclaration',
  8550. ClassExpression: 'ClassExpression',
  8551. ConditionalExpression: 'ConditionalExpression',
  8552. ContinueStatement: 'ContinueStatement',
  8553. DoWhileStatement: 'DoWhileStatement',
  8554. DebuggerStatement: 'DebuggerStatement',
  8555. EmptyStatement: 'EmptyStatement',
  8556. ExportAllDeclaration: 'ExportAllDeclaration',
  8557. ExportDefaultDeclaration: 'ExportDefaultDeclaration',
  8558. ExportNamedDeclaration: 'ExportNamedDeclaration',
  8559. ExportSpecifier: 'ExportSpecifier',
  8560. ExpressionStatement: 'ExpressionStatement',
  8561. ForStatement: 'ForStatement',
  8562. ForOfStatement: 'ForOfStatement',
  8563. ForInStatement: 'ForInStatement',
  8564. FunctionDeclaration: 'FunctionDeclaration',
  8565. FunctionExpression: 'FunctionExpression',
  8566. Identifier: 'Identifier',
  8567. IfStatement: 'IfStatement',
  8568. ImportDeclaration: 'ImportDeclaration',
  8569. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  8570. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  8571. ImportSpecifier: 'ImportSpecifier',
  8572. Literal: 'Literal',
  8573. LabeledStatement: 'LabeledStatement',
  8574. LogicalExpression: 'LogicalExpression',
  8575. MemberExpression: 'MemberExpression',
  8576. MetaProperty: 'MetaProperty',
  8577. MethodDefinition: 'MethodDefinition',
  8578. NewExpression: 'NewExpression',
  8579. ObjectExpression: 'ObjectExpression',
  8580. ObjectPattern: 'ObjectPattern',
  8581. Program: 'Program',
  8582. Property: 'Property',
  8583. RestElement: 'RestElement',
  8584. ReturnStatement: 'ReturnStatement',
  8585. SequenceExpression: 'SequenceExpression',
  8586. SpreadElement: 'SpreadElement',
  8587. Super: 'Super',
  8588. SwitchCase: 'SwitchCase',
  8589. SwitchStatement: 'SwitchStatement',
  8590. TaggedTemplateExpression: 'TaggedTemplateExpression',
  8591. TemplateElement: 'TemplateElement',
  8592. TemplateLiteral: 'TemplateLiteral',
  8593. ThisExpression: 'ThisExpression',
  8594. ThrowStatement: 'ThrowStatement',
  8595. TryStatement: 'TryStatement',
  8596. UnaryExpression: 'UnaryExpression',
  8597. UpdateExpression: 'UpdateExpression',
  8598. VariableDeclaration: 'VariableDeclaration',
  8599. VariableDeclarator: 'VariableDeclarator',
  8600. WhileStatement: 'WhileStatement',
  8601. WithStatement: 'WithStatement',
  8602. YieldExpression: 'YieldExpression'
  8603. };
  8604. /***/ },
  8605. /* 3 */
  8606. /***/ function(module, exports, __webpack_require__) {
  8607. /* istanbul ignore next */
  8608. var __extends = (this && this.__extends) || (function () {
  8609. var extendStatics = Object.setPrototypeOf ||
  8610. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  8611. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  8612. return function (d, b) {
  8613. extendStatics(d, b);
  8614. function __() { this.constructor = d; }
  8615. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8616. };
  8617. })();
  8618. Object.defineProperty(exports, "__esModule", { value: true });
  8619. var character_1 = __webpack_require__(4);
  8620. var JSXNode = __webpack_require__(5);
  8621. var jsx_syntax_1 = __webpack_require__(6);
  8622. var Node = __webpack_require__(7);
  8623. var parser_1 = __webpack_require__(8);
  8624. var token_1 = __webpack_require__(13);
  8625. var xhtml_entities_1 = __webpack_require__(14);
  8626. token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier';
  8627. token_1.TokenName[101 /* Text */] = 'JSXText';
  8628. // Fully qualified element name, e.g. <svg:path> returns "svg:path"
  8629. function getQualifiedElementName(elementName) {
  8630. var qualifiedName;
  8631. switch (elementName.type) {
  8632. case jsx_syntax_1.JSXSyntax.JSXIdentifier:
  8633. var id = elementName;
  8634. qualifiedName = id.name;
  8635. break;
  8636. case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
  8637. var ns = elementName;
  8638. qualifiedName = getQualifiedElementName(ns.namespace) + ':' +
  8639. getQualifiedElementName(ns.name);
  8640. break;
  8641. case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
  8642. var expr = elementName;
  8643. qualifiedName = getQualifiedElementName(expr.object) + '.' +
  8644. getQualifiedElementName(expr.property);
  8645. break;
  8646. }
  8647. return qualifiedName;
  8648. }
  8649. var JSXParser = (function (_super) {
  8650. __extends(JSXParser, _super);
  8651. function JSXParser(code, options, delegate) {
  8652. return _super.call(this, code, options, delegate) || this;
  8653. }
  8654. JSXParser.prototype.parsePrimaryExpression = function () {
  8655. return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
  8656. };
  8657. JSXParser.prototype.startJSX = function () {
  8658. // Unwind the scanner before the lookahead token.
  8659. this.scanner.index = this.startMarker.index;
  8660. this.scanner.lineNumber = this.startMarker.line;
  8661. this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
  8662. };
  8663. JSXParser.prototype.finishJSX = function () {
  8664. // Prime the next lookahead.
  8665. this.nextToken();
  8666. };
  8667. JSXParser.prototype.reenterJSX = function () {
  8668. this.startJSX();
  8669. this.expectJSX('}');
  8670. // Pop the closing '}' added from the lookahead.
  8671. if (this.config.tokens) {
  8672. this.tokens.pop();
  8673. }
  8674. };
  8675. JSXParser.prototype.createJSXNode = function () {
  8676. this.collectComments();
  8677. return {
  8678. index: this.scanner.index,
  8679. line: this.scanner.lineNumber,
  8680. column: this.scanner.index - this.scanner.lineStart
  8681. };
  8682. };
  8683. JSXParser.prototype.createJSXChildNode = function () {
  8684. return {
  8685. index: this.scanner.index,
  8686. line: this.scanner.lineNumber,
  8687. column: this.scanner.index - this.scanner.lineStart
  8688. };
  8689. };
  8690. JSXParser.prototype.scanXHTMLEntity = function (quote) {
  8691. var result = '&';
  8692. var valid = true;
  8693. var terminated = false;
  8694. var numeric = false;
  8695. var hex = false;
  8696. while (!this.scanner.eof() && valid && !terminated) {
  8697. var ch = this.scanner.source[this.scanner.index];
  8698. if (ch === quote) {
  8699. break;
  8700. }
  8701. terminated = (ch === ';');
  8702. result += ch;
  8703. ++this.scanner.index;
  8704. if (!terminated) {
  8705. switch (result.length) {
  8706. case 2:
  8707. // e.g. '&#123;'
  8708. numeric = (ch === '#');
  8709. break;
  8710. case 3:
  8711. if (numeric) {
  8712. // e.g. '&#x41;'
  8713. hex = (ch === 'x');
  8714. valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
  8715. numeric = numeric && !hex;
  8716. }
  8717. break;
  8718. default:
  8719. valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
  8720. valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
  8721. break;
  8722. }
  8723. }
  8724. }
  8725. if (valid && terminated && result.length > 2) {
  8726. // e.g. '&#x41;' becomes just '#x41'
  8727. var str = result.substr(1, result.length - 2);
  8728. if (numeric && str.length > 1) {
  8729. result = String.fromCharCode(parseInt(str.substr(1), 10));
  8730. }
  8731. else if (hex && str.length > 2) {
  8732. result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
  8733. }
  8734. else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
  8735. result = xhtml_entities_1.XHTMLEntities[str];
  8736. }
  8737. }
  8738. return result;
  8739. };
  8740. // Scan the next JSX token. This replaces Scanner#lex when in JSX mode.
  8741. JSXParser.prototype.lexJSX = function () {
  8742. var cp = this.scanner.source.charCodeAt(this.scanner.index);
  8743. // < > / : = { }
  8744. if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
  8745. var value = this.scanner.source[this.scanner.index++];
  8746. return {
  8747. type: 7 /* Punctuator */,
  8748. value: value,
  8749. lineNumber: this.scanner.lineNumber,
  8750. lineStart: this.scanner.lineStart,
  8751. start: this.scanner.index - 1,
  8752. end: this.scanner.index
  8753. };
  8754. }
  8755. // " '
  8756. if (cp === 34 || cp === 39) {
  8757. var start = this.scanner.index;
  8758. var quote = this.scanner.source[this.scanner.index++];
  8759. var str = '';
  8760. while (!this.scanner.eof()) {
  8761. var ch = this.scanner.source[this.scanner.index++];
  8762. if (ch === quote) {
  8763. break;
  8764. }
  8765. else if (ch === '&') {
  8766. str += this.scanXHTMLEntity(quote);
  8767. }
  8768. else {
  8769. str += ch;
  8770. }
  8771. }
  8772. return {
  8773. type: 8 /* StringLiteral */,
  8774. value: str,
  8775. lineNumber: this.scanner.lineNumber,
  8776. lineStart: this.scanner.lineStart,
  8777. start: start,
  8778. end: this.scanner.index
  8779. };
  8780. }
  8781. // ... or .
  8782. if (cp === 46) {
  8783. var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
  8784. var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
  8785. var value = (n1 === 46 && n2 === 46) ? '...' : '.';
  8786. var start = this.scanner.index;
  8787. this.scanner.index += value.length;
  8788. return {
  8789. type: 7 /* Punctuator */,
  8790. value: value,
  8791. lineNumber: this.scanner.lineNumber,
  8792. lineStart: this.scanner.lineStart,
  8793. start: start,
  8794. end: this.scanner.index
  8795. };
  8796. }
  8797. // `
  8798. if (cp === 96) {
  8799. // Only placeholder, since it will be rescanned as a real assignment expression.
  8800. return {
  8801. type: 10 /* Template */,
  8802. value: '',
  8803. lineNumber: this.scanner.lineNumber,
  8804. lineStart: this.scanner.lineStart,
  8805. start: this.scanner.index,
  8806. end: this.scanner.index
  8807. };
  8808. }
  8809. // Identifer can not contain backslash (char code 92).
  8810. if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) {
  8811. var start = this.scanner.index;
  8812. ++this.scanner.index;
  8813. while (!this.scanner.eof()) {
  8814. var ch = this.scanner.source.charCodeAt(this.scanner.index);
  8815. if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) {
  8816. ++this.scanner.index;
  8817. }
  8818. else if (ch === 45) {
  8819. // Hyphen (char code 45) can be part of an identifier.
  8820. ++this.scanner.index;
  8821. }
  8822. else {
  8823. break;
  8824. }
  8825. }
  8826. var id = this.scanner.source.slice(start, this.scanner.index);
  8827. return {
  8828. type: 100 /* Identifier */,
  8829. value: id,
  8830. lineNumber: this.scanner.lineNumber,
  8831. lineStart: this.scanner.lineStart,
  8832. start: start,
  8833. end: this.scanner.index
  8834. };
  8835. }
  8836. return this.scanner.lex();
  8837. };
  8838. JSXParser.prototype.nextJSXToken = function () {
  8839. this.collectComments();
  8840. this.startMarker.index = this.scanner.index;
  8841. this.startMarker.line = this.scanner.lineNumber;
  8842. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  8843. var token = this.lexJSX();
  8844. this.lastMarker.index = this.scanner.index;
  8845. this.lastMarker.line = this.scanner.lineNumber;
  8846. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  8847. if (this.config.tokens) {
  8848. this.tokens.push(this.convertToken(token));
  8849. }
  8850. return token;
  8851. };
  8852. JSXParser.prototype.nextJSXText = function () {
  8853. this.startMarker.index = this.scanner.index;
  8854. this.startMarker.line = this.scanner.lineNumber;
  8855. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  8856. var start = this.scanner.index;
  8857. var text = '';
  8858. while (!this.scanner.eof()) {
  8859. var ch = this.scanner.source[this.scanner.index];
  8860. if (ch === '{' || ch === '<') {
  8861. break;
  8862. }
  8863. ++this.scanner.index;
  8864. text += ch;
  8865. if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  8866. ++this.scanner.lineNumber;
  8867. if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
  8868. ++this.scanner.index;
  8869. }
  8870. this.scanner.lineStart = this.scanner.index;
  8871. }
  8872. }
  8873. this.lastMarker.index = this.scanner.index;
  8874. this.lastMarker.line = this.scanner.lineNumber;
  8875. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  8876. var token = {
  8877. type: 101 /* Text */,
  8878. value: text,
  8879. lineNumber: this.scanner.lineNumber,
  8880. lineStart: this.scanner.lineStart,
  8881. start: start,
  8882. end: this.scanner.index
  8883. };
  8884. if ((text.length > 0) && this.config.tokens) {
  8885. this.tokens.push(this.convertToken(token));
  8886. }
  8887. return token;
  8888. };
  8889. JSXParser.prototype.peekJSXToken = function () {
  8890. var state = this.scanner.saveState();
  8891. this.scanner.scanComments();
  8892. var next = this.lexJSX();
  8893. this.scanner.restoreState(state);
  8894. return next;
  8895. };
  8896. // Expect the next JSX token to match the specified punctuator.
  8897. // If not, an exception will be thrown.
  8898. JSXParser.prototype.expectJSX = function (value) {
  8899. var token = this.nextJSXToken();
  8900. if (token.type !== 7 /* Punctuator */ || token.value !== value) {
  8901. this.throwUnexpectedToken(token);
  8902. }
  8903. };
  8904. // Return true if the next JSX token matches the specified punctuator.
  8905. JSXParser.prototype.matchJSX = function (value) {
  8906. var next = this.peekJSXToken();
  8907. return next.type === 7 /* Punctuator */ && next.value === value;
  8908. };
  8909. JSXParser.prototype.parseJSXIdentifier = function () {
  8910. var node = this.createJSXNode();
  8911. var token = this.nextJSXToken();
  8912. if (token.type !== 100 /* Identifier */) {
  8913. this.throwUnexpectedToken(token);
  8914. }
  8915. return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
  8916. };
  8917. JSXParser.prototype.parseJSXElementName = function () {
  8918. var node = this.createJSXNode();
  8919. var elementName = this.parseJSXIdentifier();
  8920. if (this.matchJSX(':')) {
  8921. var namespace = elementName;
  8922. this.expectJSX(':');
  8923. var name_1 = this.parseJSXIdentifier();
  8924. elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
  8925. }
  8926. else if (this.matchJSX('.')) {
  8927. while (this.matchJSX('.')) {
  8928. var object = elementName;
  8929. this.expectJSX('.');
  8930. var property = this.parseJSXIdentifier();
  8931. elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
  8932. }
  8933. }
  8934. return elementName;
  8935. };
  8936. JSXParser.prototype.parseJSXAttributeName = function () {
  8937. var node = this.createJSXNode();
  8938. var attributeName;
  8939. var identifier = this.parseJSXIdentifier();
  8940. if (this.matchJSX(':')) {
  8941. var namespace = identifier;
  8942. this.expectJSX(':');
  8943. var name_2 = this.parseJSXIdentifier();
  8944. attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
  8945. }
  8946. else {
  8947. attributeName = identifier;
  8948. }
  8949. return attributeName;
  8950. };
  8951. JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
  8952. var node = this.createJSXNode();
  8953. var token = this.nextJSXToken();
  8954. if (token.type !== 8 /* StringLiteral */) {
  8955. this.throwUnexpectedToken(token);
  8956. }
  8957. var raw = this.getTokenRaw(token);
  8958. return this.finalize(node, new Node.Literal(token.value, raw));
  8959. };
  8960. JSXParser.prototype.parseJSXExpressionAttribute = function () {
  8961. var node = this.createJSXNode();
  8962. this.expectJSX('{');
  8963. this.finishJSX();
  8964. if (this.match('}')) {
  8965. this.tolerateError('JSX attributes must only be assigned a non-empty expression');
  8966. }
  8967. var expression = this.parseAssignmentExpression();
  8968. this.reenterJSX();
  8969. return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
  8970. };
  8971. JSXParser.prototype.parseJSXAttributeValue = function () {
  8972. return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
  8973. this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
  8974. };
  8975. JSXParser.prototype.parseJSXNameValueAttribute = function () {
  8976. var node = this.createJSXNode();
  8977. var name = this.parseJSXAttributeName();
  8978. var value = null;
  8979. if (this.matchJSX('=')) {
  8980. this.expectJSX('=');
  8981. value = this.parseJSXAttributeValue();
  8982. }
  8983. return this.finalize(node, new JSXNode.JSXAttribute(name, value));
  8984. };
  8985. JSXParser.prototype.parseJSXSpreadAttribute = function () {
  8986. var node = this.createJSXNode();
  8987. this.expectJSX('{');
  8988. this.expectJSX('...');
  8989. this.finishJSX();
  8990. var argument = this.parseAssignmentExpression();
  8991. this.reenterJSX();
  8992. return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
  8993. };
  8994. JSXParser.prototype.parseJSXAttributes = function () {
  8995. var attributes = [];
  8996. while (!this.matchJSX('/') && !this.matchJSX('>')) {
  8997. var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() :
  8998. this.parseJSXNameValueAttribute();
  8999. attributes.push(attribute);
  9000. }
  9001. return attributes;
  9002. };
  9003. JSXParser.prototype.parseJSXOpeningElement = function () {
  9004. var node = this.createJSXNode();
  9005. this.expectJSX('<');
  9006. var name = this.parseJSXElementName();
  9007. var attributes = this.parseJSXAttributes();
  9008. var selfClosing = this.matchJSX('/');
  9009. if (selfClosing) {
  9010. this.expectJSX('/');
  9011. }
  9012. this.expectJSX('>');
  9013. return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
  9014. };
  9015. JSXParser.prototype.parseJSXBoundaryElement = function () {
  9016. var node = this.createJSXNode();
  9017. this.expectJSX('<');
  9018. if (this.matchJSX('/')) {
  9019. this.expectJSX('/');
  9020. var name_3 = this.parseJSXElementName();
  9021. this.expectJSX('>');
  9022. return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
  9023. }
  9024. var name = this.parseJSXElementName();
  9025. var attributes = this.parseJSXAttributes();
  9026. var selfClosing = this.matchJSX('/');
  9027. if (selfClosing) {
  9028. this.expectJSX('/');
  9029. }
  9030. this.expectJSX('>');
  9031. return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
  9032. };
  9033. JSXParser.prototype.parseJSXEmptyExpression = function () {
  9034. var node = this.createJSXChildNode();
  9035. this.collectComments();
  9036. this.lastMarker.index = this.scanner.index;
  9037. this.lastMarker.line = this.scanner.lineNumber;
  9038. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  9039. return this.finalize(node, new JSXNode.JSXEmptyExpression());
  9040. };
  9041. JSXParser.prototype.parseJSXExpressionContainer = function () {
  9042. var node = this.createJSXNode();
  9043. this.expectJSX('{');
  9044. var expression;
  9045. if (this.matchJSX('}')) {
  9046. expression = this.parseJSXEmptyExpression();
  9047. this.expectJSX('}');
  9048. }
  9049. else {
  9050. this.finishJSX();
  9051. expression = this.parseAssignmentExpression();
  9052. this.reenterJSX();
  9053. }
  9054. return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
  9055. };
  9056. JSXParser.prototype.parseJSXChildren = function () {
  9057. var children = [];
  9058. while (!this.scanner.eof()) {
  9059. var node = this.createJSXChildNode();
  9060. var token = this.nextJSXText();
  9061. if (token.start < token.end) {
  9062. var raw = this.getTokenRaw(token);
  9063. var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
  9064. children.push(child);
  9065. }
  9066. if (this.scanner.source[this.scanner.index] === '{') {
  9067. var container = this.parseJSXExpressionContainer();
  9068. children.push(container);
  9069. }
  9070. else {
  9071. break;
  9072. }
  9073. }
  9074. return children;
  9075. };
  9076. JSXParser.prototype.parseComplexJSXElement = function (el) {
  9077. var stack = [];
  9078. while (!this.scanner.eof()) {
  9079. el.children = el.children.concat(this.parseJSXChildren());
  9080. var node = this.createJSXChildNode();
  9081. var element = this.parseJSXBoundaryElement();
  9082. if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
  9083. var opening = element;
  9084. if (opening.selfClosing) {
  9085. var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
  9086. el.children.push(child);
  9087. }
  9088. else {
  9089. stack.push(el);
  9090. el = { node: node, opening: opening, closing: null, children: [] };
  9091. }
  9092. }
  9093. if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
  9094. el.closing = element;
  9095. var open_1 = getQualifiedElementName(el.opening.name);
  9096. var close_1 = getQualifiedElementName(el.closing.name);
  9097. if (open_1 !== close_1) {
  9098. this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
  9099. }
  9100. if (stack.length > 0) {
  9101. var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
  9102. el = stack[stack.length - 1];
  9103. el.children.push(child);
  9104. stack.pop();
  9105. }
  9106. else {
  9107. break;
  9108. }
  9109. }
  9110. }
  9111. return el;
  9112. };
  9113. JSXParser.prototype.parseJSXElement = function () {
  9114. var node = this.createJSXNode();
  9115. var opening = this.parseJSXOpeningElement();
  9116. var children = [];
  9117. var closing = null;
  9118. if (!opening.selfClosing) {
  9119. var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children });
  9120. children = el.children;
  9121. closing = el.closing;
  9122. }
  9123. return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
  9124. };
  9125. JSXParser.prototype.parseJSXRoot = function () {
  9126. // Pop the opening '<' added from the lookahead.
  9127. if (this.config.tokens) {
  9128. this.tokens.pop();
  9129. }
  9130. this.startJSX();
  9131. var element = this.parseJSXElement();
  9132. this.finishJSX();
  9133. return element;
  9134. };
  9135. JSXParser.prototype.isStartOfExpression = function () {
  9136. return _super.prototype.isStartOfExpression.call(this) || this.match('<');
  9137. };
  9138. return JSXParser;
  9139. }(parser_1.Parser));
  9140. exports.JSXParser = JSXParser;
  9141. /***/ },
  9142. /* 4 */
  9143. /***/ function(module, exports) {
  9144. Object.defineProperty(exports, "__esModule", { value: true });
  9145. // See also tools/generate-unicode-regex.js.
  9146. var Regex = {
  9147. // Unicode v8.0.0 NonAsciiIdentifierStart:
  9148. NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\
  9149. // Unicode v8.0.0 NonAsciiIdentifierPart:
  9150. NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\
  9151. };
  9152. exports.Character = {
  9153. /* tslint:disable:no-bitwise */
  9154. fromCodePoint: function (cp) {
  9155. return (cp < 0x10000) ? String.fromCharCode(cp) :
  9156. String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
  9157. String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
  9158. },
  9159. // https://tc39.github.io/ecma262/#sec-white-space
  9160. isWhiteSpace: function (cp) {
  9161. return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) ||
  9162. (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0);
  9163. },
  9164. // https://tc39.github.io/ecma262/#sec-line-terminators
  9165. isLineTerminator: function (cp) {
  9166. return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
  9167. },
  9168. // https://tc39.github.io/ecma262/#sec-names-and-keywords
  9169. isIdentifierStart: function (cp) {
  9170. return (cp === 0x24) || (cp === 0x5F) ||
  9171. (cp >= 0x41 && cp <= 0x5A) ||
  9172. (cp >= 0x61 && cp <= 0x7A) ||
  9173. (cp === 0x5C) ||
  9174. ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
  9175. },
  9176. isIdentifierPart: function (cp) {
  9177. return (cp === 0x24) || (cp === 0x5F) ||
  9178. (cp >= 0x41 && cp <= 0x5A) ||
  9179. (cp >= 0x61 && cp <= 0x7A) ||
  9180. (cp >= 0x30 && cp <= 0x39) ||
  9181. (cp === 0x5C) ||
  9182. ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
  9183. },
  9184. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  9185. isDecimalDigit: function (cp) {
  9186. return (cp >= 0x30 && cp <= 0x39); // 0..9
  9187. },
  9188. isHexDigit: function (cp) {
  9189. return (cp >= 0x30 && cp <= 0x39) ||
  9190. (cp >= 0x41 && cp <= 0x46) ||
  9191. (cp >= 0x61 && cp <= 0x66); // a..f
  9192. },
  9193. isOctalDigit: function (cp) {
  9194. return (cp >= 0x30 && cp <= 0x37); // 0..7
  9195. }
  9196. };
  9197. /***/ },
  9198. /* 5 */
  9199. /***/ function(module, exports, __webpack_require__) {
  9200. Object.defineProperty(exports, "__esModule", { value: true });
  9201. var jsx_syntax_1 = __webpack_require__(6);
  9202. /* tslint:disable:max-classes-per-file */
  9203. var JSXClosingElement = (function () {
  9204. function JSXClosingElement(name) {
  9205. this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
  9206. this.name = name;
  9207. }
  9208. return JSXClosingElement;
  9209. }());
  9210. exports.JSXClosingElement = JSXClosingElement;
  9211. var JSXElement = (function () {
  9212. function JSXElement(openingElement, children, closingElement) {
  9213. this.type = jsx_syntax_1.JSXSyntax.JSXElement;
  9214. this.openingElement = openingElement;
  9215. this.children = children;
  9216. this.closingElement = closingElement;
  9217. }
  9218. return JSXElement;
  9219. }());
  9220. exports.JSXElement = JSXElement;
  9221. var JSXEmptyExpression = (function () {
  9222. function JSXEmptyExpression() {
  9223. this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
  9224. }
  9225. return JSXEmptyExpression;
  9226. }());
  9227. exports.JSXEmptyExpression = JSXEmptyExpression;
  9228. var JSXExpressionContainer = (function () {
  9229. function JSXExpressionContainer(expression) {
  9230. this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
  9231. this.expression = expression;
  9232. }
  9233. return JSXExpressionContainer;
  9234. }());
  9235. exports.JSXExpressionContainer = JSXExpressionContainer;
  9236. var JSXIdentifier = (function () {
  9237. function JSXIdentifier(name) {
  9238. this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
  9239. this.name = name;
  9240. }
  9241. return JSXIdentifier;
  9242. }());
  9243. exports.JSXIdentifier = JSXIdentifier;
  9244. var JSXMemberExpression = (function () {
  9245. function JSXMemberExpression(object, property) {
  9246. this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
  9247. this.object = object;
  9248. this.property = property;
  9249. }
  9250. return JSXMemberExpression;
  9251. }());
  9252. exports.JSXMemberExpression = JSXMemberExpression;
  9253. var JSXAttribute = (function () {
  9254. function JSXAttribute(name, value) {
  9255. this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
  9256. this.name = name;
  9257. this.value = value;
  9258. }
  9259. return JSXAttribute;
  9260. }());
  9261. exports.JSXAttribute = JSXAttribute;
  9262. var JSXNamespacedName = (function () {
  9263. function JSXNamespacedName(namespace, name) {
  9264. this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
  9265. this.namespace = namespace;
  9266. this.name = name;
  9267. }
  9268. return JSXNamespacedName;
  9269. }());
  9270. exports.JSXNamespacedName = JSXNamespacedName;
  9271. var JSXOpeningElement = (function () {
  9272. function JSXOpeningElement(name, selfClosing, attributes) {
  9273. this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
  9274. this.name = name;
  9275. this.selfClosing = selfClosing;
  9276. this.attributes = attributes;
  9277. }
  9278. return JSXOpeningElement;
  9279. }());
  9280. exports.JSXOpeningElement = JSXOpeningElement;
  9281. var JSXSpreadAttribute = (function () {
  9282. function JSXSpreadAttribute(argument) {
  9283. this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
  9284. this.argument = argument;
  9285. }
  9286. return JSXSpreadAttribute;
  9287. }());
  9288. exports.JSXSpreadAttribute = JSXSpreadAttribute;
  9289. var JSXText = (function () {
  9290. function JSXText(value, raw) {
  9291. this.type = jsx_syntax_1.JSXSyntax.JSXText;
  9292. this.value = value;
  9293. this.raw = raw;
  9294. }
  9295. return JSXText;
  9296. }());
  9297. exports.JSXText = JSXText;
  9298. /***/ },
  9299. /* 6 */
  9300. /***/ function(module, exports) {
  9301. Object.defineProperty(exports, "__esModule", { value: true });
  9302. exports.JSXSyntax = {
  9303. JSXAttribute: 'JSXAttribute',
  9304. JSXClosingElement: 'JSXClosingElement',
  9305. JSXElement: 'JSXElement',
  9306. JSXEmptyExpression: 'JSXEmptyExpression',
  9307. JSXExpressionContainer: 'JSXExpressionContainer',
  9308. JSXIdentifier: 'JSXIdentifier',
  9309. JSXMemberExpression: 'JSXMemberExpression',
  9310. JSXNamespacedName: 'JSXNamespacedName',
  9311. JSXOpeningElement: 'JSXOpeningElement',
  9312. JSXSpreadAttribute: 'JSXSpreadAttribute',
  9313. JSXText: 'JSXText'
  9314. };
  9315. /***/ },
  9316. /* 7 */
  9317. /***/ function(module, exports, __webpack_require__) {
  9318. Object.defineProperty(exports, "__esModule", { value: true });
  9319. var syntax_1 = __webpack_require__(2);
  9320. /* tslint:disable:max-classes-per-file */
  9321. var ArrayExpression = (function () {
  9322. function ArrayExpression(elements) {
  9323. this.type = syntax_1.Syntax.ArrayExpression;
  9324. this.elements = elements;
  9325. }
  9326. return ArrayExpression;
  9327. }());
  9328. exports.ArrayExpression = ArrayExpression;
  9329. var ArrayPattern = (function () {
  9330. function ArrayPattern(elements) {
  9331. this.type = syntax_1.Syntax.ArrayPattern;
  9332. this.elements = elements;
  9333. }
  9334. return ArrayPattern;
  9335. }());
  9336. exports.ArrayPattern = ArrayPattern;
  9337. var ArrowFunctionExpression = (function () {
  9338. function ArrowFunctionExpression(params, body, expression) {
  9339. this.type = syntax_1.Syntax.ArrowFunctionExpression;
  9340. this.id = null;
  9341. this.params = params;
  9342. this.body = body;
  9343. this.generator = false;
  9344. this.expression = expression;
  9345. this.async = false;
  9346. }
  9347. return ArrowFunctionExpression;
  9348. }());
  9349. exports.ArrowFunctionExpression = ArrowFunctionExpression;
  9350. var AssignmentExpression = (function () {
  9351. function AssignmentExpression(operator, left, right) {
  9352. this.type = syntax_1.Syntax.AssignmentExpression;
  9353. this.operator = operator;
  9354. this.left = left;
  9355. this.right = right;
  9356. }
  9357. return AssignmentExpression;
  9358. }());
  9359. exports.AssignmentExpression = AssignmentExpression;
  9360. var AssignmentPattern = (function () {
  9361. function AssignmentPattern(left, right) {
  9362. this.type = syntax_1.Syntax.AssignmentPattern;
  9363. this.left = left;
  9364. this.right = right;
  9365. }
  9366. return AssignmentPattern;
  9367. }());
  9368. exports.AssignmentPattern = AssignmentPattern;
  9369. var AsyncArrowFunctionExpression = (function () {
  9370. function AsyncArrowFunctionExpression(params, body, expression) {
  9371. this.type = syntax_1.Syntax.ArrowFunctionExpression;
  9372. this.id = null;
  9373. this.params = params;
  9374. this.body = body;
  9375. this.generator = false;
  9376. this.expression = expression;
  9377. this.async = true;
  9378. }
  9379. return AsyncArrowFunctionExpression;
  9380. }());
  9381. exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
  9382. var AsyncFunctionDeclaration = (function () {
  9383. function AsyncFunctionDeclaration(id, params, body) {
  9384. this.type = syntax_1.Syntax.FunctionDeclaration;
  9385. this.id = id;
  9386. this.params = params;
  9387. this.body = body;
  9388. this.generator = false;
  9389. this.expression = false;
  9390. this.async = true;
  9391. }
  9392. return AsyncFunctionDeclaration;
  9393. }());
  9394. exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
  9395. var AsyncFunctionExpression = (function () {
  9396. function AsyncFunctionExpression(id, params, body) {
  9397. this.type = syntax_1.Syntax.FunctionExpression;
  9398. this.id = id;
  9399. this.params = params;
  9400. this.body = body;
  9401. this.generator = false;
  9402. this.expression = false;
  9403. this.async = true;
  9404. }
  9405. return AsyncFunctionExpression;
  9406. }());
  9407. exports.AsyncFunctionExpression = AsyncFunctionExpression;
  9408. var AwaitExpression = (function () {
  9409. function AwaitExpression(argument) {
  9410. this.type = syntax_1.Syntax.AwaitExpression;
  9411. this.argument = argument;
  9412. }
  9413. return AwaitExpression;
  9414. }());
  9415. exports.AwaitExpression = AwaitExpression;
  9416. var BinaryExpression = (function () {
  9417. function BinaryExpression(operator, left, right) {
  9418. var logical = (operator === '||' || operator === '&&');
  9419. this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
  9420. this.operator = operator;
  9421. this.left = left;
  9422. this.right = right;
  9423. }
  9424. return BinaryExpression;
  9425. }());
  9426. exports.BinaryExpression = BinaryExpression;
  9427. var BlockStatement = (function () {
  9428. function BlockStatement(body) {
  9429. this.type = syntax_1.Syntax.BlockStatement;
  9430. this.body = body;
  9431. }
  9432. return BlockStatement;
  9433. }());
  9434. exports.BlockStatement = BlockStatement;
  9435. var BreakStatement = (function () {
  9436. function BreakStatement(label) {
  9437. this.type = syntax_1.Syntax.BreakStatement;
  9438. this.label = label;
  9439. }
  9440. return BreakStatement;
  9441. }());
  9442. exports.BreakStatement = BreakStatement;
  9443. var CallExpression = (function () {
  9444. function CallExpression(callee, args) {
  9445. this.type = syntax_1.Syntax.CallExpression;
  9446. this.callee = callee;
  9447. this.arguments = args;
  9448. }
  9449. return CallExpression;
  9450. }());
  9451. exports.CallExpression = CallExpression;
  9452. var CatchClause = (function () {
  9453. function CatchClause(param, body) {
  9454. this.type = syntax_1.Syntax.CatchClause;
  9455. this.param = param;
  9456. this.body = body;
  9457. }
  9458. return CatchClause;
  9459. }());
  9460. exports.CatchClause = CatchClause;
  9461. var ClassBody = (function () {
  9462. function ClassBody(body) {
  9463. this.type = syntax_1.Syntax.ClassBody;
  9464. this.body = body;
  9465. }
  9466. return ClassBody;
  9467. }());
  9468. exports.ClassBody = ClassBody;
  9469. var ClassDeclaration = (function () {
  9470. function ClassDeclaration(id, superClass, body) {
  9471. this.type = syntax_1.Syntax.ClassDeclaration;
  9472. this.id = id;
  9473. this.superClass = superClass;
  9474. this.body = body;
  9475. }
  9476. return ClassDeclaration;
  9477. }());
  9478. exports.ClassDeclaration = ClassDeclaration;
  9479. var ClassExpression = (function () {
  9480. function ClassExpression(id, superClass, body) {
  9481. this.type = syntax_1.Syntax.ClassExpression;
  9482. this.id = id;
  9483. this.superClass = superClass;
  9484. this.body = body;
  9485. }
  9486. return ClassExpression;
  9487. }());
  9488. exports.ClassExpression = ClassExpression;
  9489. var ComputedMemberExpression = (function () {
  9490. function ComputedMemberExpression(object, property) {
  9491. this.type = syntax_1.Syntax.MemberExpression;
  9492. this.computed = true;
  9493. this.object = object;
  9494. this.property = property;
  9495. }
  9496. return ComputedMemberExpression;
  9497. }());
  9498. exports.ComputedMemberExpression = ComputedMemberExpression;
  9499. var ConditionalExpression = (function () {
  9500. function ConditionalExpression(test, consequent, alternate) {
  9501. this.type = syntax_1.Syntax.ConditionalExpression;
  9502. this.test = test;
  9503. this.consequent = consequent;
  9504. this.alternate = alternate;
  9505. }
  9506. return ConditionalExpression;
  9507. }());
  9508. exports.ConditionalExpression = ConditionalExpression;
  9509. var ContinueStatement = (function () {
  9510. function ContinueStatement(label) {
  9511. this.type = syntax_1.Syntax.ContinueStatement;
  9512. this.label = label;
  9513. }
  9514. return ContinueStatement;
  9515. }());
  9516. exports.ContinueStatement = ContinueStatement;
  9517. var DebuggerStatement = (function () {
  9518. function DebuggerStatement() {
  9519. this.type = syntax_1.Syntax.DebuggerStatement;
  9520. }
  9521. return DebuggerStatement;
  9522. }());
  9523. exports.DebuggerStatement = DebuggerStatement;
  9524. var Directive = (function () {
  9525. function Directive(expression, directive) {
  9526. this.type = syntax_1.Syntax.ExpressionStatement;
  9527. this.expression = expression;
  9528. this.directive = directive;
  9529. }
  9530. return Directive;
  9531. }());
  9532. exports.Directive = Directive;
  9533. var DoWhileStatement = (function () {
  9534. function DoWhileStatement(body, test) {
  9535. this.type = syntax_1.Syntax.DoWhileStatement;
  9536. this.body = body;
  9537. this.test = test;
  9538. }
  9539. return DoWhileStatement;
  9540. }());
  9541. exports.DoWhileStatement = DoWhileStatement;
  9542. var EmptyStatement = (function () {
  9543. function EmptyStatement() {
  9544. this.type = syntax_1.Syntax.EmptyStatement;
  9545. }
  9546. return EmptyStatement;
  9547. }());
  9548. exports.EmptyStatement = EmptyStatement;
  9549. var ExportAllDeclaration = (function () {
  9550. function ExportAllDeclaration(source) {
  9551. this.type = syntax_1.Syntax.ExportAllDeclaration;
  9552. this.source = source;
  9553. }
  9554. return ExportAllDeclaration;
  9555. }());
  9556. exports.ExportAllDeclaration = ExportAllDeclaration;
  9557. var ExportDefaultDeclaration = (function () {
  9558. function ExportDefaultDeclaration(declaration) {
  9559. this.type = syntax_1.Syntax.ExportDefaultDeclaration;
  9560. this.declaration = declaration;
  9561. }
  9562. return ExportDefaultDeclaration;
  9563. }());
  9564. exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
  9565. var ExportNamedDeclaration = (function () {
  9566. function ExportNamedDeclaration(declaration, specifiers, source) {
  9567. this.type = syntax_1.Syntax.ExportNamedDeclaration;
  9568. this.declaration = declaration;
  9569. this.specifiers = specifiers;
  9570. this.source = source;
  9571. }
  9572. return ExportNamedDeclaration;
  9573. }());
  9574. exports.ExportNamedDeclaration = ExportNamedDeclaration;
  9575. var ExportSpecifier = (function () {
  9576. function ExportSpecifier(local, exported) {
  9577. this.type = syntax_1.Syntax.ExportSpecifier;
  9578. this.exported = exported;
  9579. this.local = local;
  9580. }
  9581. return ExportSpecifier;
  9582. }());
  9583. exports.ExportSpecifier = ExportSpecifier;
  9584. var ExpressionStatement = (function () {
  9585. function ExpressionStatement(expression) {
  9586. this.type = syntax_1.Syntax.ExpressionStatement;
  9587. this.expression = expression;
  9588. }
  9589. return ExpressionStatement;
  9590. }());
  9591. exports.ExpressionStatement = ExpressionStatement;
  9592. var ForInStatement = (function () {
  9593. function ForInStatement(left, right, body) {
  9594. this.type = syntax_1.Syntax.ForInStatement;
  9595. this.left = left;
  9596. this.right = right;
  9597. this.body = body;
  9598. this.each = false;
  9599. }
  9600. return ForInStatement;
  9601. }());
  9602. exports.ForInStatement = ForInStatement;
  9603. var ForOfStatement = (function () {
  9604. function ForOfStatement(left, right, body) {
  9605. this.type = syntax_1.Syntax.ForOfStatement;
  9606. this.left = left;
  9607. this.right = right;
  9608. this.body = body;
  9609. }
  9610. return ForOfStatement;
  9611. }());
  9612. exports.ForOfStatement = ForOfStatement;
  9613. var ForStatement = (function () {
  9614. function ForStatement(init, test, update, body) {
  9615. this.type = syntax_1.Syntax.ForStatement;
  9616. this.init = init;
  9617. this.test = test;
  9618. this.update = update;
  9619. this.body = body;
  9620. }
  9621. return ForStatement;
  9622. }());
  9623. exports.ForStatement = ForStatement;
  9624. var FunctionDeclaration = (function () {
  9625. function FunctionDeclaration(id, params, body, generator) {
  9626. this.type = syntax_1.Syntax.FunctionDeclaration;
  9627. this.id = id;
  9628. this.params = params;
  9629. this.body = body;
  9630. this.generator = generator;
  9631. this.expression = false;
  9632. this.async = false;
  9633. }
  9634. return FunctionDeclaration;
  9635. }());
  9636. exports.FunctionDeclaration = FunctionDeclaration;
  9637. var FunctionExpression = (function () {
  9638. function FunctionExpression(id, params, body, generator) {
  9639. this.type = syntax_1.Syntax.FunctionExpression;
  9640. this.id = id;
  9641. this.params = params;
  9642. this.body = body;
  9643. this.generator = generator;
  9644. this.expression = false;
  9645. this.async = false;
  9646. }
  9647. return FunctionExpression;
  9648. }());
  9649. exports.FunctionExpression = FunctionExpression;
  9650. var Identifier = (function () {
  9651. function Identifier(name) {
  9652. this.type = syntax_1.Syntax.Identifier;
  9653. this.name = name;
  9654. }
  9655. return Identifier;
  9656. }());
  9657. exports.Identifier = Identifier;
  9658. var IfStatement = (function () {
  9659. function IfStatement(test, consequent, alternate) {
  9660. this.type = syntax_1.Syntax.IfStatement;
  9661. this.test = test;
  9662. this.consequent = consequent;
  9663. this.alternate = alternate;
  9664. }
  9665. return IfStatement;
  9666. }());
  9667. exports.IfStatement = IfStatement;
  9668. var ImportDeclaration = (function () {
  9669. function ImportDeclaration(specifiers, source) {
  9670. this.type = syntax_1.Syntax.ImportDeclaration;
  9671. this.specifiers = specifiers;
  9672. this.source = source;
  9673. }
  9674. return ImportDeclaration;
  9675. }());
  9676. exports.ImportDeclaration = ImportDeclaration;
  9677. var ImportDefaultSpecifier = (function () {
  9678. function ImportDefaultSpecifier(local) {
  9679. this.type = syntax_1.Syntax.ImportDefaultSpecifier;
  9680. this.local = local;
  9681. }
  9682. return ImportDefaultSpecifier;
  9683. }());
  9684. exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
  9685. var ImportNamespaceSpecifier = (function () {
  9686. function ImportNamespaceSpecifier(local) {
  9687. this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
  9688. this.local = local;
  9689. }
  9690. return ImportNamespaceSpecifier;
  9691. }());
  9692. exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
  9693. var ImportSpecifier = (function () {
  9694. function ImportSpecifier(local, imported) {
  9695. this.type = syntax_1.Syntax.ImportSpecifier;
  9696. this.local = local;
  9697. this.imported = imported;
  9698. }
  9699. return ImportSpecifier;
  9700. }());
  9701. exports.ImportSpecifier = ImportSpecifier;
  9702. var LabeledStatement = (function () {
  9703. function LabeledStatement(label, body) {
  9704. this.type = syntax_1.Syntax.LabeledStatement;
  9705. this.label = label;
  9706. this.body = body;
  9707. }
  9708. return LabeledStatement;
  9709. }());
  9710. exports.LabeledStatement = LabeledStatement;
  9711. var Literal = (function () {
  9712. function Literal(value, raw) {
  9713. this.type = syntax_1.Syntax.Literal;
  9714. this.value = value;
  9715. this.raw = raw;
  9716. }
  9717. return Literal;
  9718. }());
  9719. exports.Literal = Literal;
  9720. var MetaProperty = (function () {
  9721. function MetaProperty(meta, property) {
  9722. this.type = syntax_1.Syntax.MetaProperty;
  9723. this.meta = meta;
  9724. this.property = property;
  9725. }
  9726. return MetaProperty;
  9727. }());
  9728. exports.MetaProperty = MetaProperty;
  9729. var MethodDefinition = (function () {
  9730. function MethodDefinition(key, computed, value, kind, isStatic) {
  9731. this.type = syntax_1.Syntax.MethodDefinition;
  9732. this.key = key;
  9733. this.computed = computed;
  9734. this.value = value;
  9735. this.kind = kind;
  9736. this.static = isStatic;
  9737. }
  9738. return MethodDefinition;
  9739. }());
  9740. exports.MethodDefinition = MethodDefinition;
  9741. var Module = (function () {
  9742. function Module(body) {
  9743. this.type = syntax_1.Syntax.Program;
  9744. this.body = body;
  9745. this.sourceType = 'module';
  9746. }
  9747. return Module;
  9748. }());
  9749. exports.Module = Module;
  9750. var NewExpression = (function () {
  9751. function NewExpression(callee, args) {
  9752. this.type = syntax_1.Syntax.NewExpression;
  9753. this.callee = callee;
  9754. this.arguments = args;
  9755. }
  9756. return NewExpression;
  9757. }());
  9758. exports.NewExpression = NewExpression;
  9759. var ObjectExpression = (function () {
  9760. function ObjectExpression(properties) {
  9761. this.type = syntax_1.Syntax.ObjectExpression;
  9762. this.properties = properties;
  9763. }
  9764. return ObjectExpression;
  9765. }());
  9766. exports.ObjectExpression = ObjectExpression;
  9767. var ObjectPattern = (function () {
  9768. function ObjectPattern(properties) {
  9769. this.type = syntax_1.Syntax.ObjectPattern;
  9770. this.properties = properties;
  9771. }
  9772. return ObjectPattern;
  9773. }());
  9774. exports.ObjectPattern = ObjectPattern;
  9775. var Property = (function () {
  9776. function Property(kind, key, computed, value, method, shorthand) {
  9777. this.type = syntax_1.Syntax.Property;
  9778. this.key = key;
  9779. this.computed = computed;
  9780. this.value = value;
  9781. this.kind = kind;
  9782. this.method = method;
  9783. this.shorthand = shorthand;
  9784. }
  9785. return Property;
  9786. }());
  9787. exports.Property = Property;
  9788. var RegexLiteral = (function () {
  9789. function RegexLiteral(value, raw, pattern, flags) {
  9790. this.type = syntax_1.Syntax.Literal;
  9791. this.value = value;
  9792. this.raw = raw;
  9793. this.regex = { pattern: pattern, flags: flags };
  9794. }
  9795. return RegexLiteral;
  9796. }());
  9797. exports.RegexLiteral = RegexLiteral;
  9798. var RestElement = (function () {
  9799. function RestElement(argument) {
  9800. this.type = syntax_1.Syntax.RestElement;
  9801. this.argument = argument;
  9802. }
  9803. return RestElement;
  9804. }());
  9805. exports.RestElement = RestElement;
  9806. var ReturnStatement = (function () {
  9807. function ReturnStatement(argument) {
  9808. this.type = syntax_1.Syntax.ReturnStatement;
  9809. this.argument = argument;
  9810. }
  9811. return ReturnStatement;
  9812. }());
  9813. exports.ReturnStatement = ReturnStatement;
  9814. var Script = (function () {
  9815. function Script(body) {
  9816. this.type = syntax_1.Syntax.Program;
  9817. this.body = body;
  9818. this.sourceType = 'script';
  9819. }
  9820. return Script;
  9821. }());
  9822. exports.Script = Script;
  9823. var SequenceExpression = (function () {
  9824. function SequenceExpression(expressions) {
  9825. this.type = syntax_1.Syntax.SequenceExpression;
  9826. this.expressions = expressions;
  9827. }
  9828. return SequenceExpression;
  9829. }());
  9830. exports.SequenceExpression = SequenceExpression;
  9831. var SpreadElement = (function () {
  9832. function SpreadElement(argument) {
  9833. this.type = syntax_1.Syntax.SpreadElement;
  9834. this.argument = argument;
  9835. }
  9836. return SpreadElement;
  9837. }());
  9838. exports.SpreadElement = SpreadElement;
  9839. var StaticMemberExpression = (function () {
  9840. function StaticMemberExpression(object, property) {
  9841. this.type = syntax_1.Syntax.MemberExpression;
  9842. this.computed = false;
  9843. this.object = object;
  9844. this.property = property;
  9845. }
  9846. return StaticMemberExpression;
  9847. }());
  9848. exports.StaticMemberExpression = StaticMemberExpression;
  9849. var Super = (function () {
  9850. function Super() {
  9851. this.type = syntax_1.Syntax.Super;
  9852. }
  9853. return Super;
  9854. }());
  9855. exports.Super = Super;
  9856. var SwitchCase = (function () {
  9857. function SwitchCase(test, consequent) {
  9858. this.type = syntax_1.Syntax.SwitchCase;
  9859. this.test = test;
  9860. this.consequent = consequent;
  9861. }
  9862. return SwitchCase;
  9863. }());
  9864. exports.SwitchCase = SwitchCase;
  9865. var SwitchStatement = (function () {
  9866. function SwitchStatement(discriminant, cases) {
  9867. this.type = syntax_1.Syntax.SwitchStatement;
  9868. this.discriminant = discriminant;
  9869. this.cases = cases;
  9870. }
  9871. return SwitchStatement;
  9872. }());
  9873. exports.SwitchStatement = SwitchStatement;
  9874. var TaggedTemplateExpression = (function () {
  9875. function TaggedTemplateExpression(tag, quasi) {
  9876. this.type = syntax_1.Syntax.TaggedTemplateExpression;
  9877. this.tag = tag;
  9878. this.quasi = quasi;
  9879. }
  9880. return TaggedTemplateExpression;
  9881. }());
  9882. exports.TaggedTemplateExpression = TaggedTemplateExpression;
  9883. var TemplateElement = (function () {
  9884. function TemplateElement(value, tail) {
  9885. this.type = syntax_1.Syntax.TemplateElement;
  9886. this.value = value;
  9887. this.tail = tail;
  9888. }
  9889. return TemplateElement;
  9890. }());
  9891. exports.TemplateElement = TemplateElement;
  9892. var TemplateLiteral = (function () {
  9893. function TemplateLiteral(quasis, expressions) {
  9894. this.type = syntax_1.Syntax.TemplateLiteral;
  9895. this.quasis = quasis;
  9896. this.expressions = expressions;
  9897. }
  9898. return TemplateLiteral;
  9899. }());
  9900. exports.TemplateLiteral = TemplateLiteral;
  9901. var ThisExpression = (function () {
  9902. function ThisExpression() {
  9903. this.type = syntax_1.Syntax.ThisExpression;
  9904. }
  9905. return ThisExpression;
  9906. }());
  9907. exports.ThisExpression = ThisExpression;
  9908. var ThrowStatement = (function () {
  9909. function ThrowStatement(argument) {
  9910. this.type = syntax_1.Syntax.ThrowStatement;
  9911. this.argument = argument;
  9912. }
  9913. return ThrowStatement;
  9914. }());
  9915. exports.ThrowStatement = ThrowStatement;
  9916. var TryStatement = (function () {
  9917. function TryStatement(block, handler, finalizer) {
  9918. this.type = syntax_1.Syntax.TryStatement;
  9919. this.block = block;
  9920. this.handler = handler;
  9921. this.finalizer = finalizer;
  9922. }
  9923. return TryStatement;
  9924. }());
  9925. exports.TryStatement = TryStatement;
  9926. var UnaryExpression = (function () {
  9927. function UnaryExpression(operator, argument) {
  9928. this.type = syntax_1.Syntax.UnaryExpression;
  9929. this.operator = operator;
  9930. this.argument = argument;
  9931. this.prefix = true;
  9932. }
  9933. return UnaryExpression;
  9934. }());
  9935. exports.UnaryExpression = UnaryExpression;
  9936. var UpdateExpression = (function () {
  9937. function UpdateExpression(operator, argument, prefix) {
  9938. this.type = syntax_1.Syntax.UpdateExpression;
  9939. this.operator = operator;
  9940. this.argument = argument;
  9941. this.prefix = prefix;
  9942. }
  9943. return UpdateExpression;
  9944. }());
  9945. exports.UpdateExpression = UpdateExpression;
  9946. var VariableDeclaration = (function () {
  9947. function VariableDeclaration(declarations, kind) {
  9948. this.type = syntax_1.Syntax.VariableDeclaration;
  9949. this.declarations = declarations;
  9950. this.kind = kind;
  9951. }
  9952. return VariableDeclaration;
  9953. }());
  9954. exports.VariableDeclaration = VariableDeclaration;
  9955. var VariableDeclarator = (function () {
  9956. function VariableDeclarator(id, init) {
  9957. this.type = syntax_1.Syntax.VariableDeclarator;
  9958. this.id = id;
  9959. this.init = init;
  9960. }
  9961. return VariableDeclarator;
  9962. }());
  9963. exports.VariableDeclarator = VariableDeclarator;
  9964. var WhileStatement = (function () {
  9965. function WhileStatement(test, body) {
  9966. this.type = syntax_1.Syntax.WhileStatement;
  9967. this.test = test;
  9968. this.body = body;
  9969. }
  9970. return WhileStatement;
  9971. }());
  9972. exports.WhileStatement = WhileStatement;
  9973. var WithStatement = (function () {
  9974. function WithStatement(object, body) {
  9975. this.type = syntax_1.Syntax.WithStatement;
  9976. this.object = object;
  9977. this.body = body;
  9978. }
  9979. return WithStatement;
  9980. }());
  9981. exports.WithStatement = WithStatement;
  9982. var YieldExpression = (function () {
  9983. function YieldExpression(argument, delegate) {
  9984. this.type = syntax_1.Syntax.YieldExpression;
  9985. this.argument = argument;
  9986. this.delegate = delegate;
  9987. }
  9988. return YieldExpression;
  9989. }());
  9990. exports.YieldExpression = YieldExpression;
  9991. /***/ },
  9992. /* 8 */
  9993. /***/ function(module, exports, __webpack_require__) {
  9994. Object.defineProperty(exports, "__esModule", { value: true });
  9995. var assert_1 = __webpack_require__(9);
  9996. var error_handler_1 = __webpack_require__(10);
  9997. var messages_1 = __webpack_require__(11);
  9998. var Node = __webpack_require__(7);
  9999. var scanner_1 = __webpack_require__(12);
  10000. var syntax_1 = __webpack_require__(2);
  10001. var token_1 = __webpack_require__(13);
  10002. var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
  10003. var Parser = (function () {
  10004. function Parser(code, options, delegate) {
  10005. if (options === void 0) { options = {}; }
  10006. this.config = {
  10007. range: (typeof options.range === 'boolean') && options.range,
  10008. loc: (typeof options.loc === 'boolean') && options.loc,
  10009. source: null,
  10010. tokens: (typeof options.tokens === 'boolean') && options.tokens,
  10011. comment: (typeof options.comment === 'boolean') && options.comment,
  10012. tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
  10013. };
  10014. if (this.config.loc && options.source && options.source !== null) {
  10015. this.config.source = String(options.source);
  10016. }
  10017. this.delegate = delegate;
  10018. this.errorHandler = new error_handler_1.ErrorHandler();
  10019. this.errorHandler.tolerant = this.config.tolerant;
  10020. this.scanner = new scanner_1.Scanner(code, this.errorHandler);
  10021. this.scanner.trackComment = this.config.comment;
  10022. this.operatorPrecedence = {
  10023. ')': 0,
  10024. ';': 0,
  10025. ',': 0,
  10026. '=': 0,
  10027. ']': 0,
  10028. '||': 1,
  10029. '&&': 2,
  10030. '|': 3,
  10031. '^': 4,
  10032. '&': 5,
  10033. '==': 6,
  10034. '!=': 6,
  10035. '===': 6,
  10036. '!==': 6,
  10037. '<': 7,
  10038. '>': 7,
  10039. '<=': 7,
  10040. '>=': 7,
  10041. '<<': 8,
  10042. '>>': 8,
  10043. '>>>': 8,
  10044. '+': 9,
  10045. '-': 9,
  10046. '*': 11,
  10047. '/': 11,
  10048. '%': 11
  10049. };
  10050. this.lookahead = {
  10051. type: 2 /* EOF */,
  10052. value: '',
  10053. lineNumber: this.scanner.lineNumber,
  10054. lineStart: 0,
  10055. start: 0,
  10056. end: 0
  10057. };
  10058. this.hasLineTerminator = false;
  10059. this.context = {
  10060. isModule: false,
  10061. await: false,
  10062. allowIn: true,
  10063. allowStrictDirective: true,
  10064. allowYield: true,
  10065. firstCoverInitializedNameError: null,
  10066. isAssignmentTarget: false,
  10067. isBindingElement: false,
  10068. inFunctionBody: false,
  10069. inIteration: false,
  10070. inSwitch: false,
  10071. labelSet: {},
  10072. strict: false
  10073. };
  10074. this.tokens = [];
  10075. this.startMarker = {
  10076. index: 0,
  10077. line: this.scanner.lineNumber,
  10078. column: 0
  10079. };
  10080. this.lastMarker = {
  10081. index: 0,
  10082. line: this.scanner.lineNumber,
  10083. column: 0
  10084. };
  10085. this.nextToken();
  10086. this.lastMarker = {
  10087. index: this.scanner.index,
  10088. line: this.scanner.lineNumber,
  10089. column: this.scanner.index - this.scanner.lineStart
  10090. };
  10091. }
  10092. Parser.prototype.throwError = function (messageFormat) {
  10093. var values = [];
  10094. for (var _i = 1; _i < arguments.length; _i++) {
  10095. values[_i - 1] = arguments[_i];
  10096. }
  10097. var args = Array.prototype.slice.call(arguments, 1);
  10098. var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
  10099. assert_1.assert(idx < args.length, 'Message reference must be in range');
  10100. return args[idx];
  10101. });
  10102. var index = this.lastMarker.index;
  10103. var line = this.lastMarker.line;
  10104. var column = this.lastMarker.column + 1;
  10105. throw this.errorHandler.createError(index, line, column, msg);
  10106. };
  10107. Parser.prototype.tolerateError = function (messageFormat) {
  10108. var values = [];
  10109. for (var _i = 1; _i < arguments.length; _i++) {
  10110. values[_i - 1] = arguments[_i];
  10111. }
  10112. var args = Array.prototype.slice.call(arguments, 1);
  10113. var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
  10114. assert_1.assert(idx < args.length, 'Message reference must be in range');
  10115. return args[idx];
  10116. });
  10117. var index = this.lastMarker.index;
  10118. var line = this.scanner.lineNumber;
  10119. var column = this.lastMarker.column + 1;
  10120. this.errorHandler.tolerateError(index, line, column, msg);
  10121. };
  10122. // Throw an exception because of the token.
  10123. Parser.prototype.unexpectedTokenError = function (token, message) {
  10124. var msg = message || messages_1.Messages.UnexpectedToken;
  10125. var value;
  10126. if (token) {
  10127. if (!message) {
  10128. msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS :
  10129. (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier :
  10130. (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber :
  10131. (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString :
  10132. (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate :
  10133. messages_1.Messages.UnexpectedToken;
  10134. if (token.type === 4 /* Keyword */) {
  10135. if (this.scanner.isFutureReservedWord(token.value)) {
  10136. msg = messages_1.Messages.UnexpectedReserved;
  10137. }
  10138. else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
  10139. msg = messages_1.Messages.StrictReservedWord;
  10140. }
  10141. }
  10142. }
  10143. value = token.value;
  10144. }
  10145. else {
  10146. value = 'ILLEGAL';
  10147. }
  10148. msg = msg.replace('%0', value);
  10149. if (token && typeof token.lineNumber === 'number') {
  10150. var index = token.start;
  10151. var line = token.lineNumber;
  10152. var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
  10153. var column = token.start - lastMarkerLineStart + 1;
  10154. return this.errorHandler.createError(index, line, column, msg);
  10155. }
  10156. else {
  10157. var index = this.lastMarker.index;
  10158. var line = this.lastMarker.line;
  10159. var column = this.lastMarker.column + 1;
  10160. return this.errorHandler.createError(index, line, column, msg);
  10161. }
  10162. };
  10163. Parser.prototype.throwUnexpectedToken = function (token, message) {
  10164. throw this.unexpectedTokenError(token, message);
  10165. };
  10166. Parser.prototype.tolerateUnexpectedToken = function (token, message) {
  10167. this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
  10168. };
  10169. Parser.prototype.collectComments = function () {
  10170. if (!this.config.comment) {
  10171. this.scanner.scanComments();
  10172. }
  10173. else {
  10174. var comments = this.scanner.scanComments();
  10175. if (comments.length > 0 && this.delegate) {
  10176. for (var i = 0; i < comments.length; ++i) {
  10177. var e = comments[i];
  10178. var node = void 0;
  10179. node = {
  10180. type: e.multiLine ? 'BlockComment' : 'LineComment',
  10181. value: this.scanner.source.slice(e.slice[0], e.slice[1])
  10182. };
  10183. if (this.config.range) {
  10184. node.range = e.range;
  10185. }
  10186. if (this.config.loc) {
  10187. node.loc = e.loc;
  10188. }
  10189. var metadata = {
  10190. start: {
  10191. line: e.loc.start.line,
  10192. column: e.loc.start.column,
  10193. offset: e.range[0]
  10194. },
  10195. end: {
  10196. line: e.loc.end.line,
  10197. column: e.loc.end.column,
  10198. offset: e.range[1]
  10199. }
  10200. };
  10201. this.delegate(node, metadata);
  10202. }
  10203. }
  10204. }
  10205. };
  10206. // From internal representation to an external structure
  10207. Parser.prototype.getTokenRaw = function (token) {
  10208. return this.scanner.source.slice(token.start, token.end);
  10209. };
  10210. Parser.prototype.convertToken = function (token) {
  10211. var t = {
  10212. type: token_1.TokenName[token.type],
  10213. value: this.getTokenRaw(token)
  10214. };
  10215. if (this.config.range) {
  10216. t.range = [token.start, token.end];
  10217. }
  10218. if (this.config.loc) {
  10219. t.loc = {
  10220. start: {
  10221. line: this.startMarker.line,
  10222. column: this.startMarker.column
  10223. },
  10224. end: {
  10225. line: this.scanner.lineNumber,
  10226. column: this.scanner.index - this.scanner.lineStart
  10227. }
  10228. };
  10229. }
  10230. if (token.type === 9 /* RegularExpression */) {
  10231. var pattern = token.pattern;
  10232. var flags = token.flags;
  10233. t.regex = { pattern: pattern, flags: flags };
  10234. }
  10235. return t;
  10236. };
  10237. Parser.prototype.nextToken = function () {
  10238. var token = this.lookahead;
  10239. this.lastMarker.index = this.scanner.index;
  10240. this.lastMarker.line = this.scanner.lineNumber;
  10241. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  10242. this.collectComments();
  10243. if (this.scanner.index !== this.startMarker.index) {
  10244. this.startMarker.index = this.scanner.index;
  10245. this.startMarker.line = this.scanner.lineNumber;
  10246. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  10247. }
  10248. var next = this.scanner.lex();
  10249. this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
  10250. if (next && this.context.strict && next.type === 3 /* Identifier */) {
  10251. if (this.scanner.isStrictModeReservedWord(next.value)) {
  10252. next.type = 4 /* Keyword */;
  10253. }
  10254. }
  10255. this.lookahead = next;
  10256. if (this.config.tokens && next.type !== 2 /* EOF */) {
  10257. this.tokens.push(this.convertToken(next));
  10258. }
  10259. return token;
  10260. };
  10261. Parser.prototype.nextRegexToken = function () {
  10262. this.collectComments();
  10263. var token = this.scanner.scanRegExp();
  10264. if (this.config.tokens) {
  10265. // Pop the previous token, '/' or '/='
  10266. // This is added from the lookahead token.
  10267. this.tokens.pop();
  10268. this.tokens.push(this.convertToken(token));
  10269. }
  10270. // Prime the next lookahead.
  10271. this.lookahead = token;
  10272. this.nextToken();
  10273. return token;
  10274. };
  10275. Parser.prototype.createNode = function () {
  10276. return {
  10277. index: this.startMarker.index,
  10278. line: this.startMarker.line,
  10279. column: this.startMarker.column
  10280. };
  10281. };
  10282. Parser.prototype.startNode = function (token, lastLineStart) {
  10283. if (lastLineStart === void 0) { lastLineStart = 0; }
  10284. var column = token.start - token.lineStart;
  10285. var line = token.lineNumber;
  10286. if (column < 0) {
  10287. column += lastLineStart;
  10288. line--;
  10289. }
  10290. return {
  10291. index: token.start,
  10292. line: line,
  10293. column: column
  10294. };
  10295. };
  10296. Parser.prototype.finalize = function (marker, node) {
  10297. if (this.config.range) {
  10298. node.range = [marker.index, this.lastMarker.index];
  10299. }
  10300. if (this.config.loc) {
  10301. node.loc = {
  10302. start: {
  10303. line: marker.line,
  10304. column: marker.column,
  10305. },
  10306. end: {
  10307. line: this.lastMarker.line,
  10308. column: this.lastMarker.column
  10309. }
  10310. };
  10311. if (this.config.source) {
  10312. node.loc.source = this.config.source;
  10313. }
  10314. }
  10315. if (this.delegate) {
  10316. var metadata = {
  10317. start: {
  10318. line: marker.line,
  10319. column: marker.column,
  10320. offset: marker.index
  10321. },
  10322. end: {
  10323. line: this.lastMarker.line,
  10324. column: this.lastMarker.column,
  10325. offset: this.lastMarker.index
  10326. }
  10327. };
  10328. this.delegate(node, metadata);
  10329. }
  10330. return node;
  10331. };
  10332. // Expect the next token to match the specified punctuator.
  10333. // If not, an exception will be thrown.
  10334. Parser.prototype.expect = function (value) {
  10335. var token = this.nextToken();
  10336. if (token.type !== 7 /* Punctuator */ || token.value !== value) {
  10337. this.throwUnexpectedToken(token);
  10338. }
  10339. };
  10340. // Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
  10341. Parser.prototype.expectCommaSeparator = function () {
  10342. if (this.config.tolerant) {
  10343. var token = this.lookahead;
  10344. if (token.type === 7 /* Punctuator */ && token.value === ',') {
  10345. this.nextToken();
  10346. }
  10347. else if (token.type === 7 /* Punctuator */ && token.value === ';') {
  10348. this.nextToken();
  10349. this.tolerateUnexpectedToken(token);
  10350. }
  10351. else {
  10352. this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
  10353. }
  10354. }
  10355. else {
  10356. this.expect(',');
  10357. }
  10358. };
  10359. // Expect the next token to match the specified keyword.
  10360. // If not, an exception will be thrown.
  10361. Parser.prototype.expectKeyword = function (keyword) {
  10362. var token = this.nextToken();
  10363. if (token.type !== 4 /* Keyword */ || token.value !== keyword) {
  10364. this.throwUnexpectedToken(token);
  10365. }
  10366. };
  10367. // Return true if the next token matches the specified punctuator.
  10368. Parser.prototype.match = function (value) {
  10369. return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value;
  10370. };
  10371. // Return true if the next token matches the specified keyword
  10372. Parser.prototype.matchKeyword = function (keyword) {
  10373. return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword;
  10374. };
  10375. // Return true if the next token matches the specified contextual keyword
  10376. // (where an identifier is sometimes a keyword depending on the context)
  10377. Parser.prototype.matchContextualKeyword = function (keyword) {
  10378. return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword;
  10379. };
  10380. // Return true if the next token is an assignment operator
  10381. Parser.prototype.matchAssign = function () {
  10382. if (this.lookahead.type !== 7 /* Punctuator */) {
  10383. return false;
  10384. }
  10385. var op = this.lookahead.value;
  10386. return op === '=' ||
  10387. op === '*=' ||
  10388. op === '**=' ||
  10389. op === '/=' ||
  10390. op === '%=' ||
  10391. op === '+=' ||
  10392. op === '-=' ||
  10393. op === '<<=' ||
  10394. op === '>>=' ||
  10395. op === '>>>=' ||
  10396. op === '&=' ||
  10397. op === '^=' ||
  10398. op === '|=';
  10399. };
  10400. // Cover grammar support.
  10401. //
  10402. // When an assignment expression position starts with an left parenthesis, the determination of the type
  10403. // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
  10404. // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
  10405. //
  10406. // There are three productions that can be parsed in a parentheses pair that needs to be determined
  10407. // after the outermost pair is closed. They are:
  10408. //
  10409. // 1. AssignmentExpression
  10410. // 2. BindingElements
  10411. // 3. AssignmentTargets
  10412. //
  10413. // In order to avoid exponential backtracking, we use two flags to denote if the production can be
  10414. // binding element or assignment target.
  10415. //
  10416. // The three productions have the relationship:
  10417. //
  10418. // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
  10419. //
  10420. // with a single exception that CoverInitializedName when used directly in an Expression, generates
  10421. // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
  10422. // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
  10423. //
  10424. // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
  10425. // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
  10426. // the CoverInitializedName check is conducted.
  10427. //
  10428. // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
  10429. // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
  10430. // pattern. The CoverInitializedName check is deferred.
  10431. Parser.prototype.isolateCoverGrammar = function (parseFunction) {
  10432. var previousIsBindingElement = this.context.isBindingElement;
  10433. var previousIsAssignmentTarget = this.context.isAssignmentTarget;
  10434. var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
  10435. this.context.isBindingElement = true;
  10436. this.context.isAssignmentTarget = true;
  10437. this.context.firstCoverInitializedNameError = null;
  10438. var result = parseFunction.call(this);
  10439. if (this.context.firstCoverInitializedNameError !== null) {
  10440. this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
  10441. }
  10442. this.context.isBindingElement = previousIsBindingElement;
  10443. this.context.isAssignmentTarget = previousIsAssignmentTarget;
  10444. this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
  10445. return result;
  10446. };
  10447. Parser.prototype.inheritCoverGrammar = function (parseFunction) {
  10448. var previousIsBindingElement = this.context.isBindingElement;
  10449. var previousIsAssignmentTarget = this.context.isAssignmentTarget;
  10450. var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
  10451. this.context.isBindingElement = true;
  10452. this.context.isAssignmentTarget = true;
  10453. this.context.firstCoverInitializedNameError = null;
  10454. var result = parseFunction.call(this);
  10455. this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
  10456. this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
  10457. this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
  10458. return result;
  10459. };
  10460. Parser.prototype.consumeSemicolon = function () {
  10461. if (this.match(';')) {
  10462. this.nextToken();
  10463. }
  10464. else if (!this.hasLineTerminator) {
  10465. if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) {
  10466. this.throwUnexpectedToken(this.lookahead);
  10467. }
  10468. this.lastMarker.index = this.startMarker.index;
  10469. this.lastMarker.line = this.startMarker.line;
  10470. this.lastMarker.column = this.startMarker.column;
  10471. }
  10472. };
  10473. // https://tc39.github.io/ecma262/#sec-primary-expression
  10474. Parser.prototype.parsePrimaryExpression = function () {
  10475. var node = this.createNode();
  10476. var expr;
  10477. var token, raw;
  10478. switch (this.lookahead.type) {
  10479. case 3 /* Identifier */:
  10480. if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') {
  10481. this.tolerateUnexpectedToken(this.lookahead);
  10482. }
  10483. expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
  10484. break;
  10485. case 6 /* NumericLiteral */:
  10486. case 8 /* StringLiteral */:
  10487. if (this.context.strict && this.lookahead.octal) {
  10488. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
  10489. }
  10490. this.context.isAssignmentTarget = false;
  10491. this.context.isBindingElement = false;
  10492. token = this.nextToken();
  10493. raw = this.getTokenRaw(token);
  10494. expr = this.finalize(node, new Node.Literal(token.value, raw));
  10495. break;
  10496. case 1 /* BooleanLiteral */:
  10497. this.context.isAssignmentTarget = false;
  10498. this.context.isBindingElement = false;
  10499. token = this.nextToken();
  10500. raw = this.getTokenRaw(token);
  10501. expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
  10502. break;
  10503. case 5 /* NullLiteral */:
  10504. this.context.isAssignmentTarget = false;
  10505. this.context.isBindingElement = false;
  10506. token = this.nextToken();
  10507. raw = this.getTokenRaw(token);
  10508. expr = this.finalize(node, new Node.Literal(null, raw));
  10509. break;
  10510. case 10 /* Template */:
  10511. expr = this.parseTemplateLiteral();
  10512. break;
  10513. case 7 /* Punctuator */:
  10514. switch (this.lookahead.value) {
  10515. case '(':
  10516. this.context.isBindingElement = false;
  10517. expr = this.inheritCoverGrammar(this.parseGroupExpression);
  10518. break;
  10519. case '[':
  10520. expr = this.inheritCoverGrammar(this.parseArrayInitializer);
  10521. break;
  10522. case '{':
  10523. expr = this.inheritCoverGrammar(this.parseObjectInitializer);
  10524. break;
  10525. case '/':
  10526. case '/=':
  10527. this.context.isAssignmentTarget = false;
  10528. this.context.isBindingElement = false;
  10529. this.scanner.index = this.startMarker.index;
  10530. token = this.nextRegexToken();
  10531. raw = this.getTokenRaw(token);
  10532. expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
  10533. break;
  10534. default:
  10535. expr = this.throwUnexpectedToken(this.nextToken());
  10536. }
  10537. break;
  10538. case 4 /* Keyword */:
  10539. if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
  10540. expr = this.parseIdentifierName();
  10541. }
  10542. else if (!this.context.strict && this.matchKeyword('let')) {
  10543. expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
  10544. }
  10545. else {
  10546. this.context.isAssignmentTarget = false;
  10547. this.context.isBindingElement = false;
  10548. if (this.matchKeyword('function')) {
  10549. expr = this.parseFunctionExpression();
  10550. }
  10551. else if (this.matchKeyword('this')) {
  10552. this.nextToken();
  10553. expr = this.finalize(node, new Node.ThisExpression());
  10554. }
  10555. else if (this.matchKeyword('class')) {
  10556. expr = this.parseClassExpression();
  10557. }
  10558. else {
  10559. expr = this.throwUnexpectedToken(this.nextToken());
  10560. }
  10561. }
  10562. break;
  10563. default:
  10564. expr = this.throwUnexpectedToken(this.nextToken());
  10565. }
  10566. return expr;
  10567. };
  10568. // https://tc39.github.io/ecma262/#sec-array-initializer
  10569. Parser.prototype.parseSpreadElement = function () {
  10570. var node = this.createNode();
  10571. this.expect('...');
  10572. var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
  10573. return this.finalize(node, new Node.SpreadElement(arg));
  10574. };
  10575. Parser.prototype.parseArrayInitializer = function () {
  10576. var node = this.createNode();
  10577. var elements = [];
  10578. this.expect('[');
  10579. while (!this.match(']')) {
  10580. if (this.match(',')) {
  10581. this.nextToken();
  10582. elements.push(null);
  10583. }
  10584. else if (this.match('...')) {
  10585. var element = this.parseSpreadElement();
  10586. if (!this.match(']')) {
  10587. this.context.isAssignmentTarget = false;
  10588. this.context.isBindingElement = false;
  10589. this.expect(',');
  10590. }
  10591. elements.push(element);
  10592. }
  10593. else {
  10594. elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
  10595. if (!this.match(']')) {
  10596. this.expect(',');
  10597. }
  10598. }
  10599. }
  10600. this.expect(']');
  10601. return this.finalize(node, new Node.ArrayExpression(elements));
  10602. };
  10603. // https://tc39.github.io/ecma262/#sec-object-initializer
  10604. Parser.prototype.parsePropertyMethod = function (params) {
  10605. this.context.isAssignmentTarget = false;
  10606. this.context.isBindingElement = false;
  10607. var previousStrict = this.context.strict;
  10608. var previousAllowStrictDirective = this.context.allowStrictDirective;
  10609. this.context.allowStrictDirective = params.simple;
  10610. var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
  10611. if (this.context.strict && params.firstRestricted) {
  10612. this.tolerateUnexpectedToken(params.firstRestricted, params.message);
  10613. }
  10614. if (this.context.strict && params.stricted) {
  10615. this.tolerateUnexpectedToken(params.stricted, params.message);
  10616. }
  10617. this.context.strict = previousStrict;
  10618. this.context.allowStrictDirective = previousAllowStrictDirective;
  10619. return body;
  10620. };
  10621. Parser.prototype.parsePropertyMethodFunction = function () {
  10622. var isGenerator = false;
  10623. var node = this.createNode();
  10624. var previousAllowYield = this.context.allowYield;
  10625. this.context.allowYield = true;
  10626. var params = this.parseFormalParameters();
  10627. var method = this.parsePropertyMethod(params);
  10628. this.context.allowYield = previousAllowYield;
  10629. return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
  10630. };
  10631. Parser.prototype.parsePropertyMethodAsyncFunction = function () {
  10632. var node = this.createNode();
  10633. var previousAllowYield = this.context.allowYield;
  10634. var previousAwait = this.context.await;
  10635. this.context.allowYield = false;
  10636. this.context.await = true;
  10637. var params = this.parseFormalParameters();
  10638. var method = this.parsePropertyMethod(params);
  10639. this.context.allowYield = previousAllowYield;
  10640. this.context.await = previousAwait;
  10641. return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
  10642. };
  10643. Parser.prototype.parseObjectPropertyKey = function () {
  10644. var node = this.createNode();
  10645. var token = this.nextToken();
  10646. var key;
  10647. switch (token.type) {
  10648. case 8 /* StringLiteral */:
  10649. case 6 /* NumericLiteral */:
  10650. if (this.context.strict && token.octal) {
  10651. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
  10652. }
  10653. var raw = this.getTokenRaw(token);
  10654. key = this.finalize(node, new Node.Literal(token.value, raw));
  10655. break;
  10656. case 3 /* Identifier */:
  10657. case 1 /* BooleanLiteral */:
  10658. case 5 /* NullLiteral */:
  10659. case 4 /* Keyword */:
  10660. key = this.finalize(node, new Node.Identifier(token.value));
  10661. break;
  10662. case 7 /* Punctuator */:
  10663. if (token.value === '[') {
  10664. key = this.isolateCoverGrammar(this.parseAssignmentExpression);
  10665. this.expect(']');
  10666. }
  10667. else {
  10668. key = this.throwUnexpectedToken(token);
  10669. }
  10670. break;
  10671. default:
  10672. key = this.throwUnexpectedToken(token);
  10673. }
  10674. return key;
  10675. };
  10676. Parser.prototype.isPropertyKey = function (key, value) {
  10677. return (key.type === syntax_1.Syntax.Identifier && key.name === value) ||
  10678. (key.type === syntax_1.Syntax.Literal && key.value === value);
  10679. };
  10680. Parser.prototype.parseObjectProperty = function (hasProto) {
  10681. var node = this.createNode();
  10682. var token = this.lookahead;
  10683. var kind;
  10684. var key = null;
  10685. var value = null;
  10686. var computed = false;
  10687. var method = false;
  10688. var shorthand = false;
  10689. var isAsync = false;
  10690. if (token.type === 3 /* Identifier */) {
  10691. var id = token.value;
  10692. this.nextToken();
  10693. computed = this.match('[');
  10694. isAsync = !this.hasLineTerminator && (id === 'async') &&
  10695. !this.match(':') && !this.match('(') && !this.match('*') && !this.match(',');
  10696. key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
  10697. }
  10698. else if (this.match('*')) {
  10699. this.nextToken();
  10700. }
  10701. else {
  10702. computed = this.match('[');
  10703. key = this.parseObjectPropertyKey();
  10704. }
  10705. var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
  10706. if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
  10707. kind = 'get';
  10708. computed = this.match('[');
  10709. key = this.parseObjectPropertyKey();
  10710. this.context.allowYield = false;
  10711. value = this.parseGetterMethod();
  10712. }
  10713. else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
  10714. kind = 'set';
  10715. computed = this.match('[');
  10716. key = this.parseObjectPropertyKey();
  10717. value = this.parseSetterMethod();
  10718. }
  10719. else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
  10720. kind = 'init';
  10721. computed = this.match('[');
  10722. key = this.parseObjectPropertyKey();
  10723. value = this.parseGeneratorMethod();
  10724. method = true;
  10725. }
  10726. else {
  10727. if (!key) {
  10728. this.throwUnexpectedToken(this.lookahead);
  10729. }
  10730. kind = 'init';
  10731. if (this.match(':') && !isAsync) {
  10732. if (!computed && this.isPropertyKey(key, '__proto__')) {
  10733. if (hasProto.value) {
  10734. this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
  10735. }
  10736. hasProto.value = true;
  10737. }
  10738. this.nextToken();
  10739. value = this.inheritCoverGrammar(this.parseAssignmentExpression);
  10740. }
  10741. else if (this.match('(')) {
  10742. value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
  10743. method = true;
  10744. }
  10745. else if (token.type === 3 /* Identifier */) {
  10746. var id = this.finalize(node, new Node.Identifier(token.value));
  10747. if (this.match('=')) {
  10748. this.context.firstCoverInitializedNameError = this.lookahead;
  10749. this.nextToken();
  10750. shorthand = true;
  10751. var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  10752. value = this.finalize(node, new Node.AssignmentPattern(id, init));
  10753. }
  10754. else {
  10755. shorthand = true;
  10756. value = id;
  10757. }
  10758. }
  10759. else {
  10760. this.throwUnexpectedToken(this.nextToken());
  10761. }
  10762. }
  10763. return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
  10764. };
  10765. Parser.prototype.parseObjectInitializer = function () {
  10766. var node = this.createNode();
  10767. this.expect('{');
  10768. var properties = [];
  10769. var hasProto = { value: false };
  10770. while (!this.match('}')) {
  10771. properties.push(this.parseObjectProperty(hasProto));
  10772. if (!this.match('}')) {
  10773. this.expectCommaSeparator();
  10774. }
  10775. }
  10776. this.expect('}');
  10777. return this.finalize(node, new Node.ObjectExpression(properties));
  10778. };
  10779. // https://tc39.github.io/ecma262/#sec-template-literals
  10780. Parser.prototype.parseTemplateHead = function () {
  10781. assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
  10782. var node = this.createNode();
  10783. var token = this.nextToken();
  10784. var raw = token.value;
  10785. var cooked = token.cooked;
  10786. return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
  10787. };
  10788. Parser.prototype.parseTemplateElement = function () {
  10789. if (this.lookahead.type !== 10 /* Template */) {
  10790. this.throwUnexpectedToken();
  10791. }
  10792. var node = this.createNode();
  10793. var token = this.nextToken();
  10794. var raw = token.value;
  10795. var cooked = token.cooked;
  10796. return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
  10797. };
  10798. Parser.prototype.parseTemplateLiteral = function () {
  10799. var node = this.createNode();
  10800. var expressions = [];
  10801. var quasis = [];
  10802. var quasi = this.parseTemplateHead();
  10803. quasis.push(quasi);
  10804. while (!quasi.tail) {
  10805. expressions.push(this.parseExpression());
  10806. quasi = this.parseTemplateElement();
  10807. quasis.push(quasi);
  10808. }
  10809. return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
  10810. };
  10811. // https://tc39.github.io/ecma262/#sec-grouping-operator
  10812. Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
  10813. switch (expr.type) {
  10814. case syntax_1.Syntax.Identifier:
  10815. case syntax_1.Syntax.MemberExpression:
  10816. case syntax_1.Syntax.RestElement:
  10817. case syntax_1.Syntax.AssignmentPattern:
  10818. break;
  10819. case syntax_1.Syntax.SpreadElement:
  10820. expr.type = syntax_1.Syntax.RestElement;
  10821. this.reinterpretExpressionAsPattern(expr.argument);
  10822. break;
  10823. case syntax_1.Syntax.ArrayExpression:
  10824. expr.type = syntax_1.Syntax.ArrayPattern;
  10825. for (var i = 0; i < expr.elements.length; i++) {
  10826. if (expr.elements[i] !== null) {
  10827. this.reinterpretExpressionAsPattern(expr.elements[i]);
  10828. }
  10829. }
  10830. break;
  10831. case syntax_1.Syntax.ObjectExpression:
  10832. expr.type = syntax_1.Syntax.ObjectPattern;
  10833. for (var i = 0; i < expr.properties.length; i++) {
  10834. this.reinterpretExpressionAsPattern(expr.properties[i].value);
  10835. }
  10836. break;
  10837. case syntax_1.Syntax.AssignmentExpression:
  10838. expr.type = syntax_1.Syntax.AssignmentPattern;
  10839. delete expr.operator;
  10840. this.reinterpretExpressionAsPattern(expr.left);
  10841. break;
  10842. }
  10843. };
  10844. Parser.prototype.parseGroupExpression = function () {
  10845. var expr;
  10846. this.expect('(');
  10847. if (this.match(')')) {
  10848. this.nextToken();
  10849. if (!this.match('=>')) {
  10850. this.expect('=>');
  10851. }
  10852. expr = {
  10853. type: ArrowParameterPlaceHolder,
  10854. params: [],
  10855. async: false
  10856. };
  10857. }
  10858. else {
  10859. var startToken = this.lookahead;
  10860. var params = [];
  10861. if (this.match('...')) {
  10862. expr = this.parseRestElement(params);
  10863. this.expect(')');
  10864. if (!this.match('=>')) {
  10865. this.expect('=>');
  10866. }
  10867. expr = {
  10868. type: ArrowParameterPlaceHolder,
  10869. params: [expr],
  10870. async: false
  10871. };
  10872. }
  10873. else {
  10874. var arrow = false;
  10875. this.context.isBindingElement = true;
  10876. expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
  10877. if (this.match(',')) {
  10878. var expressions = [];
  10879. this.context.isAssignmentTarget = false;
  10880. expressions.push(expr);
  10881. while (this.lookahead.type !== 2 /* EOF */) {
  10882. if (!this.match(',')) {
  10883. break;
  10884. }
  10885. this.nextToken();
  10886. if (this.match(')')) {
  10887. this.nextToken();
  10888. for (var i = 0; i < expressions.length; i++) {
  10889. this.reinterpretExpressionAsPattern(expressions[i]);
  10890. }
  10891. arrow = true;
  10892. expr = {
  10893. type: ArrowParameterPlaceHolder,
  10894. params: expressions,
  10895. async: false
  10896. };
  10897. }
  10898. else if (this.match('...')) {
  10899. if (!this.context.isBindingElement) {
  10900. this.throwUnexpectedToken(this.lookahead);
  10901. }
  10902. expressions.push(this.parseRestElement(params));
  10903. this.expect(')');
  10904. if (!this.match('=>')) {
  10905. this.expect('=>');
  10906. }
  10907. this.context.isBindingElement = false;
  10908. for (var i = 0; i < expressions.length; i++) {
  10909. this.reinterpretExpressionAsPattern(expressions[i]);
  10910. }
  10911. arrow = true;
  10912. expr = {
  10913. type: ArrowParameterPlaceHolder,
  10914. params: expressions,
  10915. async: false
  10916. };
  10917. }
  10918. else {
  10919. expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
  10920. }
  10921. if (arrow) {
  10922. break;
  10923. }
  10924. }
  10925. if (!arrow) {
  10926. expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
  10927. }
  10928. }
  10929. if (!arrow) {
  10930. this.expect(')');
  10931. if (this.match('=>')) {
  10932. if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
  10933. arrow = true;
  10934. expr = {
  10935. type: ArrowParameterPlaceHolder,
  10936. params: [expr],
  10937. async: false
  10938. };
  10939. }
  10940. if (!arrow) {
  10941. if (!this.context.isBindingElement) {
  10942. this.throwUnexpectedToken(this.lookahead);
  10943. }
  10944. if (expr.type === syntax_1.Syntax.SequenceExpression) {
  10945. for (var i = 0; i < expr.expressions.length; i++) {
  10946. this.reinterpretExpressionAsPattern(expr.expressions[i]);
  10947. }
  10948. }
  10949. else {
  10950. this.reinterpretExpressionAsPattern(expr);
  10951. }
  10952. var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
  10953. expr = {
  10954. type: ArrowParameterPlaceHolder,
  10955. params: parameters,
  10956. async: false
  10957. };
  10958. }
  10959. }
  10960. this.context.isBindingElement = false;
  10961. }
  10962. }
  10963. }
  10964. return expr;
  10965. };
  10966. // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions
  10967. Parser.prototype.parseArguments = function () {
  10968. this.expect('(');
  10969. var args = [];
  10970. if (!this.match(')')) {
  10971. while (true) {
  10972. var expr = this.match('...') ? this.parseSpreadElement() :
  10973. this.isolateCoverGrammar(this.parseAssignmentExpression);
  10974. args.push(expr);
  10975. if (this.match(')')) {
  10976. break;
  10977. }
  10978. this.expectCommaSeparator();
  10979. if (this.match(')')) {
  10980. break;
  10981. }
  10982. }
  10983. }
  10984. this.expect(')');
  10985. return args;
  10986. };
  10987. Parser.prototype.isIdentifierName = function (token) {
  10988. return token.type === 3 /* Identifier */ ||
  10989. token.type === 4 /* Keyword */ ||
  10990. token.type === 1 /* BooleanLiteral */ ||
  10991. token.type === 5 /* NullLiteral */;
  10992. };
  10993. Parser.prototype.parseIdentifierName = function () {
  10994. var node = this.createNode();
  10995. var token = this.nextToken();
  10996. if (!this.isIdentifierName(token)) {
  10997. this.throwUnexpectedToken(token);
  10998. }
  10999. return this.finalize(node, new Node.Identifier(token.value));
  11000. };
  11001. Parser.prototype.parseNewExpression = function () {
  11002. var node = this.createNode();
  11003. var id = this.parseIdentifierName();
  11004. assert_1.assert(id.name === 'new', 'New expression must start with `new`');
  11005. var expr;
  11006. if (this.match('.')) {
  11007. this.nextToken();
  11008. if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') {
  11009. var property = this.parseIdentifierName();
  11010. expr = new Node.MetaProperty(id, property);
  11011. }
  11012. else {
  11013. this.throwUnexpectedToken(this.lookahead);
  11014. }
  11015. }
  11016. else {
  11017. var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
  11018. var args = this.match('(') ? this.parseArguments() : [];
  11019. expr = new Node.NewExpression(callee, args);
  11020. this.context.isAssignmentTarget = false;
  11021. this.context.isBindingElement = false;
  11022. }
  11023. return this.finalize(node, expr);
  11024. };
  11025. Parser.prototype.parseAsyncArgument = function () {
  11026. var arg = this.parseAssignmentExpression();
  11027. this.context.firstCoverInitializedNameError = null;
  11028. return arg;
  11029. };
  11030. Parser.prototype.parseAsyncArguments = function () {
  11031. this.expect('(');
  11032. var args = [];
  11033. if (!this.match(')')) {
  11034. while (true) {
  11035. var expr = this.match('...') ? this.parseSpreadElement() :
  11036. this.isolateCoverGrammar(this.parseAsyncArgument);
  11037. args.push(expr);
  11038. if (this.match(')')) {
  11039. break;
  11040. }
  11041. this.expectCommaSeparator();
  11042. if (this.match(')')) {
  11043. break;
  11044. }
  11045. }
  11046. }
  11047. this.expect(')');
  11048. return args;
  11049. };
  11050. Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
  11051. var startToken = this.lookahead;
  11052. var maybeAsync = this.matchContextualKeyword('async');
  11053. var previousAllowIn = this.context.allowIn;
  11054. this.context.allowIn = true;
  11055. var expr;
  11056. if (this.matchKeyword('super') && this.context.inFunctionBody) {
  11057. expr = this.createNode();
  11058. this.nextToken();
  11059. expr = this.finalize(expr, new Node.Super());
  11060. if (!this.match('(') && !this.match('.') && !this.match('[')) {
  11061. this.throwUnexpectedToken(this.lookahead);
  11062. }
  11063. }
  11064. else {
  11065. expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
  11066. }
  11067. while (true) {
  11068. if (this.match('.')) {
  11069. this.context.isBindingElement = false;
  11070. this.context.isAssignmentTarget = true;
  11071. this.expect('.');
  11072. var property = this.parseIdentifierName();
  11073. expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
  11074. }
  11075. else if (this.match('(')) {
  11076. var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber);
  11077. this.context.isBindingElement = false;
  11078. this.context.isAssignmentTarget = false;
  11079. var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
  11080. expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
  11081. if (asyncArrow && this.match('=>')) {
  11082. for (var i = 0; i < args.length; ++i) {
  11083. this.reinterpretExpressionAsPattern(args[i]);
  11084. }
  11085. expr = {
  11086. type: ArrowParameterPlaceHolder,
  11087. params: args,
  11088. async: true
  11089. };
  11090. }
  11091. }
  11092. else if (this.match('[')) {
  11093. this.context.isBindingElement = false;
  11094. this.context.isAssignmentTarget = true;
  11095. this.expect('[');
  11096. var property = this.isolateCoverGrammar(this.parseExpression);
  11097. this.expect(']');
  11098. expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
  11099. }
  11100. else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
  11101. var quasi = this.parseTemplateLiteral();
  11102. expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
  11103. }
  11104. else {
  11105. break;
  11106. }
  11107. }
  11108. this.context.allowIn = previousAllowIn;
  11109. return expr;
  11110. };
  11111. Parser.prototype.parseSuper = function () {
  11112. var node = this.createNode();
  11113. this.expectKeyword('super');
  11114. if (!this.match('[') && !this.match('.')) {
  11115. this.throwUnexpectedToken(this.lookahead);
  11116. }
  11117. return this.finalize(node, new Node.Super());
  11118. };
  11119. Parser.prototype.parseLeftHandSideExpression = function () {
  11120. assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
  11121. var node = this.startNode(this.lookahead);
  11122. var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() :
  11123. this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
  11124. while (true) {
  11125. if (this.match('[')) {
  11126. this.context.isBindingElement = false;
  11127. this.context.isAssignmentTarget = true;
  11128. this.expect('[');
  11129. var property = this.isolateCoverGrammar(this.parseExpression);
  11130. this.expect(']');
  11131. expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
  11132. }
  11133. else if (this.match('.')) {
  11134. this.context.isBindingElement = false;
  11135. this.context.isAssignmentTarget = true;
  11136. this.expect('.');
  11137. var property = this.parseIdentifierName();
  11138. expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
  11139. }
  11140. else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
  11141. var quasi = this.parseTemplateLiteral();
  11142. expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
  11143. }
  11144. else {
  11145. break;
  11146. }
  11147. }
  11148. return expr;
  11149. };
  11150. // https://tc39.github.io/ecma262/#sec-update-expressions
  11151. Parser.prototype.parseUpdateExpression = function () {
  11152. var expr;
  11153. var startToken = this.lookahead;
  11154. if (this.match('++') || this.match('--')) {
  11155. var node = this.startNode(startToken);
  11156. var token = this.nextToken();
  11157. expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  11158. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
  11159. this.tolerateError(messages_1.Messages.StrictLHSPrefix);
  11160. }
  11161. if (!this.context.isAssignmentTarget) {
  11162. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  11163. }
  11164. var prefix = true;
  11165. expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
  11166. this.context.isAssignmentTarget = false;
  11167. this.context.isBindingElement = false;
  11168. }
  11169. else {
  11170. expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  11171. if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) {
  11172. if (this.match('++') || this.match('--')) {
  11173. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
  11174. this.tolerateError(messages_1.Messages.StrictLHSPostfix);
  11175. }
  11176. if (!this.context.isAssignmentTarget) {
  11177. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  11178. }
  11179. this.context.isAssignmentTarget = false;
  11180. this.context.isBindingElement = false;
  11181. var operator = this.nextToken().value;
  11182. var prefix = false;
  11183. expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
  11184. }
  11185. }
  11186. }
  11187. return expr;
  11188. };
  11189. // https://tc39.github.io/ecma262/#sec-unary-operators
  11190. Parser.prototype.parseAwaitExpression = function () {
  11191. var node = this.createNode();
  11192. this.nextToken();
  11193. var argument = this.parseUnaryExpression();
  11194. return this.finalize(node, new Node.AwaitExpression(argument));
  11195. };
  11196. Parser.prototype.parseUnaryExpression = function () {
  11197. var expr;
  11198. if (this.match('+') || this.match('-') || this.match('~') || this.match('!') ||
  11199. this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
  11200. var node = this.startNode(this.lookahead);
  11201. var token = this.nextToken();
  11202. expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  11203. expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
  11204. if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
  11205. this.tolerateError(messages_1.Messages.StrictDelete);
  11206. }
  11207. this.context.isAssignmentTarget = false;
  11208. this.context.isBindingElement = false;
  11209. }
  11210. else if (this.context.await && this.matchContextualKeyword('await')) {
  11211. expr = this.parseAwaitExpression();
  11212. }
  11213. else {
  11214. expr = this.parseUpdateExpression();
  11215. }
  11216. return expr;
  11217. };
  11218. Parser.prototype.parseExponentiationExpression = function () {
  11219. var startToken = this.lookahead;
  11220. var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  11221. if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
  11222. this.nextToken();
  11223. this.context.isAssignmentTarget = false;
  11224. this.context.isBindingElement = false;
  11225. var left = expr;
  11226. var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
  11227. expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
  11228. }
  11229. return expr;
  11230. };
  11231. // https://tc39.github.io/ecma262/#sec-exp-operator
  11232. // https://tc39.github.io/ecma262/#sec-multiplicative-operators
  11233. // https://tc39.github.io/ecma262/#sec-additive-operators
  11234. // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
  11235. // https://tc39.github.io/ecma262/#sec-relational-operators
  11236. // https://tc39.github.io/ecma262/#sec-equality-operators
  11237. // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
  11238. // https://tc39.github.io/ecma262/#sec-binary-logical-operators
  11239. Parser.prototype.binaryPrecedence = function (token) {
  11240. var op = token.value;
  11241. var precedence;
  11242. if (token.type === 7 /* Punctuator */) {
  11243. precedence = this.operatorPrecedence[op] || 0;
  11244. }
  11245. else if (token.type === 4 /* Keyword */) {
  11246. precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0;
  11247. }
  11248. else {
  11249. precedence = 0;
  11250. }
  11251. return precedence;
  11252. };
  11253. Parser.prototype.parseBinaryExpression = function () {
  11254. var startToken = this.lookahead;
  11255. var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
  11256. var token = this.lookahead;
  11257. var prec = this.binaryPrecedence(token);
  11258. if (prec > 0) {
  11259. this.nextToken();
  11260. this.context.isAssignmentTarget = false;
  11261. this.context.isBindingElement = false;
  11262. var markers = [startToken, this.lookahead];
  11263. var left = expr;
  11264. var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
  11265. var stack = [left, token.value, right];
  11266. var precedences = [prec];
  11267. while (true) {
  11268. prec = this.binaryPrecedence(this.lookahead);
  11269. if (prec <= 0) {
  11270. break;
  11271. }
  11272. // Reduce: make a binary expression from the three topmost entries.
  11273. while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) {
  11274. right = stack.pop();
  11275. var operator = stack.pop();
  11276. precedences.pop();
  11277. left = stack.pop();
  11278. markers.pop();
  11279. var node = this.startNode(markers[markers.length - 1]);
  11280. stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
  11281. }
  11282. // Shift.
  11283. stack.push(this.nextToken().value);
  11284. precedences.push(prec);
  11285. markers.push(this.lookahead);
  11286. stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
  11287. }
  11288. // Final reduce to clean-up the stack.
  11289. var i = stack.length - 1;
  11290. expr = stack[i];
  11291. var lastMarker = markers.pop();
  11292. while (i > 1) {
  11293. var marker = markers.pop();
  11294. var lastLineStart = lastMarker && lastMarker.lineStart;
  11295. var node = this.startNode(marker, lastLineStart);
  11296. var operator = stack[i - 1];
  11297. expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
  11298. i -= 2;
  11299. lastMarker = marker;
  11300. }
  11301. }
  11302. return expr;
  11303. };
  11304. // https://tc39.github.io/ecma262/#sec-conditional-operator
  11305. Parser.prototype.parseConditionalExpression = function () {
  11306. var startToken = this.lookahead;
  11307. var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
  11308. if (this.match('?')) {
  11309. this.nextToken();
  11310. var previousAllowIn = this.context.allowIn;
  11311. this.context.allowIn = true;
  11312. var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11313. this.context.allowIn = previousAllowIn;
  11314. this.expect(':');
  11315. var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11316. expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
  11317. this.context.isAssignmentTarget = false;
  11318. this.context.isBindingElement = false;
  11319. }
  11320. return expr;
  11321. };
  11322. // https://tc39.github.io/ecma262/#sec-assignment-operators
  11323. Parser.prototype.checkPatternParam = function (options, param) {
  11324. switch (param.type) {
  11325. case syntax_1.Syntax.Identifier:
  11326. this.validateParam(options, param, param.name);
  11327. break;
  11328. case syntax_1.Syntax.RestElement:
  11329. this.checkPatternParam(options, param.argument);
  11330. break;
  11331. case syntax_1.Syntax.AssignmentPattern:
  11332. this.checkPatternParam(options, param.left);
  11333. break;
  11334. case syntax_1.Syntax.ArrayPattern:
  11335. for (var i = 0; i < param.elements.length; i++) {
  11336. if (param.elements[i] !== null) {
  11337. this.checkPatternParam(options, param.elements[i]);
  11338. }
  11339. }
  11340. break;
  11341. case syntax_1.Syntax.ObjectPattern:
  11342. for (var i = 0; i < param.properties.length; i++) {
  11343. this.checkPatternParam(options, param.properties[i].value);
  11344. }
  11345. break;
  11346. }
  11347. options.simple = options.simple && (param instanceof Node.Identifier);
  11348. };
  11349. Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
  11350. var params = [expr];
  11351. var options;
  11352. var asyncArrow = false;
  11353. switch (expr.type) {
  11354. case syntax_1.Syntax.Identifier:
  11355. break;
  11356. case ArrowParameterPlaceHolder:
  11357. params = expr.params;
  11358. asyncArrow = expr.async;
  11359. break;
  11360. default:
  11361. return null;
  11362. }
  11363. options = {
  11364. simple: true,
  11365. paramSet: {}
  11366. };
  11367. for (var i = 0; i < params.length; ++i) {
  11368. var param = params[i];
  11369. if (param.type === syntax_1.Syntax.AssignmentPattern) {
  11370. if (param.right.type === syntax_1.Syntax.YieldExpression) {
  11371. if (param.right.argument) {
  11372. this.throwUnexpectedToken(this.lookahead);
  11373. }
  11374. param.right.type = syntax_1.Syntax.Identifier;
  11375. param.right.name = 'yield';
  11376. delete param.right.argument;
  11377. delete param.right.delegate;
  11378. }
  11379. }
  11380. else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') {
  11381. this.throwUnexpectedToken(this.lookahead);
  11382. }
  11383. this.checkPatternParam(options, param);
  11384. params[i] = param;
  11385. }
  11386. if (this.context.strict || !this.context.allowYield) {
  11387. for (var i = 0; i < params.length; ++i) {
  11388. var param = params[i];
  11389. if (param.type === syntax_1.Syntax.YieldExpression) {
  11390. this.throwUnexpectedToken(this.lookahead);
  11391. }
  11392. }
  11393. }
  11394. if (options.message === messages_1.Messages.StrictParamDupe) {
  11395. var token = this.context.strict ? options.stricted : options.firstRestricted;
  11396. this.throwUnexpectedToken(token, options.message);
  11397. }
  11398. return {
  11399. simple: options.simple,
  11400. params: params,
  11401. stricted: options.stricted,
  11402. firstRestricted: options.firstRestricted,
  11403. message: options.message
  11404. };
  11405. };
  11406. Parser.prototype.parseAssignmentExpression = function () {
  11407. var expr;
  11408. if (!this.context.allowYield && this.matchKeyword('yield')) {
  11409. expr = this.parseYieldExpression();
  11410. }
  11411. else {
  11412. var startToken = this.lookahead;
  11413. var token = startToken;
  11414. expr = this.parseConditionalExpression();
  11415. if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') {
  11416. if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) {
  11417. var arg = this.parsePrimaryExpression();
  11418. this.reinterpretExpressionAsPattern(arg);
  11419. expr = {
  11420. type: ArrowParameterPlaceHolder,
  11421. params: [arg],
  11422. async: true
  11423. };
  11424. }
  11425. }
  11426. if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
  11427. // https://tc39.github.io/ecma262/#sec-arrow-function-definitions
  11428. this.context.isAssignmentTarget = false;
  11429. this.context.isBindingElement = false;
  11430. var isAsync = expr.async;
  11431. var list = this.reinterpretAsCoverFormalsList(expr);
  11432. if (list) {
  11433. if (this.hasLineTerminator) {
  11434. this.tolerateUnexpectedToken(this.lookahead);
  11435. }
  11436. this.context.firstCoverInitializedNameError = null;
  11437. var previousStrict = this.context.strict;
  11438. var previousAllowStrictDirective = this.context.allowStrictDirective;
  11439. this.context.allowStrictDirective = list.simple;
  11440. var previousAllowYield = this.context.allowYield;
  11441. var previousAwait = this.context.await;
  11442. this.context.allowYield = true;
  11443. this.context.await = isAsync;
  11444. var node = this.startNode(startToken);
  11445. this.expect('=>');
  11446. var body = void 0;
  11447. if (this.match('{')) {
  11448. var previousAllowIn = this.context.allowIn;
  11449. this.context.allowIn = true;
  11450. body = this.parseFunctionSourceElements();
  11451. this.context.allowIn = previousAllowIn;
  11452. }
  11453. else {
  11454. body = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11455. }
  11456. var expression = body.type !== syntax_1.Syntax.BlockStatement;
  11457. if (this.context.strict && list.firstRestricted) {
  11458. this.throwUnexpectedToken(list.firstRestricted, list.message);
  11459. }
  11460. if (this.context.strict && list.stricted) {
  11461. this.tolerateUnexpectedToken(list.stricted, list.message);
  11462. }
  11463. expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
  11464. this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
  11465. this.context.strict = previousStrict;
  11466. this.context.allowStrictDirective = previousAllowStrictDirective;
  11467. this.context.allowYield = previousAllowYield;
  11468. this.context.await = previousAwait;
  11469. }
  11470. }
  11471. else {
  11472. if (this.matchAssign()) {
  11473. if (!this.context.isAssignmentTarget) {
  11474. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  11475. }
  11476. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
  11477. var id = expr;
  11478. if (this.scanner.isRestrictedWord(id.name)) {
  11479. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
  11480. }
  11481. if (this.scanner.isStrictModeReservedWord(id.name)) {
  11482. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  11483. }
  11484. }
  11485. if (!this.match('=')) {
  11486. this.context.isAssignmentTarget = false;
  11487. this.context.isBindingElement = false;
  11488. }
  11489. else {
  11490. this.reinterpretExpressionAsPattern(expr);
  11491. }
  11492. token = this.nextToken();
  11493. var operator = token.value;
  11494. var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11495. expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
  11496. this.context.firstCoverInitializedNameError = null;
  11497. }
  11498. }
  11499. }
  11500. return expr;
  11501. };
  11502. // https://tc39.github.io/ecma262/#sec-comma-operator
  11503. Parser.prototype.parseExpression = function () {
  11504. var startToken = this.lookahead;
  11505. var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11506. if (this.match(',')) {
  11507. var expressions = [];
  11508. expressions.push(expr);
  11509. while (this.lookahead.type !== 2 /* EOF */) {
  11510. if (!this.match(',')) {
  11511. break;
  11512. }
  11513. this.nextToken();
  11514. expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
  11515. }
  11516. expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
  11517. }
  11518. return expr;
  11519. };
  11520. // https://tc39.github.io/ecma262/#sec-block
  11521. Parser.prototype.parseStatementListItem = function () {
  11522. var statement;
  11523. this.context.isAssignmentTarget = true;
  11524. this.context.isBindingElement = true;
  11525. if (this.lookahead.type === 4 /* Keyword */) {
  11526. switch (this.lookahead.value) {
  11527. case 'export':
  11528. if (!this.context.isModule) {
  11529. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
  11530. }
  11531. statement = this.parseExportDeclaration();
  11532. break;
  11533. case 'import':
  11534. if (!this.context.isModule) {
  11535. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
  11536. }
  11537. statement = this.parseImportDeclaration();
  11538. break;
  11539. case 'const':
  11540. statement = this.parseLexicalDeclaration({ inFor: false });
  11541. break;
  11542. case 'function':
  11543. statement = this.parseFunctionDeclaration();
  11544. break;
  11545. case 'class':
  11546. statement = this.parseClassDeclaration();
  11547. break;
  11548. case 'let':
  11549. statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
  11550. break;
  11551. default:
  11552. statement = this.parseStatement();
  11553. break;
  11554. }
  11555. }
  11556. else {
  11557. statement = this.parseStatement();
  11558. }
  11559. return statement;
  11560. };
  11561. Parser.prototype.parseBlock = function () {
  11562. var node = this.createNode();
  11563. this.expect('{');
  11564. var block = [];
  11565. while (true) {
  11566. if (this.match('}')) {
  11567. break;
  11568. }
  11569. block.push(this.parseStatementListItem());
  11570. }
  11571. this.expect('}');
  11572. return this.finalize(node, new Node.BlockStatement(block));
  11573. };
  11574. // https://tc39.github.io/ecma262/#sec-let-and-const-declarations
  11575. Parser.prototype.parseLexicalBinding = function (kind, options) {
  11576. var node = this.createNode();
  11577. var params = [];
  11578. var id = this.parsePattern(params, kind);
  11579. if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
  11580. if (this.scanner.isRestrictedWord(id.name)) {
  11581. this.tolerateError(messages_1.Messages.StrictVarName);
  11582. }
  11583. }
  11584. var init = null;
  11585. if (kind === 'const') {
  11586. if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
  11587. if (this.match('=')) {
  11588. this.nextToken();
  11589. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11590. }
  11591. else {
  11592. this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
  11593. }
  11594. }
  11595. }
  11596. else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) {
  11597. this.expect('=');
  11598. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11599. }
  11600. return this.finalize(node, new Node.VariableDeclarator(id, init));
  11601. };
  11602. Parser.prototype.parseBindingList = function (kind, options) {
  11603. var list = [this.parseLexicalBinding(kind, options)];
  11604. while (this.match(',')) {
  11605. this.nextToken();
  11606. list.push(this.parseLexicalBinding(kind, options));
  11607. }
  11608. return list;
  11609. };
  11610. Parser.prototype.isLexicalDeclaration = function () {
  11611. var state = this.scanner.saveState();
  11612. this.scanner.scanComments();
  11613. var next = this.scanner.lex();
  11614. this.scanner.restoreState(state);
  11615. return (next.type === 3 /* Identifier */) ||
  11616. (next.type === 7 /* Punctuator */ && next.value === '[') ||
  11617. (next.type === 7 /* Punctuator */ && next.value === '{') ||
  11618. (next.type === 4 /* Keyword */ && next.value === 'let') ||
  11619. (next.type === 4 /* Keyword */ && next.value === 'yield');
  11620. };
  11621. Parser.prototype.parseLexicalDeclaration = function (options) {
  11622. var node = this.createNode();
  11623. var kind = this.nextToken().value;
  11624. assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
  11625. var declarations = this.parseBindingList(kind, options);
  11626. this.consumeSemicolon();
  11627. return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
  11628. };
  11629. // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns
  11630. Parser.prototype.parseBindingRestElement = function (params, kind) {
  11631. var node = this.createNode();
  11632. this.expect('...');
  11633. var arg = this.parsePattern(params, kind);
  11634. return this.finalize(node, new Node.RestElement(arg));
  11635. };
  11636. Parser.prototype.parseArrayPattern = function (params, kind) {
  11637. var node = this.createNode();
  11638. this.expect('[');
  11639. var elements = [];
  11640. while (!this.match(']')) {
  11641. if (this.match(',')) {
  11642. this.nextToken();
  11643. elements.push(null);
  11644. }
  11645. else {
  11646. if (this.match('...')) {
  11647. elements.push(this.parseBindingRestElement(params, kind));
  11648. break;
  11649. }
  11650. else {
  11651. elements.push(this.parsePatternWithDefault(params, kind));
  11652. }
  11653. if (!this.match(']')) {
  11654. this.expect(',');
  11655. }
  11656. }
  11657. }
  11658. this.expect(']');
  11659. return this.finalize(node, new Node.ArrayPattern(elements));
  11660. };
  11661. Parser.prototype.parsePropertyPattern = function (params, kind) {
  11662. var node = this.createNode();
  11663. var computed = false;
  11664. var shorthand = false;
  11665. var method = false;
  11666. var key;
  11667. var value;
  11668. if (this.lookahead.type === 3 /* Identifier */) {
  11669. var keyToken = this.lookahead;
  11670. key = this.parseVariableIdentifier();
  11671. var init = this.finalize(node, new Node.Identifier(keyToken.value));
  11672. if (this.match('=')) {
  11673. params.push(keyToken);
  11674. shorthand = true;
  11675. this.nextToken();
  11676. var expr = this.parseAssignmentExpression();
  11677. value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
  11678. }
  11679. else if (!this.match(':')) {
  11680. params.push(keyToken);
  11681. shorthand = true;
  11682. value = init;
  11683. }
  11684. else {
  11685. this.expect(':');
  11686. value = this.parsePatternWithDefault(params, kind);
  11687. }
  11688. }
  11689. else {
  11690. computed = this.match('[');
  11691. key = this.parseObjectPropertyKey();
  11692. this.expect(':');
  11693. value = this.parsePatternWithDefault(params, kind);
  11694. }
  11695. return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
  11696. };
  11697. Parser.prototype.parseObjectPattern = function (params, kind) {
  11698. var node = this.createNode();
  11699. var properties = [];
  11700. this.expect('{');
  11701. while (!this.match('}')) {
  11702. properties.push(this.parsePropertyPattern(params, kind));
  11703. if (!this.match('}')) {
  11704. this.expect(',');
  11705. }
  11706. }
  11707. this.expect('}');
  11708. return this.finalize(node, new Node.ObjectPattern(properties));
  11709. };
  11710. Parser.prototype.parsePattern = function (params, kind) {
  11711. var pattern;
  11712. if (this.match('[')) {
  11713. pattern = this.parseArrayPattern(params, kind);
  11714. }
  11715. else if (this.match('{')) {
  11716. pattern = this.parseObjectPattern(params, kind);
  11717. }
  11718. else {
  11719. if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
  11720. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
  11721. }
  11722. params.push(this.lookahead);
  11723. pattern = this.parseVariableIdentifier(kind);
  11724. }
  11725. return pattern;
  11726. };
  11727. Parser.prototype.parsePatternWithDefault = function (params, kind) {
  11728. var startToken = this.lookahead;
  11729. var pattern = this.parsePattern(params, kind);
  11730. if (this.match('=')) {
  11731. this.nextToken();
  11732. var previousAllowYield = this.context.allowYield;
  11733. this.context.allowYield = true;
  11734. var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11735. this.context.allowYield = previousAllowYield;
  11736. pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
  11737. }
  11738. return pattern;
  11739. };
  11740. // https://tc39.github.io/ecma262/#sec-variable-statement
  11741. Parser.prototype.parseVariableIdentifier = function (kind) {
  11742. var node = this.createNode();
  11743. var token = this.nextToken();
  11744. if (token.type === 4 /* Keyword */ && token.value === 'yield') {
  11745. if (this.context.strict) {
  11746. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  11747. }
  11748. else if (!this.context.allowYield) {
  11749. this.throwUnexpectedToken(token);
  11750. }
  11751. }
  11752. else if (token.type !== 3 /* Identifier */) {
  11753. if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) {
  11754. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  11755. }
  11756. else {
  11757. if (this.context.strict || token.value !== 'let' || kind !== 'var') {
  11758. this.throwUnexpectedToken(token);
  11759. }
  11760. }
  11761. }
  11762. else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') {
  11763. this.tolerateUnexpectedToken(token);
  11764. }
  11765. return this.finalize(node, new Node.Identifier(token.value));
  11766. };
  11767. Parser.prototype.parseVariableDeclaration = function (options) {
  11768. var node = this.createNode();
  11769. var params = [];
  11770. var id = this.parsePattern(params, 'var');
  11771. if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
  11772. if (this.scanner.isRestrictedWord(id.name)) {
  11773. this.tolerateError(messages_1.Messages.StrictVarName);
  11774. }
  11775. }
  11776. var init = null;
  11777. if (this.match('=')) {
  11778. this.nextToken();
  11779. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  11780. }
  11781. else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
  11782. this.expect('=');
  11783. }
  11784. return this.finalize(node, new Node.VariableDeclarator(id, init));
  11785. };
  11786. Parser.prototype.parseVariableDeclarationList = function (options) {
  11787. var opt = { inFor: options.inFor };
  11788. var list = [];
  11789. list.push(this.parseVariableDeclaration(opt));
  11790. while (this.match(',')) {
  11791. this.nextToken();
  11792. list.push(this.parseVariableDeclaration(opt));
  11793. }
  11794. return list;
  11795. };
  11796. Parser.prototype.parseVariableStatement = function () {
  11797. var node = this.createNode();
  11798. this.expectKeyword('var');
  11799. var declarations = this.parseVariableDeclarationList({ inFor: false });
  11800. this.consumeSemicolon();
  11801. return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
  11802. };
  11803. // https://tc39.github.io/ecma262/#sec-empty-statement
  11804. Parser.prototype.parseEmptyStatement = function () {
  11805. var node = this.createNode();
  11806. this.expect(';');
  11807. return this.finalize(node, new Node.EmptyStatement());
  11808. };
  11809. // https://tc39.github.io/ecma262/#sec-expression-statement
  11810. Parser.prototype.parseExpressionStatement = function () {
  11811. var node = this.createNode();
  11812. var expr = this.parseExpression();
  11813. this.consumeSemicolon();
  11814. return this.finalize(node, new Node.ExpressionStatement(expr));
  11815. };
  11816. // https://tc39.github.io/ecma262/#sec-if-statement
  11817. Parser.prototype.parseIfClause = function () {
  11818. if (this.context.strict && this.matchKeyword('function')) {
  11819. this.tolerateError(messages_1.Messages.StrictFunction);
  11820. }
  11821. return this.parseStatement();
  11822. };
  11823. Parser.prototype.parseIfStatement = function () {
  11824. var node = this.createNode();
  11825. var consequent;
  11826. var alternate = null;
  11827. this.expectKeyword('if');
  11828. this.expect('(');
  11829. var test = this.parseExpression();
  11830. if (!this.match(')') && this.config.tolerant) {
  11831. this.tolerateUnexpectedToken(this.nextToken());
  11832. consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
  11833. }
  11834. else {
  11835. this.expect(')');
  11836. consequent = this.parseIfClause();
  11837. if (this.matchKeyword('else')) {
  11838. this.nextToken();
  11839. alternate = this.parseIfClause();
  11840. }
  11841. }
  11842. return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
  11843. };
  11844. // https://tc39.github.io/ecma262/#sec-do-while-statement
  11845. Parser.prototype.parseDoWhileStatement = function () {
  11846. var node = this.createNode();
  11847. this.expectKeyword('do');
  11848. var previousInIteration = this.context.inIteration;
  11849. this.context.inIteration = true;
  11850. var body = this.parseStatement();
  11851. this.context.inIteration = previousInIteration;
  11852. this.expectKeyword('while');
  11853. this.expect('(');
  11854. var test = this.parseExpression();
  11855. if (!this.match(')') && this.config.tolerant) {
  11856. this.tolerateUnexpectedToken(this.nextToken());
  11857. }
  11858. else {
  11859. this.expect(')');
  11860. if (this.match(';')) {
  11861. this.nextToken();
  11862. }
  11863. }
  11864. return this.finalize(node, new Node.DoWhileStatement(body, test));
  11865. };
  11866. // https://tc39.github.io/ecma262/#sec-while-statement
  11867. Parser.prototype.parseWhileStatement = function () {
  11868. var node = this.createNode();
  11869. var body;
  11870. this.expectKeyword('while');
  11871. this.expect('(');
  11872. var test = this.parseExpression();
  11873. if (!this.match(')') && this.config.tolerant) {
  11874. this.tolerateUnexpectedToken(this.nextToken());
  11875. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  11876. }
  11877. else {
  11878. this.expect(')');
  11879. var previousInIteration = this.context.inIteration;
  11880. this.context.inIteration = true;
  11881. body = this.parseStatement();
  11882. this.context.inIteration = previousInIteration;
  11883. }
  11884. return this.finalize(node, new Node.WhileStatement(test, body));
  11885. };
  11886. // https://tc39.github.io/ecma262/#sec-for-statement
  11887. // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements
  11888. Parser.prototype.parseForStatement = function () {
  11889. var init = null;
  11890. var test = null;
  11891. var update = null;
  11892. var forIn = true;
  11893. var left, right;
  11894. var node = this.createNode();
  11895. this.expectKeyword('for');
  11896. this.expect('(');
  11897. if (this.match(';')) {
  11898. this.nextToken();
  11899. }
  11900. else {
  11901. if (this.matchKeyword('var')) {
  11902. init = this.createNode();
  11903. this.nextToken();
  11904. var previousAllowIn = this.context.allowIn;
  11905. this.context.allowIn = false;
  11906. var declarations = this.parseVariableDeclarationList({ inFor: true });
  11907. this.context.allowIn = previousAllowIn;
  11908. if (declarations.length === 1 && this.matchKeyword('in')) {
  11909. var decl = declarations[0];
  11910. if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
  11911. this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
  11912. }
  11913. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  11914. this.nextToken();
  11915. left = init;
  11916. right = this.parseExpression();
  11917. init = null;
  11918. }
  11919. else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
  11920. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  11921. this.nextToken();
  11922. left = init;
  11923. right = this.parseAssignmentExpression();
  11924. init = null;
  11925. forIn = false;
  11926. }
  11927. else {
  11928. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  11929. this.expect(';');
  11930. }
  11931. }
  11932. else if (this.matchKeyword('const') || this.matchKeyword('let')) {
  11933. init = this.createNode();
  11934. var kind = this.nextToken().value;
  11935. if (!this.context.strict && this.lookahead.value === 'in') {
  11936. init = this.finalize(init, new Node.Identifier(kind));
  11937. this.nextToken();
  11938. left = init;
  11939. right = this.parseExpression();
  11940. init = null;
  11941. }
  11942. else {
  11943. var previousAllowIn = this.context.allowIn;
  11944. this.context.allowIn = false;
  11945. var declarations = this.parseBindingList(kind, { inFor: true });
  11946. this.context.allowIn = previousAllowIn;
  11947. if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
  11948. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  11949. this.nextToken();
  11950. left = init;
  11951. right = this.parseExpression();
  11952. init = null;
  11953. }
  11954. else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
  11955. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  11956. this.nextToken();
  11957. left = init;
  11958. right = this.parseAssignmentExpression();
  11959. init = null;
  11960. forIn = false;
  11961. }
  11962. else {
  11963. this.consumeSemicolon();
  11964. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  11965. }
  11966. }
  11967. }
  11968. else {
  11969. var initStartToken = this.lookahead;
  11970. var previousAllowIn = this.context.allowIn;
  11971. this.context.allowIn = false;
  11972. init = this.inheritCoverGrammar(this.parseAssignmentExpression);
  11973. this.context.allowIn = previousAllowIn;
  11974. if (this.matchKeyword('in')) {
  11975. if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
  11976. this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
  11977. }
  11978. this.nextToken();
  11979. this.reinterpretExpressionAsPattern(init);
  11980. left = init;
  11981. right = this.parseExpression();
  11982. init = null;
  11983. }
  11984. else if (this.matchContextualKeyword('of')) {
  11985. if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
  11986. this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
  11987. }
  11988. this.nextToken();
  11989. this.reinterpretExpressionAsPattern(init);
  11990. left = init;
  11991. right = this.parseAssignmentExpression();
  11992. init = null;
  11993. forIn = false;
  11994. }
  11995. else {
  11996. if (this.match(',')) {
  11997. var initSeq = [init];
  11998. while (this.match(',')) {
  11999. this.nextToken();
  12000. initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
  12001. }
  12002. init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
  12003. }
  12004. this.expect(';');
  12005. }
  12006. }
  12007. }
  12008. if (typeof left === 'undefined') {
  12009. if (!this.match(';')) {
  12010. test = this.parseExpression();
  12011. }
  12012. this.expect(';');
  12013. if (!this.match(')')) {
  12014. update = this.parseExpression();
  12015. }
  12016. }
  12017. var body;
  12018. if (!this.match(')') && this.config.tolerant) {
  12019. this.tolerateUnexpectedToken(this.nextToken());
  12020. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  12021. }
  12022. else {
  12023. this.expect(')');
  12024. var previousInIteration = this.context.inIteration;
  12025. this.context.inIteration = true;
  12026. body = this.isolateCoverGrammar(this.parseStatement);
  12027. this.context.inIteration = previousInIteration;
  12028. }
  12029. return (typeof left === 'undefined') ?
  12030. this.finalize(node, new Node.ForStatement(init, test, update, body)) :
  12031. forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) :
  12032. this.finalize(node, new Node.ForOfStatement(left, right, body));
  12033. };
  12034. // https://tc39.github.io/ecma262/#sec-continue-statement
  12035. Parser.prototype.parseContinueStatement = function () {
  12036. var node = this.createNode();
  12037. this.expectKeyword('continue');
  12038. var label = null;
  12039. if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
  12040. var id = this.parseVariableIdentifier();
  12041. label = id;
  12042. var key = '$' + id.name;
  12043. if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  12044. this.throwError(messages_1.Messages.UnknownLabel, id.name);
  12045. }
  12046. }
  12047. this.consumeSemicolon();
  12048. if (label === null && !this.context.inIteration) {
  12049. this.throwError(messages_1.Messages.IllegalContinue);
  12050. }
  12051. return this.finalize(node, new Node.ContinueStatement(label));
  12052. };
  12053. // https://tc39.github.io/ecma262/#sec-break-statement
  12054. Parser.prototype.parseBreakStatement = function () {
  12055. var node = this.createNode();
  12056. this.expectKeyword('break');
  12057. var label = null;
  12058. if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
  12059. var id = this.parseVariableIdentifier();
  12060. var key = '$' + id.name;
  12061. if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  12062. this.throwError(messages_1.Messages.UnknownLabel, id.name);
  12063. }
  12064. label = id;
  12065. }
  12066. this.consumeSemicolon();
  12067. if (label === null && !this.context.inIteration && !this.context.inSwitch) {
  12068. this.throwError(messages_1.Messages.IllegalBreak);
  12069. }
  12070. return this.finalize(node, new Node.BreakStatement(label));
  12071. };
  12072. // https://tc39.github.io/ecma262/#sec-return-statement
  12073. Parser.prototype.parseReturnStatement = function () {
  12074. if (!this.context.inFunctionBody) {
  12075. this.tolerateError(messages_1.Messages.IllegalReturn);
  12076. }
  12077. var node = this.createNode();
  12078. this.expectKeyword('return');
  12079. var hasArgument = (!this.match(';') && !this.match('}') &&
  12080. !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) ||
  12081. this.lookahead.type === 8 /* StringLiteral */ ||
  12082. this.lookahead.type === 10 /* Template */;
  12083. var argument = hasArgument ? this.parseExpression() : null;
  12084. this.consumeSemicolon();
  12085. return this.finalize(node, new Node.ReturnStatement(argument));
  12086. };
  12087. // https://tc39.github.io/ecma262/#sec-with-statement
  12088. Parser.prototype.parseWithStatement = function () {
  12089. if (this.context.strict) {
  12090. this.tolerateError(messages_1.Messages.StrictModeWith);
  12091. }
  12092. var node = this.createNode();
  12093. var body;
  12094. this.expectKeyword('with');
  12095. this.expect('(');
  12096. var object = this.parseExpression();
  12097. if (!this.match(')') && this.config.tolerant) {
  12098. this.tolerateUnexpectedToken(this.nextToken());
  12099. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  12100. }
  12101. else {
  12102. this.expect(')');
  12103. body = this.parseStatement();
  12104. }
  12105. return this.finalize(node, new Node.WithStatement(object, body));
  12106. };
  12107. // https://tc39.github.io/ecma262/#sec-switch-statement
  12108. Parser.prototype.parseSwitchCase = function () {
  12109. var node = this.createNode();
  12110. var test;
  12111. if (this.matchKeyword('default')) {
  12112. this.nextToken();
  12113. test = null;
  12114. }
  12115. else {
  12116. this.expectKeyword('case');
  12117. test = this.parseExpression();
  12118. }
  12119. this.expect(':');
  12120. var consequent = [];
  12121. while (true) {
  12122. if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
  12123. break;
  12124. }
  12125. consequent.push(this.parseStatementListItem());
  12126. }
  12127. return this.finalize(node, new Node.SwitchCase(test, consequent));
  12128. };
  12129. Parser.prototype.parseSwitchStatement = function () {
  12130. var node = this.createNode();
  12131. this.expectKeyword('switch');
  12132. this.expect('(');
  12133. var discriminant = this.parseExpression();
  12134. this.expect(')');
  12135. var previousInSwitch = this.context.inSwitch;
  12136. this.context.inSwitch = true;
  12137. var cases = [];
  12138. var defaultFound = false;
  12139. this.expect('{');
  12140. while (true) {
  12141. if (this.match('}')) {
  12142. break;
  12143. }
  12144. var clause = this.parseSwitchCase();
  12145. if (clause.test === null) {
  12146. if (defaultFound) {
  12147. this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
  12148. }
  12149. defaultFound = true;
  12150. }
  12151. cases.push(clause);
  12152. }
  12153. this.expect('}');
  12154. this.context.inSwitch = previousInSwitch;
  12155. return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
  12156. };
  12157. // https://tc39.github.io/ecma262/#sec-labelled-statements
  12158. Parser.prototype.parseLabelledStatement = function () {
  12159. var node = this.createNode();
  12160. var expr = this.parseExpression();
  12161. var statement;
  12162. if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) {
  12163. this.nextToken();
  12164. var id = expr;
  12165. var key = '$' + id.name;
  12166. if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  12167. this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
  12168. }
  12169. this.context.labelSet[key] = true;
  12170. var body = void 0;
  12171. if (this.matchKeyword('class')) {
  12172. this.tolerateUnexpectedToken(this.lookahead);
  12173. body = this.parseClassDeclaration();
  12174. }
  12175. else if (this.matchKeyword('function')) {
  12176. var token = this.lookahead;
  12177. var declaration = this.parseFunctionDeclaration();
  12178. if (this.context.strict) {
  12179. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
  12180. }
  12181. else if (declaration.generator) {
  12182. this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
  12183. }
  12184. body = declaration;
  12185. }
  12186. else {
  12187. body = this.parseStatement();
  12188. }
  12189. delete this.context.labelSet[key];
  12190. statement = new Node.LabeledStatement(id, body);
  12191. }
  12192. else {
  12193. this.consumeSemicolon();
  12194. statement = new Node.ExpressionStatement(expr);
  12195. }
  12196. return this.finalize(node, statement);
  12197. };
  12198. // https://tc39.github.io/ecma262/#sec-throw-statement
  12199. Parser.prototype.parseThrowStatement = function () {
  12200. var node = this.createNode();
  12201. this.expectKeyword('throw');
  12202. if (this.hasLineTerminator) {
  12203. this.throwError(messages_1.Messages.NewlineAfterThrow);
  12204. }
  12205. var argument = this.parseExpression();
  12206. this.consumeSemicolon();
  12207. return this.finalize(node, new Node.ThrowStatement(argument));
  12208. };
  12209. // https://tc39.github.io/ecma262/#sec-try-statement
  12210. Parser.prototype.parseCatchClause = function () {
  12211. var node = this.createNode();
  12212. this.expectKeyword('catch');
  12213. this.expect('(');
  12214. if (this.match(')')) {
  12215. this.throwUnexpectedToken(this.lookahead);
  12216. }
  12217. var params = [];
  12218. var param = this.parsePattern(params);
  12219. var paramMap = {};
  12220. for (var i = 0; i < params.length; i++) {
  12221. var key = '$' + params[i].value;
  12222. if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
  12223. this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
  12224. }
  12225. paramMap[key] = true;
  12226. }
  12227. if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
  12228. if (this.scanner.isRestrictedWord(param.name)) {
  12229. this.tolerateError(messages_1.Messages.StrictCatchVariable);
  12230. }
  12231. }
  12232. this.expect(')');
  12233. var body = this.parseBlock();
  12234. return this.finalize(node, new Node.CatchClause(param, body));
  12235. };
  12236. Parser.prototype.parseFinallyClause = function () {
  12237. this.expectKeyword('finally');
  12238. return this.parseBlock();
  12239. };
  12240. Parser.prototype.parseTryStatement = function () {
  12241. var node = this.createNode();
  12242. this.expectKeyword('try');
  12243. var block = this.parseBlock();
  12244. var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
  12245. var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
  12246. if (!handler && !finalizer) {
  12247. this.throwError(messages_1.Messages.NoCatchOrFinally);
  12248. }
  12249. return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
  12250. };
  12251. // https://tc39.github.io/ecma262/#sec-debugger-statement
  12252. Parser.prototype.parseDebuggerStatement = function () {
  12253. var node = this.createNode();
  12254. this.expectKeyword('debugger');
  12255. this.consumeSemicolon();
  12256. return this.finalize(node, new Node.DebuggerStatement());
  12257. };
  12258. // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations
  12259. Parser.prototype.parseStatement = function () {
  12260. var statement;
  12261. switch (this.lookahead.type) {
  12262. case 1 /* BooleanLiteral */:
  12263. case 5 /* NullLiteral */:
  12264. case 6 /* NumericLiteral */:
  12265. case 8 /* StringLiteral */:
  12266. case 10 /* Template */:
  12267. case 9 /* RegularExpression */:
  12268. statement = this.parseExpressionStatement();
  12269. break;
  12270. case 7 /* Punctuator */:
  12271. var value = this.lookahead.value;
  12272. if (value === '{') {
  12273. statement = this.parseBlock();
  12274. }
  12275. else if (value === '(') {
  12276. statement = this.parseExpressionStatement();
  12277. }
  12278. else if (value === ';') {
  12279. statement = this.parseEmptyStatement();
  12280. }
  12281. else {
  12282. statement = this.parseExpressionStatement();
  12283. }
  12284. break;
  12285. case 3 /* Identifier */:
  12286. statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
  12287. break;
  12288. case 4 /* Keyword */:
  12289. switch (this.lookahead.value) {
  12290. case 'break':
  12291. statement = this.parseBreakStatement();
  12292. break;
  12293. case 'continue':
  12294. statement = this.parseContinueStatement();
  12295. break;
  12296. case 'debugger':
  12297. statement = this.parseDebuggerStatement();
  12298. break;
  12299. case 'do':
  12300. statement = this.parseDoWhileStatement();
  12301. break;
  12302. case 'for':
  12303. statement = this.parseForStatement();
  12304. break;
  12305. case 'function':
  12306. statement = this.parseFunctionDeclaration();
  12307. break;
  12308. case 'if':
  12309. statement = this.parseIfStatement();
  12310. break;
  12311. case 'return':
  12312. statement = this.parseReturnStatement();
  12313. break;
  12314. case 'switch':
  12315. statement = this.parseSwitchStatement();
  12316. break;
  12317. case 'throw':
  12318. statement = this.parseThrowStatement();
  12319. break;
  12320. case 'try':
  12321. statement = this.parseTryStatement();
  12322. break;
  12323. case 'var':
  12324. statement = this.parseVariableStatement();
  12325. break;
  12326. case 'while':
  12327. statement = this.parseWhileStatement();
  12328. break;
  12329. case 'with':
  12330. statement = this.parseWithStatement();
  12331. break;
  12332. default:
  12333. statement = this.parseExpressionStatement();
  12334. break;
  12335. }
  12336. break;
  12337. default:
  12338. statement = this.throwUnexpectedToken(this.lookahead);
  12339. }
  12340. return statement;
  12341. };
  12342. // https://tc39.github.io/ecma262/#sec-function-definitions
  12343. Parser.prototype.parseFunctionSourceElements = function () {
  12344. var node = this.createNode();
  12345. this.expect('{');
  12346. var body = this.parseDirectivePrologues();
  12347. var previousLabelSet = this.context.labelSet;
  12348. var previousInIteration = this.context.inIteration;
  12349. var previousInSwitch = this.context.inSwitch;
  12350. var previousInFunctionBody = this.context.inFunctionBody;
  12351. this.context.labelSet = {};
  12352. this.context.inIteration = false;
  12353. this.context.inSwitch = false;
  12354. this.context.inFunctionBody = true;
  12355. while (this.lookahead.type !== 2 /* EOF */) {
  12356. if (this.match('}')) {
  12357. break;
  12358. }
  12359. body.push(this.parseStatementListItem());
  12360. }
  12361. this.expect('}');
  12362. this.context.labelSet = previousLabelSet;
  12363. this.context.inIteration = previousInIteration;
  12364. this.context.inSwitch = previousInSwitch;
  12365. this.context.inFunctionBody = previousInFunctionBody;
  12366. return this.finalize(node, new Node.BlockStatement(body));
  12367. };
  12368. Parser.prototype.validateParam = function (options, param, name) {
  12369. var key = '$' + name;
  12370. if (this.context.strict) {
  12371. if (this.scanner.isRestrictedWord(name)) {
  12372. options.stricted = param;
  12373. options.message = messages_1.Messages.StrictParamName;
  12374. }
  12375. if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  12376. options.stricted = param;
  12377. options.message = messages_1.Messages.StrictParamDupe;
  12378. }
  12379. }
  12380. else if (!options.firstRestricted) {
  12381. if (this.scanner.isRestrictedWord(name)) {
  12382. options.firstRestricted = param;
  12383. options.message = messages_1.Messages.StrictParamName;
  12384. }
  12385. else if (this.scanner.isStrictModeReservedWord(name)) {
  12386. options.firstRestricted = param;
  12387. options.message = messages_1.Messages.StrictReservedWord;
  12388. }
  12389. else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  12390. options.stricted = param;
  12391. options.message = messages_1.Messages.StrictParamDupe;
  12392. }
  12393. }
  12394. /* istanbul ignore next */
  12395. if (typeof Object.defineProperty === 'function') {
  12396. Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
  12397. }
  12398. else {
  12399. options.paramSet[key] = true;
  12400. }
  12401. };
  12402. Parser.prototype.parseRestElement = function (params) {
  12403. var node = this.createNode();
  12404. this.expect('...');
  12405. var arg = this.parsePattern(params);
  12406. if (this.match('=')) {
  12407. this.throwError(messages_1.Messages.DefaultRestParameter);
  12408. }
  12409. if (!this.match(')')) {
  12410. this.throwError(messages_1.Messages.ParameterAfterRestParameter);
  12411. }
  12412. return this.finalize(node, new Node.RestElement(arg));
  12413. };
  12414. Parser.prototype.parseFormalParameter = function (options) {
  12415. var params = [];
  12416. var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
  12417. for (var i = 0; i < params.length; i++) {
  12418. this.validateParam(options, params[i], params[i].value);
  12419. }
  12420. options.simple = options.simple && (param instanceof Node.Identifier);
  12421. options.params.push(param);
  12422. };
  12423. Parser.prototype.parseFormalParameters = function (firstRestricted) {
  12424. var options;
  12425. options = {
  12426. simple: true,
  12427. params: [],
  12428. firstRestricted: firstRestricted
  12429. };
  12430. this.expect('(');
  12431. if (!this.match(')')) {
  12432. options.paramSet = {};
  12433. while (this.lookahead.type !== 2 /* EOF */) {
  12434. this.parseFormalParameter(options);
  12435. if (this.match(')')) {
  12436. break;
  12437. }
  12438. this.expect(',');
  12439. if (this.match(')')) {
  12440. break;
  12441. }
  12442. }
  12443. }
  12444. this.expect(')');
  12445. return {
  12446. simple: options.simple,
  12447. params: options.params,
  12448. stricted: options.stricted,
  12449. firstRestricted: options.firstRestricted,
  12450. message: options.message
  12451. };
  12452. };
  12453. Parser.prototype.matchAsyncFunction = function () {
  12454. var match = this.matchContextualKeyword('async');
  12455. if (match) {
  12456. var state = this.scanner.saveState();
  12457. this.scanner.scanComments();
  12458. var next = this.scanner.lex();
  12459. this.scanner.restoreState(state);
  12460. match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function');
  12461. }
  12462. return match;
  12463. };
  12464. Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
  12465. var node = this.createNode();
  12466. var isAsync = this.matchContextualKeyword('async');
  12467. if (isAsync) {
  12468. this.nextToken();
  12469. }
  12470. this.expectKeyword('function');
  12471. var isGenerator = isAsync ? false : this.match('*');
  12472. if (isGenerator) {
  12473. this.nextToken();
  12474. }
  12475. var message;
  12476. var id = null;
  12477. var firstRestricted = null;
  12478. if (!identifierIsOptional || !this.match('(')) {
  12479. var token = this.lookahead;
  12480. id = this.parseVariableIdentifier();
  12481. if (this.context.strict) {
  12482. if (this.scanner.isRestrictedWord(token.value)) {
  12483. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
  12484. }
  12485. }
  12486. else {
  12487. if (this.scanner.isRestrictedWord(token.value)) {
  12488. firstRestricted = token;
  12489. message = messages_1.Messages.StrictFunctionName;
  12490. }
  12491. else if (this.scanner.isStrictModeReservedWord(token.value)) {
  12492. firstRestricted = token;
  12493. message = messages_1.Messages.StrictReservedWord;
  12494. }
  12495. }
  12496. }
  12497. var previousAllowAwait = this.context.await;
  12498. var previousAllowYield = this.context.allowYield;
  12499. this.context.await = isAsync;
  12500. this.context.allowYield = !isGenerator;
  12501. var formalParameters = this.parseFormalParameters(firstRestricted);
  12502. var params = formalParameters.params;
  12503. var stricted = formalParameters.stricted;
  12504. firstRestricted = formalParameters.firstRestricted;
  12505. if (formalParameters.message) {
  12506. message = formalParameters.message;
  12507. }
  12508. var previousStrict = this.context.strict;
  12509. var previousAllowStrictDirective = this.context.allowStrictDirective;
  12510. this.context.allowStrictDirective = formalParameters.simple;
  12511. var body = this.parseFunctionSourceElements();
  12512. if (this.context.strict && firstRestricted) {
  12513. this.throwUnexpectedToken(firstRestricted, message);
  12514. }
  12515. if (this.context.strict && stricted) {
  12516. this.tolerateUnexpectedToken(stricted, message);
  12517. }
  12518. this.context.strict = previousStrict;
  12519. this.context.allowStrictDirective = previousAllowStrictDirective;
  12520. this.context.await = previousAllowAwait;
  12521. this.context.allowYield = previousAllowYield;
  12522. return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) :
  12523. this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
  12524. };
  12525. Parser.prototype.parseFunctionExpression = function () {
  12526. var node = this.createNode();
  12527. var isAsync = this.matchContextualKeyword('async');
  12528. if (isAsync) {
  12529. this.nextToken();
  12530. }
  12531. this.expectKeyword('function');
  12532. var isGenerator = isAsync ? false : this.match('*');
  12533. if (isGenerator) {
  12534. this.nextToken();
  12535. }
  12536. var message;
  12537. var id = null;
  12538. var firstRestricted;
  12539. var previousAllowAwait = this.context.await;
  12540. var previousAllowYield = this.context.allowYield;
  12541. this.context.await = isAsync;
  12542. this.context.allowYield = !isGenerator;
  12543. if (!this.match('(')) {
  12544. var token = this.lookahead;
  12545. id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier();
  12546. if (this.context.strict) {
  12547. if (this.scanner.isRestrictedWord(token.value)) {
  12548. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
  12549. }
  12550. }
  12551. else {
  12552. if (this.scanner.isRestrictedWord(token.value)) {
  12553. firstRestricted = token;
  12554. message = messages_1.Messages.StrictFunctionName;
  12555. }
  12556. else if (this.scanner.isStrictModeReservedWord(token.value)) {
  12557. firstRestricted = token;
  12558. message = messages_1.Messages.StrictReservedWord;
  12559. }
  12560. }
  12561. }
  12562. var formalParameters = this.parseFormalParameters(firstRestricted);
  12563. var params = formalParameters.params;
  12564. var stricted = formalParameters.stricted;
  12565. firstRestricted = formalParameters.firstRestricted;
  12566. if (formalParameters.message) {
  12567. message = formalParameters.message;
  12568. }
  12569. var previousStrict = this.context.strict;
  12570. var previousAllowStrictDirective = this.context.allowStrictDirective;
  12571. this.context.allowStrictDirective = formalParameters.simple;
  12572. var body = this.parseFunctionSourceElements();
  12573. if (this.context.strict && firstRestricted) {
  12574. this.throwUnexpectedToken(firstRestricted, message);
  12575. }
  12576. if (this.context.strict && stricted) {
  12577. this.tolerateUnexpectedToken(stricted, message);
  12578. }
  12579. this.context.strict = previousStrict;
  12580. this.context.allowStrictDirective = previousAllowStrictDirective;
  12581. this.context.await = previousAllowAwait;
  12582. this.context.allowYield = previousAllowYield;
  12583. return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) :
  12584. this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
  12585. };
  12586. // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive
  12587. Parser.prototype.parseDirective = function () {
  12588. var token = this.lookahead;
  12589. var node = this.createNode();
  12590. var expr = this.parseExpression();
  12591. var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null;
  12592. this.consumeSemicolon();
  12593. return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
  12594. };
  12595. Parser.prototype.parseDirectivePrologues = function () {
  12596. var firstRestricted = null;
  12597. var body = [];
  12598. while (true) {
  12599. var token = this.lookahead;
  12600. if (token.type !== 8 /* StringLiteral */) {
  12601. break;
  12602. }
  12603. var statement = this.parseDirective();
  12604. body.push(statement);
  12605. var directive = statement.directive;
  12606. if (typeof directive !== 'string') {
  12607. break;
  12608. }
  12609. if (directive === 'use strict') {
  12610. this.context.strict = true;
  12611. if (firstRestricted) {
  12612. this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
  12613. }
  12614. if (!this.context.allowStrictDirective) {
  12615. this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
  12616. }
  12617. }
  12618. else {
  12619. if (!firstRestricted && token.octal) {
  12620. firstRestricted = token;
  12621. }
  12622. }
  12623. }
  12624. return body;
  12625. };
  12626. // https://tc39.github.io/ecma262/#sec-method-definitions
  12627. Parser.prototype.qualifiedPropertyName = function (token) {
  12628. switch (token.type) {
  12629. case 3 /* Identifier */:
  12630. case 8 /* StringLiteral */:
  12631. case 1 /* BooleanLiteral */:
  12632. case 5 /* NullLiteral */:
  12633. case 6 /* NumericLiteral */:
  12634. case 4 /* Keyword */:
  12635. return true;
  12636. case 7 /* Punctuator */:
  12637. return token.value === '[';
  12638. }
  12639. return false;
  12640. };
  12641. Parser.prototype.parseGetterMethod = function () {
  12642. var node = this.createNode();
  12643. var isGenerator = false;
  12644. var previousAllowYield = this.context.allowYield;
  12645. this.context.allowYield = !isGenerator;
  12646. var formalParameters = this.parseFormalParameters();
  12647. if (formalParameters.params.length > 0) {
  12648. this.tolerateError(messages_1.Messages.BadGetterArity);
  12649. }
  12650. var method = this.parsePropertyMethod(formalParameters);
  12651. this.context.allowYield = previousAllowYield;
  12652. return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
  12653. };
  12654. Parser.prototype.parseSetterMethod = function () {
  12655. var node = this.createNode();
  12656. var isGenerator = false;
  12657. var previousAllowYield = this.context.allowYield;
  12658. this.context.allowYield = !isGenerator;
  12659. var formalParameters = this.parseFormalParameters();
  12660. if (formalParameters.params.length !== 1) {
  12661. this.tolerateError(messages_1.Messages.BadSetterArity);
  12662. }
  12663. else if (formalParameters.params[0] instanceof Node.RestElement) {
  12664. this.tolerateError(messages_1.Messages.BadSetterRestParameter);
  12665. }
  12666. var method = this.parsePropertyMethod(formalParameters);
  12667. this.context.allowYield = previousAllowYield;
  12668. return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
  12669. };
  12670. Parser.prototype.parseGeneratorMethod = function () {
  12671. var node = this.createNode();
  12672. var isGenerator = true;
  12673. var previousAllowYield = this.context.allowYield;
  12674. this.context.allowYield = true;
  12675. var params = this.parseFormalParameters();
  12676. this.context.allowYield = false;
  12677. var method = this.parsePropertyMethod(params);
  12678. this.context.allowYield = previousAllowYield;
  12679. return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
  12680. };
  12681. // https://tc39.github.io/ecma262/#sec-generator-function-definitions
  12682. Parser.prototype.isStartOfExpression = function () {
  12683. var start = true;
  12684. var value = this.lookahead.value;
  12685. switch (this.lookahead.type) {
  12686. case 7 /* Punctuator */:
  12687. start = (value === '[') || (value === '(') || (value === '{') ||
  12688. (value === '+') || (value === '-') ||
  12689. (value === '!') || (value === '~') ||
  12690. (value === '++') || (value === '--') ||
  12691. (value === '/') || (value === '/='); // regular expression literal
  12692. break;
  12693. case 4 /* Keyword */:
  12694. start = (value === 'class') || (value === 'delete') ||
  12695. (value === 'function') || (value === 'let') || (value === 'new') ||
  12696. (value === 'super') || (value === 'this') || (value === 'typeof') ||
  12697. (value === 'void') || (value === 'yield');
  12698. break;
  12699. }
  12700. return start;
  12701. };
  12702. Parser.prototype.parseYieldExpression = function () {
  12703. var node = this.createNode();
  12704. this.expectKeyword('yield');
  12705. var argument = null;
  12706. var delegate = false;
  12707. if (!this.hasLineTerminator) {
  12708. var previousAllowYield = this.context.allowYield;
  12709. this.context.allowYield = false;
  12710. delegate = this.match('*');
  12711. if (delegate) {
  12712. this.nextToken();
  12713. argument = this.parseAssignmentExpression();
  12714. }
  12715. else if (this.isStartOfExpression()) {
  12716. argument = this.parseAssignmentExpression();
  12717. }
  12718. this.context.allowYield = previousAllowYield;
  12719. }
  12720. return this.finalize(node, new Node.YieldExpression(argument, delegate));
  12721. };
  12722. // https://tc39.github.io/ecma262/#sec-class-definitions
  12723. Parser.prototype.parseClassElement = function (hasConstructor) {
  12724. var token = this.lookahead;
  12725. var node = this.createNode();
  12726. var kind = '';
  12727. var key = null;
  12728. var value = null;
  12729. var computed = false;
  12730. var method = false;
  12731. var isStatic = false;
  12732. var isAsync = false;
  12733. if (this.match('*')) {
  12734. this.nextToken();
  12735. }
  12736. else {
  12737. computed = this.match('[');
  12738. key = this.parseObjectPropertyKey();
  12739. var id = key;
  12740. if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
  12741. token = this.lookahead;
  12742. isStatic = true;
  12743. computed = this.match('[');
  12744. if (this.match('*')) {
  12745. this.nextToken();
  12746. }
  12747. else {
  12748. key = this.parseObjectPropertyKey();
  12749. }
  12750. }
  12751. if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) {
  12752. var punctuator = this.lookahead.value;
  12753. if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
  12754. isAsync = true;
  12755. token = this.lookahead;
  12756. key = this.parseObjectPropertyKey();
  12757. if (token.type === 3 /* Identifier */ && token.value === 'constructor') {
  12758. this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
  12759. }
  12760. }
  12761. }
  12762. }
  12763. var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
  12764. if (token.type === 3 /* Identifier */) {
  12765. if (token.value === 'get' && lookaheadPropertyKey) {
  12766. kind = 'get';
  12767. computed = this.match('[');
  12768. key = this.parseObjectPropertyKey();
  12769. this.context.allowYield = false;
  12770. value = this.parseGetterMethod();
  12771. }
  12772. else if (token.value === 'set' && lookaheadPropertyKey) {
  12773. kind = 'set';
  12774. computed = this.match('[');
  12775. key = this.parseObjectPropertyKey();
  12776. value = this.parseSetterMethod();
  12777. }
  12778. }
  12779. else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
  12780. kind = 'init';
  12781. computed = this.match('[');
  12782. key = this.parseObjectPropertyKey();
  12783. value = this.parseGeneratorMethod();
  12784. method = true;
  12785. }
  12786. if (!kind && key && this.match('(')) {
  12787. kind = 'init';
  12788. value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
  12789. method = true;
  12790. }
  12791. if (!kind) {
  12792. this.throwUnexpectedToken(this.lookahead);
  12793. }
  12794. if (kind === 'init') {
  12795. kind = 'method';
  12796. }
  12797. if (!computed) {
  12798. if (isStatic && this.isPropertyKey(key, 'prototype')) {
  12799. this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
  12800. }
  12801. if (!isStatic && this.isPropertyKey(key, 'constructor')) {
  12802. if (kind !== 'method' || !method || (value && value.generator)) {
  12803. this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
  12804. }
  12805. if (hasConstructor.value) {
  12806. this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
  12807. }
  12808. else {
  12809. hasConstructor.value = true;
  12810. }
  12811. kind = 'constructor';
  12812. }
  12813. }
  12814. return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
  12815. };
  12816. Parser.prototype.parseClassElementList = function () {
  12817. var body = [];
  12818. var hasConstructor = { value: false };
  12819. this.expect('{');
  12820. while (!this.match('}')) {
  12821. if (this.match(';')) {
  12822. this.nextToken();
  12823. }
  12824. else {
  12825. body.push(this.parseClassElement(hasConstructor));
  12826. }
  12827. }
  12828. this.expect('}');
  12829. return body;
  12830. };
  12831. Parser.prototype.parseClassBody = function () {
  12832. var node = this.createNode();
  12833. var elementList = this.parseClassElementList();
  12834. return this.finalize(node, new Node.ClassBody(elementList));
  12835. };
  12836. Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
  12837. var node = this.createNode();
  12838. var previousStrict = this.context.strict;
  12839. this.context.strict = true;
  12840. this.expectKeyword('class');
  12841. var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier();
  12842. var superClass = null;
  12843. if (this.matchKeyword('extends')) {
  12844. this.nextToken();
  12845. superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  12846. }
  12847. var classBody = this.parseClassBody();
  12848. this.context.strict = previousStrict;
  12849. return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
  12850. };
  12851. Parser.prototype.parseClassExpression = function () {
  12852. var node = this.createNode();
  12853. var previousStrict = this.context.strict;
  12854. this.context.strict = true;
  12855. this.expectKeyword('class');
  12856. var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null;
  12857. var superClass = null;
  12858. if (this.matchKeyword('extends')) {
  12859. this.nextToken();
  12860. superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  12861. }
  12862. var classBody = this.parseClassBody();
  12863. this.context.strict = previousStrict;
  12864. return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
  12865. };
  12866. // https://tc39.github.io/ecma262/#sec-scripts
  12867. // https://tc39.github.io/ecma262/#sec-modules
  12868. Parser.prototype.parseModule = function () {
  12869. this.context.strict = true;
  12870. this.context.isModule = true;
  12871. this.scanner.isModule = true;
  12872. var node = this.createNode();
  12873. var body = this.parseDirectivePrologues();
  12874. while (this.lookahead.type !== 2 /* EOF */) {
  12875. body.push(this.parseStatementListItem());
  12876. }
  12877. return this.finalize(node, new Node.Module(body));
  12878. };
  12879. Parser.prototype.parseScript = function () {
  12880. var node = this.createNode();
  12881. var body = this.parseDirectivePrologues();
  12882. while (this.lookahead.type !== 2 /* EOF */) {
  12883. body.push(this.parseStatementListItem());
  12884. }
  12885. return this.finalize(node, new Node.Script(body));
  12886. };
  12887. // https://tc39.github.io/ecma262/#sec-imports
  12888. Parser.prototype.parseModuleSpecifier = function () {
  12889. var node = this.createNode();
  12890. if (this.lookahead.type !== 8 /* StringLiteral */) {
  12891. this.throwError(messages_1.Messages.InvalidModuleSpecifier);
  12892. }
  12893. var token = this.nextToken();
  12894. var raw = this.getTokenRaw(token);
  12895. return this.finalize(node, new Node.Literal(token.value, raw));
  12896. };
  12897. // import {<foo as bar>} ...;
  12898. Parser.prototype.parseImportSpecifier = function () {
  12899. var node = this.createNode();
  12900. var imported;
  12901. var local;
  12902. if (this.lookahead.type === 3 /* Identifier */) {
  12903. imported = this.parseVariableIdentifier();
  12904. local = imported;
  12905. if (this.matchContextualKeyword('as')) {
  12906. this.nextToken();
  12907. local = this.parseVariableIdentifier();
  12908. }
  12909. }
  12910. else {
  12911. imported = this.parseIdentifierName();
  12912. local = imported;
  12913. if (this.matchContextualKeyword('as')) {
  12914. this.nextToken();
  12915. local = this.parseVariableIdentifier();
  12916. }
  12917. else {
  12918. this.throwUnexpectedToken(this.nextToken());
  12919. }
  12920. }
  12921. return this.finalize(node, new Node.ImportSpecifier(local, imported));
  12922. };
  12923. // {foo, bar as bas}
  12924. Parser.prototype.parseNamedImports = function () {
  12925. this.expect('{');
  12926. var specifiers = [];
  12927. while (!this.match('}')) {
  12928. specifiers.push(this.parseImportSpecifier());
  12929. if (!this.match('}')) {
  12930. this.expect(',');
  12931. }
  12932. }
  12933. this.expect('}');
  12934. return specifiers;
  12935. };
  12936. // import <foo> ...;
  12937. Parser.prototype.parseImportDefaultSpecifier = function () {
  12938. var node = this.createNode();
  12939. var local = this.parseIdentifierName();
  12940. return this.finalize(node, new Node.ImportDefaultSpecifier(local));
  12941. };
  12942. // import <* as foo> ...;
  12943. Parser.prototype.parseImportNamespaceSpecifier = function () {
  12944. var node = this.createNode();
  12945. this.expect('*');
  12946. if (!this.matchContextualKeyword('as')) {
  12947. this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
  12948. }
  12949. this.nextToken();
  12950. var local = this.parseIdentifierName();
  12951. return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
  12952. };
  12953. Parser.prototype.parseImportDeclaration = function () {
  12954. if (this.context.inFunctionBody) {
  12955. this.throwError(messages_1.Messages.IllegalImportDeclaration);
  12956. }
  12957. var node = this.createNode();
  12958. this.expectKeyword('import');
  12959. var src;
  12960. var specifiers = [];
  12961. if (this.lookahead.type === 8 /* StringLiteral */) {
  12962. // import 'foo';
  12963. src = this.parseModuleSpecifier();
  12964. }
  12965. else {
  12966. if (this.match('{')) {
  12967. // import {bar}
  12968. specifiers = specifiers.concat(this.parseNamedImports());
  12969. }
  12970. else if (this.match('*')) {
  12971. // import * as foo
  12972. specifiers.push(this.parseImportNamespaceSpecifier());
  12973. }
  12974. else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
  12975. // import foo
  12976. specifiers.push(this.parseImportDefaultSpecifier());
  12977. if (this.match(',')) {
  12978. this.nextToken();
  12979. if (this.match('*')) {
  12980. // import foo, * as foo
  12981. specifiers.push(this.parseImportNamespaceSpecifier());
  12982. }
  12983. else if (this.match('{')) {
  12984. // import foo, {bar}
  12985. specifiers = specifiers.concat(this.parseNamedImports());
  12986. }
  12987. else {
  12988. this.throwUnexpectedToken(this.lookahead);
  12989. }
  12990. }
  12991. }
  12992. else {
  12993. this.throwUnexpectedToken(this.nextToken());
  12994. }
  12995. if (!this.matchContextualKeyword('from')) {
  12996. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  12997. this.throwError(message, this.lookahead.value);
  12998. }
  12999. this.nextToken();
  13000. src = this.parseModuleSpecifier();
  13001. }
  13002. this.consumeSemicolon();
  13003. return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
  13004. };
  13005. // https://tc39.github.io/ecma262/#sec-exports
  13006. Parser.prototype.parseExportSpecifier = function () {
  13007. var node = this.createNode();
  13008. var local = this.parseIdentifierName();
  13009. var exported = local;
  13010. if (this.matchContextualKeyword('as')) {
  13011. this.nextToken();
  13012. exported = this.parseIdentifierName();
  13013. }
  13014. return this.finalize(node, new Node.ExportSpecifier(local, exported));
  13015. };
  13016. Parser.prototype.parseExportDeclaration = function () {
  13017. if (this.context.inFunctionBody) {
  13018. this.throwError(messages_1.Messages.IllegalExportDeclaration);
  13019. }
  13020. var node = this.createNode();
  13021. this.expectKeyword('export');
  13022. var exportDeclaration;
  13023. if (this.matchKeyword('default')) {
  13024. // export default ...
  13025. this.nextToken();
  13026. if (this.matchKeyword('function')) {
  13027. // export default function foo () {}
  13028. // export default function () {}
  13029. var declaration = this.parseFunctionDeclaration(true);
  13030. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  13031. }
  13032. else if (this.matchKeyword('class')) {
  13033. // export default class foo {}
  13034. var declaration = this.parseClassDeclaration(true);
  13035. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  13036. }
  13037. else if (this.matchContextualKeyword('async')) {
  13038. // export default async function f () {}
  13039. // export default async function () {}
  13040. // export default async x => x
  13041. var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
  13042. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  13043. }
  13044. else {
  13045. if (this.matchContextualKeyword('from')) {
  13046. this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
  13047. }
  13048. // export default {};
  13049. // export default [];
  13050. // export default (1 + 2);
  13051. var declaration = this.match('{') ? this.parseObjectInitializer() :
  13052. this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
  13053. this.consumeSemicolon();
  13054. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  13055. }
  13056. }
  13057. else if (this.match('*')) {
  13058. // export * from 'foo';
  13059. this.nextToken();
  13060. if (!this.matchContextualKeyword('from')) {
  13061. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  13062. this.throwError(message, this.lookahead.value);
  13063. }
  13064. this.nextToken();
  13065. var src = this.parseModuleSpecifier();
  13066. this.consumeSemicolon();
  13067. exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
  13068. }
  13069. else if (this.lookahead.type === 4 /* Keyword */) {
  13070. // export var f = 1;
  13071. var declaration = void 0;
  13072. switch (this.lookahead.value) {
  13073. case 'let':
  13074. case 'const':
  13075. declaration = this.parseLexicalDeclaration({ inFor: false });
  13076. break;
  13077. case 'var':
  13078. case 'class':
  13079. case 'function':
  13080. declaration = this.parseStatementListItem();
  13081. break;
  13082. default:
  13083. this.throwUnexpectedToken(this.lookahead);
  13084. }
  13085. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
  13086. }
  13087. else if (this.matchAsyncFunction()) {
  13088. var declaration = this.parseFunctionDeclaration();
  13089. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
  13090. }
  13091. else {
  13092. var specifiers = [];
  13093. var source = null;
  13094. var isExportFromIdentifier = false;
  13095. this.expect('{');
  13096. while (!this.match('}')) {
  13097. isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
  13098. specifiers.push(this.parseExportSpecifier());
  13099. if (!this.match('}')) {
  13100. this.expect(',');
  13101. }
  13102. }
  13103. this.expect('}');
  13104. if (this.matchContextualKeyword('from')) {
  13105. // export {default} from 'foo';
  13106. // export {foo} from 'foo';
  13107. this.nextToken();
  13108. source = this.parseModuleSpecifier();
  13109. this.consumeSemicolon();
  13110. }
  13111. else if (isExportFromIdentifier) {
  13112. // export {default}; // missing fromClause
  13113. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  13114. this.throwError(message, this.lookahead.value);
  13115. }
  13116. else {
  13117. // export {foo};
  13118. this.consumeSemicolon();
  13119. }
  13120. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
  13121. }
  13122. return exportDeclaration;
  13123. };
  13124. return Parser;
  13125. }());
  13126. exports.Parser = Parser;
  13127. /***/ },
  13128. /* 9 */
  13129. /***/ function(module, exports) {
  13130. // Ensure the condition is true, otherwise throw an error.
  13131. // This is only to have a better contract semantic, i.e. another safety net
  13132. // to catch a logic error. The condition shall be fulfilled in normal case.
  13133. // Do NOT use this to enforce a certain condition on any user input.
  13134. Object.defineProperty(exports, "__esModule", { value: true });
  13135. function assert(condition, message) {
  13136. /* istanbul ignore if */
  13137. if (!condition) {
  13138. throw new Error('ASSERT: ' + message);
  13139. }
  13140. }
  13141. exports.assert = assert;
  13142. /***/ },
  13143. /* 10 */
  13144. /***/ function(module, exports) {
  13145. /* tslint:disable:max-classes-per-file */
  13146. Object.defineProperty(exports, "__esModule", { value: true });
  13147. var ErrorHandler = (function () {
  13148. function ErrorHandler() {
  13149. this.errors = [];
  13150. this.tolerant = false;
  13151. }
  13152. ErrorHandler.prototype.recordError = function (error) {
  13153. this.errors.push(error);
  13154. };
  13155. ErrorHandler.prototype.tolerate = function (error) {
  13156. if (this.tolerant) {
  13157. this.recordError(error);
  13158. }
  13159. else {
  13160. throw error;
  13161. }
  13162. };
  13163. ErrorHandler.prototype.constructError = function (msg, column) {
  13164. var error = new Error(msg);
  13165. try {
  13166. throw error;
  13167. }
  13168. catch (base) {
  13169. /* istanbul ignore else */
  13170. if (Object.create && Object.defineProperty) {
  13171. error = Object.create(base);
  13172. Object.defineProperty(error, 'column', { value: column });
  13173. }
  13174. }
  13175. /* istanbul ignore next */
  13176. return error;
  13177. };
  13178. ErrorHandler.prototype.createError = function (index, line, col, description) {
  13179. var msg = 'Line ' + line + ': ' + description;
  13180. var error = this.constructError(msg, col);
  13181. error.index = index;
  13182. error.lineNumber = line;
  13183. error.description = description;
  13184. return error;
  13185. };
  13186. ErrorHandler.prototype.throwError = function (index, line, col, description) {
  13187. throw this.createError(index, line, col, description);
  13188. };
  13189. ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
  13190. var error = this.createError(index, line, col, description);
  13191. if (this.tolerant) {
  13192. this.recordError(error);
  13193. }
  13194. else {
  13195. throw error;
  13196. }
  13197. };
  13198. return ErrorHandler;
  13199. }());
  13200. exports.ErrorHandler = ErrorHandler;
  13201. /***/ },
  13202. /* 11 */
  13203. /***/ function(module, exports) {
  13204. Object.defineProperty(exports, "__esModule", { value: true });
  13205. // Error messages should be identical to V8.
  13206. exports.Messages = {
  13207. BadGetterArity: 'Getter must not have any formal parameters',
  13208. BadSetterArity: 'Setter must have exactly one formal parameter',
  13209. BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
  13210. ConstructorIsAsync: 'Class constructor may not be an async method',
  13211. ConstructorSpecialMethod: 'Class constructor may not be an accessor',
  13212. DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
  13213. DefaultRestParameter: 'Unexpected token =',
  13214. DuplicateBinding: 'Duplicate binding %0',
  13215. DuplicateConstructor: 'A class may only have one constructor',
  13216. DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
  13217. ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
  13218. GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
  13219. IllegalBreak: 'Illegal break statement',
  13220. IllegalContinue: 'Illegal continue statement',
  13221. IllegalExportDeclaration: 'Unexpected token',
  13222. IllegalImportDeclaration: 'Unexpected token',
  13223. IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
  13224. IllegalReturn: 'Illegal return statement',
  13225. InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
  13226. InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
  13227. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  13228. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  13229. InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
  13230. InvalidModuleSpecifier: 'Unexpected token',
  13231. InvalidRegExp: 'Invalid regular expression',
  13232. LetInLexicalBinding: 'let is disallowed as a lexically bound name',
  13233. MissingFromClause: 'Unexpected token',
  13234. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  13235. NewlineAfterThrow: 'Illegal newline after throw',
  13236. NoAsAfterImportNamespace: 'Unexpected token',
  13237. NoCatchOrFinally: 'Missing catch or finally after try',
  13238. ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
  13239. Redeclaration: '%0 \'%1\' has already been declared',
  13240. StaticPrototype: 'Classes may not have static property named prototype',
  13241. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  13242. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  13243. StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
  13244. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  13245. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  13246. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  13247. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  13248. StrictModeWith: 'Strict mode code may not include a with statement',
  13249. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  13250. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  13251. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  13252. StrictReservedWord: 'Use of future reserved word in strict mode',
  13253. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  13254. TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
  13255. UnexpectedEOS: 'Unexpected end of input',
  13256. UnexpectedIdentifier: 'Unexpected identifier',
  13257. UnexpectedNumber: 'Unexpected number',
  13258. UnexpectedReserved: 'Unexpected reserved word',
  13259. UnexpectedString: 'Unexpected string',
  13260. UnexpectedTemplate: 'Unexpected quasi %0',
  13261. UnexpectedToken: 'Unexpected token %0',
  13262. UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
  13263. UnknownLabel: 'Undefined label \'%0\'',
  13264. UnterminatedRegExp: 'Invalid regular expression: missing /'
  13265. };
  13266. /***/ },
  13267. /* 12 */
  13268. /***/ function(module, exports, __webpack_require__) {
  13269. Object.defineProperty(exports, "__esModule", { value: true });
  13270. var assert_1 = __webpack_require__(9);
  13271. var character_1 = __webpack_require__(4);
  13272. var messages_1 = __webpack_require__(11);
  13273. function hexValue(ch) {
  13274. return '0123456789abcdef'.indexOf(ch.toLowerCase());
  13275. }
  13276. function octalValue(ch) {
  13277. return '01234567'.indexOf(ch);
  13278. }
  13279. var Scanner = (function () {
  13280. function Scanner(code, handler) {
  13281. this.source = code;
  13282. this.errorHandler = handler;
  13283. this.trackComment = false;
  13284. this.isModule = false;
  13285. this.length = code.length;
  13286. this.index = 0;
  13287. this.lineNumber = (code.length > 0) ? 1 : 0;
  13288. this.lineStart = 0;
  13289. this.curlyStack = [];
  13290. }
  13291. Scanner.prototype.saveState = function () {
  13292. return {
  13293. index: this.index,
  13294. lineNumber: this.lineNumber,
  13295. lineStart: this.lineStart
  13296. };
  13297. };
  13298. Scanner.prototype.restoreState = function (state) {
  13299. this.index = state.index;
  13300. this.lineNumber = state.lineNumber;
  13301. this.lineStart = state.lineStart;
  13302. };
  13303. Scanner.prototype.eof = function () {
  13304. return this.index >= this.length;
  13305. };
  13306. Scanner.prototype.throwUnexpectedToken = function (message) {
  13307. if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
  13308. return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
  13309. };
  13310. Scanner.prototype.tolerateUnexpectedToken = function (message) {
  13311. if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
  13312. this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
  13313. };
  13314. // https://tc39.github.io/ecma262/#sec-comments
  13315. Scanner.prototype.skipSingleLineComment = function (offset) {
  13316. var comments = [];
  13317. var start, loc;
  13318. if (this.trackComment) {
  13319. comments = [];
  13320. start = this.index - offset;
  13321. loc = {
  13322. start: {
  13323. line: this.lineNumber,
  13324. column: this.index - this.lineStart - offset
  13325. },
  13326. end: {}
  13327. };
  13328. }
  13329. while (!this.eof()) {
  13330. var ch = this.source.charCodeAt(this.index);
  13331. ++this.index;
  13332. if (character_1.Character.isLineTerminator(ch)) {
  13333. if (this.trackComment) {
  13334. loc.end = {
  13335. line: this.lineNumber,
  13336. column: this.index - this.lineStart - 1
  13337. };
  13338. var entry = {
  13339. multiLine: false,
  13340. slice: [start + offset, this.index - 1],
  13341. range: [start, this.index - 1],
  13342. loc: loc
  13343. };
  13344. comments.push(entry);
  13345. }
  13346. if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
  13347. ++this.index;
  13348. }
  13349. ++this.lineNumber;
  13350. this.lineStart = this.index;
  13351. return comments;
  13352. }
  13353. }
  13354. if (this.trackComment) {
  13355. loc.end = {
  13356. line: this.lineNumber,
  13357. column: this.index - this.lineStart
  13358. };
  13359. var entry = {
  13360. multiLine: false,
  13361. slice: [start + offset, this.index],
  13362. range: [start, this.index],
  13363. loc: loc
  13364. };
  13365. comments.push(entry);
  13366. }
  13367. return comments;
  13368. };
  13369. Scanner.prototype.skipMultiLineComment = function () {
  13370. var comments = [];
  13371. var start, loc;
  13372. if (this.trackComment) {
  13373. comments = [];
  13374. start = this.index - 2;
  13375. loc = {
  13376. start: {
  13377. line: this.lineNumber,
  13378. column: this.index - this.lineStart - 2
  13379. },
  13380. end: {}
  13381. };
  13382. }
  13383. while (!this.eof()) {
  13384. var ch = this.source.charCodeAt(this.index);
  13385. if (character_1.Character.isLineTerminator(ch)) {
  13386. if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
  13387. ++this.index;
  13388. }
  13389. ++this.lineNumber;
  13390. ++this.index;
  13391. this.lineStart = this.index;
  13392. }
  13393. else if (ch === 0x2A) {
  13394. // Block comment ends with '*/'.
  13395. if (this.source.charCodeAt(this.index + 1) === 0x2F) {
  13396. this.index += 2;
  13397. if (this.trackComment) {
  13398. loc.end = {
  13399. line: this.lineNumber,
  13400. column: this.index - this.lineStart
  13401. };
  13402. var entry = {
  13403. multiLine: true,
  13404. slice: [start + 2, this.index - 2],
  13405. range: [start, this.index],
  13406. loc: loc
  13407. };
  13408. comments.push(entry);
  13409. }
  13410. return comments;
  13411. }
  13412. ++this.index;
  13413. }
  13414. else {
  13415. ++this.index;
  13416. }
  13417. }
  13418. // Ran off the end of the file - the whole thing is a comment
  13419. if (this.trackComment) {
  13420. loc.end = {
  13421. line: this.lineNumber,
  13422. column: this.index - this.lineStart
  13423. };
  13424. var entry = {
  13425. multiLine: true,
  13426. slice: [start + 2, this.index],
  13427. range: [start, this.index],
  13428. loc: loc
  13429. };
  13430. comments.push(entry);
  13431. }
  13432. this.tolerateUnexpectedToken();
  13433. return comments;
  13434. };
  13435. Scanner.prototype.scanComments = function () {
  13436. var comments;
  13437. if (this.trackComment) {
  13438. comments = [];
  13439. }
  13440. var start = (this.index === 0);
  13441. while (!this.eof()) {
  13442. var ch = this.source.charCodeAt(this.index);
  13443. if (character_1.Character.isWhiteSpace(ch)) {
  13444. ++this.index;
  13445. }
  13446. else if (character_1.Character.isLineTerminator(ch)) {
  13447. ++this.index;
  13448. if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
  13449. ++this.index;
  13450. }
  13451. ++this.lineNumber;
  13452. this.lineStart = this.index;
  13453. start = true;
  13454. }
  13455. else if (ch === 0x2F) {
  13456. ch = this.source.charCodeAt(this.index + 1);
  13457. if (ch === 0x2F) {
  13458. this.index += 2;
  13459. var comment = this.skipSingleLineComment(2);
  13460. if (this.trackComment) {
  13461. comments = comments.concat(comment);
  13462. }
  13463. start = true;
  13464. }
  13465. else if (ch === 0x2A) {
  13466. this.index += 2;
  13467. var comment = this.skipMultiLineComment();
  13468. if (this.trackComment) {
  13469. comments = comments.concat(comment);
  13470. }
  13471. }
  13472. else {
  13473. break;
  13474. }
  13475. }
  13476. else if (start && ch === 0x2D) {
  13477. // U+003E is '>'
  13478. if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) {
  13479. // '-->' is a single-line comment
  13480. this.index += 3;
  13481. var comment = this.skipSingleLineComment(3);
  13482. if (this.trackComment) {
  13483. comments = comments.concat(comment);
  13484. }
  13485. }
  13486. else {
  13487. break;
  13488. }
  13489. }
  13490. else if (ch === 0x3C && !this.isModule) {
  13491. if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
  13492. this.index += 4; // `<!--`
  13493. var comment = this.skipSingleLineComment(4);
  13494. if (this.trackComment) {
  13495. comments = comments.concat(comment);
  13496. }
  13497. }
  13498. else {
  13499. break;
  13500. }
  13501. }
  13502. else {
  13503. break;
  13504. }
  13505. }
  13506. return comments;
  13507. };
  13508. // https://tc39.github.io/ecma262/#sec-future-reserved-words
  13509. Scanner.prototype.isFutureReservedWord = function (id) {
  13510. switch (id) {
  13511. case 'enum':
  13512. case 'export':
  13513. case 'import':
  13514. case 'super':
  13515. return true;
  13516. default:
  13517. return false;
  13518. }
  13519. };
  13520. Scanner.prototype.isStrictModeReservedWord = function (id) {
  13521. switch (id) {
  13522. case 'implements':
  13523. case 'interface':
  13524. case 'package':
  13525. case 'private':
  13526. case 'protected':
  13527. case 'public':
  13528. case 'static':
  13529. case 'yield':
  13530. case 'let':
  13531. return true;
  13532. default:
  13533. return false;
  13534. }
  13535. };
  13536. Scanner.prototype.isRestrictedWord = function (id) {
  13537. return id === 'eval' || id === 'arguments';
  13538. };
  13539. // https://tc39.github.io/ecma262/#sec-keywords
  13540. Scanner.prototype.isKeyword = function (id) {
  13541. switch (id.length) {
  13542. case 2:
  13543. return (id === 'if') || (id === 'in') || (id === 'do');
  13544. case 3:
  13545. return (id === 'var') || (id === 'for') || (id === 'new') ||
  13546. (id === 'try') || (id === 'let');
  13547. case 4:
  13548. return (id === 'this') || (id === 'else') || (id === 'case') ||
  13549. (id === 'void') || (id === 'with') || (id === 'enum');
  13550. case 5:
  13551. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  13552. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  13553. (id === 'class') || (id === 'super');
  13554. case 6:
  13555. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  13556. (id === 'switch') || (id === 'export') || (id === 'import');
  13557. case 7:
  13558. return (id === 'default') || (id === 'finally') || (id === 'extends');
  13559. case 8:
  13560. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  13561. case 10:
  13562. return (id === 'instanceof');
  13563. default:
  13564. return false;
  13565. }
  13566. };
  13567. Scanner.prototype.codePointAt = function (i) {
  13568. var cp = this.source.charCodeAt(i);
  13569. if (cp >= 0xD800 && cp <= 0xDBFF) {
  13570. var second = this.source.charCodeAt(i + 1);
  13571. if (second >= 0xDC00 && second <= 0xDFFF) {
  13572. var first = cp;
  13573. cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  13574. }
  13575. }
  13576. return cp;
  13577. };
  13578. Scanner.prototype.scanHexEscape = function (prefix) {
  13579. var len = (prefix === 'u') ? 4 : 2;
  13580. var code = 0;
  13581. for (var i = 0; i < len; ++i) {
  13582. if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
  13583. code = code * 16 + hexValue(this.source[this.index++]);
  13584. }
  13585. else {
  13586. return null;
  13587. }
  13588. }
  13589. return String.fromCharCode(code);
  13590. };
  13591. Scanner.prototype.scanUnicodeCodePointEscape = function () {
  13592. var ch = this.source[this.index];
  13593. var code = 0;
  13594. // At least, one hex digit is required.
  13595. if (ch === '}') {
  13596. this.throwUnexpectedToken();
  13597. }
  13598. while (!this.eof()) {
  13599. ch = this.source[this.index++];
  13600. if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
  13601. break;
  13602. }
  13603. code = code * 16 + hexValue(ch);
  13604. }
  13605. if (code > 0x10FFFF || ch !== '}') {
  13606. this.throwUnexpectedToken();
  13607. }
  13608. return character_1.Character.fromCodePoint(code);
  13609. };
  13610. Scanner.prototype.getIdentifier = function () {
  13611. var start = this.index++;
  13612. while (!this.eof()) {
  13613. var ch = this.source.charCodeAt(this.index);
  13614. if (ch === 0x5C) {
  13615. // Blackslash (U+005C) marks Unicode escape sequence.
  13616. this.index = start;
  13617. return this.getComplexIdentifier();
  13618. }
  13619. else if (ch >= 0xD800 && ch < 0xDFFF) {
  13620. // Need to handle surrogate pairs.
  13621. this.index = start;
  13622. return this.getComplexIdentifier();
  13623. }
  13624. if (character_1.Character.isIdentifierPart(ch)) {
  13625. ++this.index;
  13626. }
  13627. else {
  13628. break;
  13629. }
  13630. }
  13631. return this.source.slice(start, this.index);
  13632. };
  13633. Scanner.prototype.getComplexIdentifier = function () {
  13634. var cp = this.codePointAt(this.index);
  13635. var id = character_1.Character.fromCodePoint(cp);
  13636. this.index += id.length;
  13637. // '\u' (U+005C, U+0075) denotes an escaped character.
  13638. var ch;
  13639. if (cp === 0x5C) {
  13640. if (this.source.charCodeAt(this.index) !== 0x75) {
  13641. this.throwUnexpectedToken();
  13642. }
  13643. ++this.index;
  13644. if (this.source[this.index] === '{') {
  13645. ++this.index;
  13646. ch = this.scanUnicodeCodePointEscape();
  13647. }
  13648. else {
  13649. ch = this.scanHexEscape('u');
  13650. if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
  13651. this.throwUnexpectedToken();
  13652. }
  13653. }
  13654. id = ch;
  13655. }
  13656. while (!this.eof()) {
  13657. cp = this.codePointAt(this.index);
  13658. if (!character_1.Character.isIdentifierPart(cp)) {
  13659. break;
  13660. }
  13661. ch = character_1.Character.fromCodePoint(cp);
  13662. id += ch;
  13663. this.index += ch.length;
  13664. // '\u' (U+005C, U+0075) denotes an escaped character.
  13665. if (cp === 0x5C) {
  13666. id = id.substr(0, id.length - 1);
  13667. if (this.source.charCodeAt(this.index) !== 0x75) {
  13668. this.throwUnexpectedToken();
  13669. }
  13670. ++this.index;
  13671. if (this.source[this.index] === '{') {
  13672. ++this.index;
  13673. ch = this.scanUnicodeCodePointEscape();
  13674. }
  13675. else {
  13676. ch = this.scanHexEscape('u');
  13677. if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
  13678. this.throwUnexpectedToken();
  13679. }
  13680. }
  13681. id += ch;
  13682. }
  13683. }
  13684. return id;
  13685. };
  13686. Scanner.prototype.octalToDecimal = function (ch) {
  13687. // \0 is not octal escape sequence
  13688. var octal = (ch !== '0');
  13689. var code = octalValue(ch);
  13690. if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  13691. octal = true;
  13692. code = code * 8 + octalValue(this.source[this.index++]);
  13693. // 3 digits are only allowed when string starts
  13694. // with 0, 1, 2, 3
  13695. if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  13696. code = code * 8 + octalValue(this.source[this.index++]);
  13697. }
  13698. }
  13699. return {
  13700. code: code,
  13701. octal: octal
  13702. };
  13703. };
  13704. // https://tc39.github.io/ecma262/#sec-names-and-keywords
  13705. Scanner.prototype.scanIdentifier = function () {
  13706. var type;
  13707. var start = this.index;
  13708. // Backslash (U+005C) starts an escaped character.
  13709. var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier();
  13710. // There is no keyword or literal with only one character.
  13711. // Thus, it must be an identifier.
  13712. if (id.length === 1) {
  13713. type = 3 /* Identifier */;
  13714. }
  13715. else if (this.isKeyword(id)) {
  13716. type = 4 /* Keyword */;
  13717. }
  13718. else if (id === 'null') {
  13719. type = 5 /* NullLiteral */;
  13720. }
  13721. else if (id === 'true' || id === 'false') {
  13722. type = 1 /* BooleanLiteral */;
  13723. }
  13724. else {
  13725. type = 3 /* Identifier */;
  13726. }
  13727. if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) {
  13728. var restore = this.index;
  13729. this.index = start;
  13730. this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
  13731. this.index = restore;
  13732. }
  13733. return {
  13734. type: type,
  13735. value: id,
  13736. lineNumber: this.lineNumber,
  13737. lineStart: this.lineStart,
  13738. start: start,
  13739. end: this.index
  13740. };
  13741. };
  13742. // https://tc39.github.io/ecma262/#sec-punctuators
  13743. Scanner.prototype.scanPunctuator = function () {
  13744. var start = this.index;
  13745. // Check for most common single-character punctuators.
  13746. var str = this.source[this.index];
  13747. switch (str) {
  13748. case '(':
  13749. case '{':
  13750. if (str === '{') {
  13751. this.curlyStack.push('{');
  13752. }
  13753. ++this.index;
  13754. break;
  13755. case '.':
  13756. ++this.index;
  13757. if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
  13758. // Spread operator: ...
  13759. this.index += 2;
  13760. str = '...';
  13761. }
  13762. break;
  13763. case '}':
  13764. ++this.index;
  13765. this.curlyStack.pop();
  13766. break;
  13767. case ')':
  13768. case ';':
  13769. case ',':
  13770. case '[':
  13771. case ']':
  13772. case ':':
  13773. case '?':
  13774. case '~':
  13775. ++this.index;
  13776. break;
  13777. default:
  13778. // 4-character punctuator.
  13779. str = this.source.substr(this.index, 4);
  13780. if (str === '>>>=') {
  13781. this.index += 4;
  13782. }
  13783. else {
  13784. // 3-character punctuators.
  13785. str = str.substr(0, 3);
  13786. if (str === '===' || str === '!==' || str === '>>>' ||
  13787. str === '<<=' || str === '>>=' || str === '**=') {
  13788. this.index += 3;
  13789. }
  13790. else {
  13791. // 2-character punctuators.
  13792. str = str.substr(0, 2);
  13793. if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
  13794. str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
  13795. str === '++' || str === '--' || str === '<<' || str === '>>' ||
  13796. str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
  13797. str === '<=' || str === '>=' || str === '=>' || str === '**') {
  13798. this.index += 2;
  13799. }
  13800. else {
  13801. // 1-character punctuators.
  13802. str = this.source[this.index];
  13803. if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
  13804. ++this.index;
  13805. }
  13806. }
  13807. }
  13808. }
  13809. }
  13810. if (this.index === start) {
  13811. this.throwUnexpectedToken();
  13812. }
  13813. return {
  13814. type: 7 /* Punctuator */,
  13815. value: str,
  13816. lineNumber: this.lineNumber,
  13817. lineStart: this.lineStart,
  13818. start: start,
  13819. end: this.index
  13820. };
  13821. };
  13822. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  13823. Scanner.prototype.scanHexLiteral = function (start) {
  13824. var num = '';
  13825. while (!this.eof()) {
  13826. if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
  13827. break;
  13828. }
  13829. num += this.source[this.index++];
  13830. }
  13831. if (num.length === 0) {
  13832. this.throwUnexpectedToken();
  13833. }
  13834. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
  13835. this.throwUnexpectedToken();
  13836. }
  13837. return {
  13838. type: 6 /* NumericLiteral */,
  13839. value: parseInt('0x' + num, 16),
  13840. lineNumber: this.lineNumber,
  13841. lineStart: this.lineStart,
  13842. start: start,
  13843. end: this.index
  13844. };
  13845. };
  13846. Scanner.prototype.scanBinaryLiteral = function (start) {
  13847. var num = '';
  13848. var ch;
  13849. while (!this.eof()) {
  13850. ch = this.source[this.index];
  13851. if (ch !== '0' && ch !== '1') {
  13852. break;
  13853. }
  13854. num += this.source[this.index++];
  13855. }
  13856. if (num.length === 0) {
  13857. // only 0b or 0B
  13858. this.throwUnexpectedToken();
  13859. }
  13860. if (!this.eof()) {
  13861. ch = this.source.charCodeAt(this.index);
  13862. /* istanbul ignore else */
  13863. if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
  13864. this.throwUnexpectedToken();
  13865. }
  13866. }
  13867. return {
  13868. type: 6 /* NumericLiteral */,
  13869. value: parseInt(num, 2),
  13870. lineNumber: this.lineNumber,
  13871. lineStart: this.lineStart,
  13872. start: start,
  13873. end: this.index
  13874. };
  13875. };
  13876. Scanner.prototype.scanOctalLiteral = function (prefix, start) {
  13877. var num = '';
  13878. var octal = false;
  13879. if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
  13880. octal = true;
  13881. num = '0' + this.source[this.index++];
  13882. }
  13883. else {
  13884. ++this.index;
  13885. }
  13886. while (!this.eof()) {
  13887. if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  13888. break;
  13889. }
  13890. num += this.source[this.index++];
  13891. }
  13892. if (!octal && num.length === 0) {
  13893. // only 0o or 0O
  13894. this.throwUnexpectedToken();
  13895. }
  13896. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  13897. this.throwUnexpectedToken();
  13898. }
  13899. return {
  13900. type: 6 /* NumericLiteral */,
  13901. value: parseInt(num, 8),
  13902. octal: octal,
  13903. lineNumber: this.lineNumber,
  13904. lineStart: this.lineStart,
  13905. start: start,
  13906. end: this.index
  13907. };
  13908. };
  13909. Scanner.prototype.isImplicitOctalLiteral = function () {
  13910. // Implicit octal, unless there is a non-octal digit.
  13911. // (Annex B.1.1 on Numeric Literals)
  13912. for (var i = this.index + 1; i < this.length; ++i) {
  13913. var ch = this.source[i];
  13914. if (ch === '8' || ch === '9') {
  13915. return false;
  13916. }
  13917. if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  13918. return true;
  13919. }
  13920. }
  13921. return true;
  13922. };
  13923. Scanner.prototype.scanNumericLiteral = function () {
  13924. var start = this.index;
  13925. var ch = this.source[start];
  13926. assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point');
  13927. var num = '';
  13928. if (ch !== '.') {
  13929. num = this.source[this.index++];
  13930. ch = this.source[this.index];
  13931. // Hex number starts with '0x'.
  13932. // Octal number starts with '0'.
  13933. // Octal number in ES6 starts with '0o'.
  13934. // Binary number in ES6 starts with '0b'.
  13935. if (num === '0') {
  13936. if (ch === 'x' || ch === 'X') {
  13937. ++this.index;
  13938. return this.scanHexLiteral(start);
  13939. }
  13940. if (ch === 'b' || ch === 'B') {
  13941. ++this.index;
  13942. return this.scanBinaryLiteral(start);
  13943. }
  13944. if (ch === 'o' || ch === 'O') {
  13945. return this.scanOctalLiteral(ch, start);
  13946. }
  13947. if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  13948. if (this.isImplicitOctalLiteral()) {
  13949. return this.scanOctalLiteral(ch, start);
  13950. }
  13951. }
  13952. }
  13953. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  13954. num += this.source[this.index++];
  13955. }
  13956. ch = this.source[this.index];
  13957. }
  13958. if (ch === '.') {
  13959. num += this.source[this.index++];
  13960. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  13961. num += this.source[this.index++];
  13962. }
  13963. ch = this.source[this.index];
  13964. }
  13965. if (ch === 'e' || ch === 'E') {
  13966. num += this.source[this.index++];
  13967. ch = this.source[this.index];
  13968. if (ch === '+' || ch === '-') {
  13969. num += this.source[this.index++];
  13970. }
  13971. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  13972. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  13973. num += this.source[this.index++];
  13974. }
  13975. }
  13976. else {
  13977. this.throwUnexpectedToken();
  13978. }
  13979. }
  13980. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
  13981. this.throwUnexpectedToken();
  13982. }
  13983. return {
  13984. type: 6 /* NumericLiteral */,
  13985. value: parseFloat(num),
  13986. lineNumber: this.lineNumber,
  13987. lineStart: this.lineStart,
  13988. start: start,
  13989. end: this.index
  13990. };
  13991. };
  13992. // https://tc39.github.io/ecma262/#sec-literals-string-literals
  13993. Scanner.prototype.scanStringLiteral = function () {
  13994. var start = this.index;
  13995. var quote = this.source[start];
  13996. assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote');
  13997. ++this.index;
  13998. var octal = false;
  13999. var str = '';
  14000. while (!this.eof()) {
  14001. var ch = this.source[this.index++];
  14002. if (ch === quote) {
  14003. quote = '';
  14004. break;
  14005. }
  14006. else if (ch === '\\') {
  14007. ch = this.source[this.index++];
  14008. if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14009. switch (ch) {
  14010. case 'u':
  14011. if (this.source[this.index] === '{') {
  14012. ++this.index;
  14013. str += this.scanUnicodeCodePointEscape();
  14014. }
  14015. else {
  14016. var unescaped_1 = this.scanHexEscape(ch);
  14017. if (unescaped_1 === null) {
  14018. this.throwUnexpectedToken();
  14019. }
  14020. str += unescaped_1;
  14021. }
  14022. break;
  14023. case 'x':
  14024. var unescaped = this.scanHexEscape(ch);
  14025. if (unescaped === null) {
  14026. this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
  14027. }
  14028. str += unescaped;
  14029. break;
  14030. case 'n':
  14031. str += '\n';
  14032. break;
  14033. case 'r':
  14034. str += '\r';
  14035. break;
  14036. case 't':
  14037. str += '\t';
  14038. break;
  14039. case 'b':
  14040. str += '\b';
  14041. break;
  14042. case 'f':
  14043. str += '\f';
  14044. break;
  14045. case 'v':
  14046. str += '\x0B';
  14047. break;
  14048. case '8':
  14049. case '9':
  14050. str += ch;
  14051. this.tolerateUnexpectedToken();
  14052. break;
  14053. default:
  14054. if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  14055. var octToDec = this.octalToDecimal(ch);
  14056. octal = octToDec.octal || octal;
  14057. str += String.fromCharCode(octToDec.code);
  14058. }
  14059. else {
  14060. str += ch;
  14061. }
  14062. break;
  14063. }
  14064. }
  14065. else {
  14066. ++this.lineNumber;
  14067. if (ch === '\r' && this.source[this.index] === '\n') {
  14068. ++this.index;
  14069. }
  14070. this.lineStart = this.index;
  14071. }
  14072. }
  14073. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14074. break;
  14075. }
  14076. else {
  14077. str += ch;
  14078. }
  14079. }
  14080. if (quote !== '') {
  14081. this.index = start;
  14082. this.throwUnexpectedToken();
  14083. }
  14084. return {
  14085. type: 8 /* StringLiteral */,
  14086. value: str,
  14087. octal: octal,
  14088. lineNumber: this.lineNumber,
  14089. lineStart: this.lineStart,
  14090. start: start,
  14091. end: this.index
  14092. };
  14093. };
  14094. // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components
  14095. Scanner.prototype.scanTemplate = function () {
  14096. var cooked = '';
  14097. var terminated = false;
  14098. var start = this.index;
  14099. var head = (this.source[start] === '`');
  14100. var tail = false;
  14101. var rawOffset = 2;
  14102. ++this.index;
  14103. while (!this.eof()) {
  14104. var ch = this.source[this.index++];
  14105. if (ch === '`') {
  14106. rawOffset = 1;
  14107. tail = true;
  14108. terminated = true;
  14109. break;
  14110. }
  14111. else if (ch === '$') {
  14112. if (this.source[this.index] === '{') {
  14113. this.curlyStack.push('${');
  14114. ++this.index;
  14115. terminated = true;
  14116. break;
  14117. }
  14118. cooked += ch;
  14119. }
  14120. else if (ch === '\\') {
  14121. ch = this.source[this.index++];
  14122. if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14123. switch (ch) {
  14124. case 'n':
  14125. cooked += '\n';
  14126. break;
  14127. case 'r':
  14128. cooked += '\r';
  14129. break;
  14130. case 't':
  14131. cooked += '\t';
  14132. break;
  14133. case 'u':
  14134. if (this.source[this.index] === '{') {
  14135. ++this.index;
  14136. cooked += this.scanUnicodeCodePointEscape();
  14137. }
  14138. else {
  14139. var restore = this.index;
  14140. var unescaped_2 = this.scanHexEscape(ch);
  14141. if (unescaped_2 !== null) {
  14142. cooked += unescaped_2;
  14143. }
  14144. else {
  14145. this.index = restore;
  14146. cooked += ch;
  14147. }
  14148. }
  14149. break;
  14150. case 'x':
  14151. var unescaped = this.scanHexEscape(ch);
  14152. if (unescaped === null) {
  14153. this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
  14154. }
  14155. cooked += unescaped;
  14156. break;
  14157. case 'b':
  14158. cooked += '\b';
  14159. break;
  14160. case 'f':
  14161. cooked += '\f';
  14162. break;
  14163. case 'v':
  14164. cooked += '\v';
  14165. break;
  14166. default:
  14167. if (ch === '0') {
  14168. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  14169. // Illegal: \01 \02 and so on
  14170. this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
  14171. }
  14172. cooked += '\0';
  14173. }
  14174. else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  14175. // Illegal: \1 \2
  14176. this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
  14177. }
  14178. else {
  14179. cooked += ch;
  14180. }
  14181. break;
  14182. }
  14183. }
  14184. else {
  14185. ++this.lineNumber;
  14186. if (ch === '\r' && this.source[this.index] === '\n') {
  14187. ++this.index;
  14188. }
  14189. this.lineStart = this.index;
  14190. }
  14191. }
  14192. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14193. ++this.lineNumber;
  14194. if (ch === '\r' && this.source[this.index] === '\n') {
  14195. ++this.index;
  14196. }
  14197. this.lineStart = this.index;
  14198. cooked += '\n';
  14199. }
  14200. else {
  14201. cooked += ch;
  14202. }
  14203. }
  14204. if (!terminated) {
  14205. this.throwUnexpectedToken();
  14206. }
  14207. if (!head) {
  14208. this.curlyStack.pop();
  14209. }
  14210. return {
  14211. type: 10 /* Template */,
  14212. value: this.source.slice(start + 1, this.index - rawOffset),
  14213. cooked: cooked,
  14214. head: head,
  14215. tail: tail,
  14216. lineNumber: this.lineNumber,
  14217. lineStart: this.lineStart,
  14218. start: start,
  14219. end: this.index
  14220. };
  14221. };
  14222. // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
  14223. Scanner.prototype.testRegExp = function (pattern, flags) {
  14224. // The BMP character to use as a replacement for astral symbols when
  14225. // translating an ES6 "u"-flagged pattern to an ES5-compatible
  14226. // approximation.
  14227. // Note: replacing with '\uFFFF' enables false positives in unlikely
  14228. // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
  14229. // pattern that would not be detected by this substitution.
  14230. var astralSubstitute = '\uFFFF';
  14231. var tmp = pattern;
  14232. var self = this;
  14233. if (flags.indexOf('u') >= 0) {
  14234. tmp = tmp
  14235. .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
  14236. var codePoint = parseInt($1 || $2, 16);
  14237. if (codePoint > 0x10FFFF) {
  14238. self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
  14239. }
  14240. if (codePoint <= 0xFFFF) {
  14241. return String.fromCharCode(codePoint);
  14242. }
  14243. return astralSubstitute;
  14244. })
  14245. .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
  14246. }
  14247. // First, detect invalid regular expressions.
  14248. try {
  14249. RegExp(tmp);
  14250. }
  14251. catch (e) {
  14252. this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
  14253. }
  14254. // Return a regular expression object for this pattern-flag pair, or
  14255. // `null` in case the current environment doesn't support the flags it
  14256. // uses.
  14257. try {
  14258. return new RegExp(pattern, flags);
  14259. }
  14260. catch (exception) {
  14261. /* istanbul ignore next */
  14262. return null;
  14263. }
  14264. };
  14265. Scanner.prototype.scanRegExpBody = function () {
  14266. var ch = this.source[this.index];
  14267. assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
  14268. var str = this.source[this.index++];
  14269. var classMarker = false;
  14270. var terminated = false;
  14271. while (!this.eof()) {
  14272. ch = this.source[this.index++];
  14273. str += ch;
  14274. if (ch === '\\') {
  14275. ch = this.source[this.index++];
  14276. // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
  14277. if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14278. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  14279. }
  14280. str += ch;
  14281. }
  14282. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  14283. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  14284. }
  14285. else if (classMarker) {
  14286. if (ch === ']') {
  14287. classMarker = false;
  14288. }
  14289. }
  14290. else {
  14291. if (ch === '/') {
  14292. terminated = true;
  14293. break;
  14294. }
  14295. else if (ch === '[') {
  14296. classMarker = true;
  14297. }
  14298. }
  14299. }
  14300. if (!terminated) {
  14301. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  14302. }
  14303. // Exclude leading and trailing slash.
  14304. return str.substr(1, str.length - 2);
  14305. };
  14306. Scanner.prototype.scanRegExpFlags = function () {
  14307. var str = '';
  14308. var flags = '';
  14309. while (!this.eof()) {
  14310. var ch = this.source[this.index];
  14311. if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
  14312. break;
  14313. }
  14314. ++this.index;
  14315. if (ch === '\\' && !this.eof()) {
  14316. ch = this.source[this.index];
  14317. if (ch === 'u') {
  14318. ++this.index;
  14319. var restore = this.index;
  14320. var char = this.scanHexEscape('u');
  14321. if (char !== null) {
  14322. flags += char;
  14323. for (str += '\\u'; restore < this.index; ++restore) {
  14324. str += this.source[restore];
  14325. }
  14326. }
  14327. else {
  14328. this.index = restore;
  14329. flags += 'u';
  14330. str += '\\u';
  14331. }
  14332. this.tolerateUnexpectedToken();
  14333. }
  14334. else {
  14335. str += '\\';
  14336. this.tolerateUnexpectedToken();
  14337. }
  14338. }
  14339. else {
  14340. flags += ch;
  14341. str += ch;
  14342. }
  14343. }
  14344. return flags;
  14345. };
  14346. Scanner.prototype.scanRegExp = function () {
  14347. var start = this.index;
  14348. var pattern = this.scanRegExpBody();
  14349. var flags = this.scanRegExpFlags();
  14350. var value = this.testRegExp(pattern, flags);
  14351. return {
  14352. type: 9 /* RegularExpression */,
  14353. value: '',
  14354. pattern: pattern,
  14355. flags: flags,
  14356. regex: value,
  14357. lineNumber: this.lineNumber,
  14358. lineStart: this.lineStart,
  14359. start: start,
  14360. end: this.index
  14361. };
  14362. };
  14363. Scanner.prototype.lex = function () {
  14364. if (this.eof()) {
  14365. return {
  14366. type: 2 /* EOF */,
  14367. value: '',
  14368. lineNumber: this.lineNumber,
  14369. lineStart: this.lineStart,
  14370. start: this.index,
  14371. end: this.index
  14372. };
  14373. }
  14374. var cp = this.source.charCodeAt(this.index);
  14375. if (character_1.Character.isIdentifierStart(cp)) {
  14376. return this.scanIdentifier();
  14377. }
  14378. // Very common: ( and ) and ;
  14379. if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
  14380. return this.scanPunctuator();
  14381. }
  14382. // String literal starts with single quote (U+0027) or double quote (U+0022).
  14383. if (cp === 0x27 || cp === 0x22) {
  14384. return this.scanStringLiteral();
  14385. }
  14386. // Dot (.) U+002E can also start a floating-point number, hence the need
  14387. // to check the next character.
  14388. if (cp === 0x2E) {
  14389. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
  14390. return this.scanNumericLiteral();
  14391. }
  14392. return this.scanPunctuator();
  14393. }
  14394. if (character_1.Character.isDecimalDigit(cp)) {
  14395. return this.scanNumericLiteral();
  14396. }
  14397. // Template literals start with ` (U+0060) for template head
  14398. // or } (U+007D) for template middle or template tail.
  14399. if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) {
  14400. return this.scanTemplate();
  14401. }
  14402. // Possible identifier start in a surrogate pair.
  14403. if (cp >= 0xD800 && cp < 0xDFFF) {
  14404. if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
  14405. return this.scanIdentifier();
  14406. }
  14407. }
  14408. return this.scanPunctuator();
  14409. };
  14410. return Scanner;
  14411. }());
  14412. exports.Scanner = Scanner;
  14413. /***/ },
  14414. /* 13 */
  14415. /***/ function(module, exports) {
  14416. Object.defineProperty(exports, "__esModule", { value: true });
  14417. exports.TokenName = {};
  14418. exports.TokenName[1 /* BooleanLiteral */] = 'Boolean';
  14419. exports.TokenName[2 /* EOF */] = '<end>';
  14420. exports.TokenName[3 /* Identifier */] = 'Identifier';
  14421. exports.TokenName[4 /* Keyword */] = 'Keyword';
  14422. exports.TokenName[5 /* NullLiteral */] = 'Null';
  14423. exports.TokenName[6 /* NumericLiteral */] = 'Numeric';
  14424. exports.TokenName[7 /* Punctuator */] = 'Punctuator';
  14425. exports.TokenName[8 /* StringLiteral */] = 'String';
  14426. exports.TokenName[9 /* RegularExpression */] = 'RegularExpression';
  14427. exports.TokenName[10 /* Template */] = 'Template';
  14428. /***/ },
  14429. /* 14 */
  14430. /***/ function(module, exports) {
  14431. // Generated by generate-xhtml-entities.js. DO NOT MODIFY!
  14432. Object.defineProperty(exports, "__esModule", { value: true });
  14433. exports.XHTMLEntities = {
  14434. quot: '\u0022',
  14435. amp: '\u0026',
  14436. apos: '\u0027',
  14437. gt: '\u003E',
  14438. nbsp: '\u00A0',
  14439. iexcl: '\u00A1',
  14440. cent: '\u00A2',
  14441. pound: '\u00A3',
  14442. curren: '\u00A4',
  14443. yen: '\u00A5',
  14444. brvbar: '\u00A6',
  14445. sect: '\u00A7',
  14446. uml: '\u00A8',
  14447. copy: '\u00A9',
  14448. ordf: '\u00AA',
  14449. laquo: '\u00AB',
  14450. not: '\u00AC',
  14451. shy: '\u00AD',
  14452. reg: '\u00AE',
  14453. macr: '\u00AF',
  14454. deg: '\u00B0',
  14455. plusmn: '\u00B1',
  14456. sup2: '\u00B2',
  14457. sup3: '\u00B3',
  14458. acute: '\u00B4',
  14459. micro: '\u00B5',
  14460. para: '\u00B6',
  14461. middot: '\u00B7',
  14462. cedil: '\u00B8',
  14463. sup1: '\u00B9',
  14464. ordm: '\u00BA',
  14465. raquo: '\u00BB',
  14466. frac14: '\u00BC',
  14467. frac12: '\u00BD',
  14468. frac34: '\u00BE',
  14469. iquest: '\u00BF',
  14470. Agrave: '\u00C0',
  14471. Aacute: '\u00C1',
  14472. Acirc: '\u00C2',
  14473. Atilde: '\u00C3',
  14474. Auml: '\u00C4',
  14475. Aring: '\u00C5',
  14476. AElig: '\u00C6',
  14477. Ccedil: '\u00C7',
  14478. Egrave: '\u00C8',
  14479. Eacute: '\u00C9',
  14480. Ecirc: '\u00CA',
  14481. Euml: '\u00CB',
  14482. Igrave: '\u00CC',
  14483. Iacute: '\u00CD',
  14484. Icirc: '\u00CE',
  14485. Iuml: '\u00CF',
  14486. ETH: '\u00D0',
  14487. Ntilde: '\u00D1',
  14488. Ograve: '\u00D2',
  14489. Oacute: '\u00D3',
  14490. Ocirc: '\u00D4',
  14491. Otilde: '\u00D5',
  14492. Ouml: '\u00D6',
  14493. times: '\u00D7',
  14494. Oslash: '\u00D8',
  14495. Ugrave: '\u00D9',
  14496. Uacute: '\u00DA',
  14497. Ucirc: '\u00DB',
  14498. Uuml: '\u00DC',
  14499. Yacute: '\u00DD',
  14500. THORN: '\u00DE',
  14501. szlig: '\u00DF',
  14502. agrave: '\u00E0',
  14503. aacute: '\u00E1',
  14504. acirc: '\u00E2',
  14505. atilde: '\u00E3',
  14506. auml: '\u00E4',
  14507. aring: '\u00E5',
  14508. aelig: '\u00E6',
  14509. ccedil: '\u00E7',
  14510. egrave: '\u00E8',
  14511. eacute: '\u00E9',
  14512. ecirc: '\u00EA',
  14513. euml: '\u00EB',
  14514. igrave: '\u00EC',
  14515. iacute: '\u00ED',
  14516. icirc: '\u00EE',
  14517. iuml: '\u00EF',
  14518. eth: '\u00F0',
  14519. ntilde: '\u00F1',
  14520. ograve: '\u00F2',
  14521. oacute: '\u00F3',
  14522. ocirc: '\u00F4',
  14523. otilde: '\u00F5',
  14524. ouml: '\u00F6',
  14525. divide: '\u00F7',
  14526. oslash: '\u00F8',
  14527. ugrave: '\u00F9',
  14528. uacute: '\u00FA',
  14529. ucirc: '\u00FB',
  14530. uuml: '\u00FC',
  14531. yacute: '\u00FD',
  14532. thorn: '\u00FE',
  14533. yuml: '\u00FF',
  14534. OElig: '\u0152',
  14535. oelig: '\u0153',
  14536. Scaron: '\u0160',
  14537. scaron: '\u0161',
  14538. Yuml: '\u0178',
  14539. fnof: '\u0192',
  14540. circ: '\u02C6',
  14541. tilde: '\u02DC',
  14542. Alpha: '\u0391',
  14543. Beta: '\u0392',
  14544. Gamma: '\u0393',
  14545. Delta: '\u0394',
  14546. Epsilon: '\u0395',
  14547. Zeta: '\u0396',
  14548. Eta: '\u0397',
  14549. Theta: '\u0398',
  14550. Iota: '\u0399',
  14551. Kappa: '\u039A',
  14552. Lambda: '\u039B',
  14553. Mu: '\u039C',
  14554. Nu: '\u039D',
  14555. Xi: '\u039E',
  14556. Omicron: '\u039F',
  14557. Pi: '\u03A0',
  14558. Rho: '\u03A1',
  14559. Sigma: '\u03A3',
  14560. Tau: '\u03A4',
  14561. Upsilon: '\u03A5',
  14562. Phi: '\u03A6',
  14563. Chi: '\u03A7',
  14564. Psi: '\u03A8',
  14565. Omega: '\u03A9',
  14566. alpha: '\u03B1',
  14567. beta: '\u03B2',
  14568. gamma: '\u03B3',
  14569. delta: '\u03B4',
  14570. epsilon: '\u03B5',
  14571. zeta: '\u03B6',
  14572. eta: '\u03B7',
  14573. theta: '\u03B8',
  14574. iota: '\u03B9',
  14575. kappa: '\u03BA',
  14576. lambda: '\u03BB',
  14577. mu: '\u03BC',
  14578. nu: '\u03BD',
  14579. xi: '\u03BE',
  14580. omicron: '\u03BF',
  14581. pi: '\u03C0',
  14582. rho: '\u03C1',
  14583. sigmaf: '\u03C2',
  14584. sigma: '\u03C3',
  14585. tau: '\u03C4',
  14586. upsilon: '\u03C5',
  14587. phi: '\u03C6',
  14588. chi: '\u03C7',
  14589. psi: '\u03C8',
  14590. omega: '\u03C9',
  14591. thetasym: '\u03D1',
  14592. upsih: '\u03D2',
  14593. piv: '\u03D6',
  14594. ensp: '\u2002',
  14595. emsp: '\u2003',
  14596. thinsp: '\u2009',
  14597. zwnj: '\u200C',
  14598. zwj: '\u200D',
  14599. lrm: '\u200E',
  14600. rlm: '\u200F',
  14601. ndash: '\u2013',
  14602. mdash: '\u2014',
  14603. lsquo: '\u2018',
  14604. rsquo: '\u2019',
  14605. sbquo: '\u201A',
  14606. ldquo: '\u201C',
  14607. rdquo: '\u201D',
  14608. bdquo: '\u201E',
  14609. dagger: '\u2020',
  14610. Dagger: '\u2021',
  14611. bull: '\u2022',
  14612. hellip: '\u2026',
  14613. permil: '\u2030',
  14614. prime: '\u2032',
  14615. Prime: '\u2033',
  14616. lsaquo: '\u2039',
  14617. rsaquo: '\u203A',
  14618. oline: '\u203E',
  14619. frasl: '\u2044',
  14620. euro: '\u20AC',
  14621. image: '\u2111',
  14622. weierp: '\u2118',
  14623. real: '\u211C',
  14624. trade: '\u2122',
  14625. alefsym: '\u2135',
  14626. larr: '\u2190',
  14627. uarr: '\u2191',
  14628. rarr: '\u2192',
  14629. darr: '\u2193',
  14630. harr: '\u2194',
  14631. crarr: '\u21B5',
  14632. lArr: '\u21D0',
  14633. uArr: '\u21D1',
  14634. rArr: '\u21D2',
  14635. dArr: '\u21D3',
  14636. hArr: '\u21D4',
  14637. forall: '\u2200',
  14638. part: '\u2202',
  14639. exist: '\u2203',
  14640. empty: '\u2205',
  14641. nabla: '\u2207',
  14642. isin: '\u2208',
  14643. notin: '\u2209',
  14644. ni: '\u220B',
  14645. prod: '\u220F',
  14646. sum: '\u2211',
  14647. minus: '\u2212',
  14648. lowast: '\u2217',
  14649. radic: '\u221A',
  14650. prop: '\u221D',
  14651. infin: '\u221E',
  14652. ang: '\u2220',
  14653. and: '\u2227',
  14654. or: '\u2228',
  14655. cap: '\u2229',
  14656. cup: '\u222A',
  14657. int: '\u222B',
  14658. there4: '\u2234',
  14659. sim: '\u223C',
  14660. cong: '\u2245',
  14661. asymp: '\u2248',
  14662. ne: '\u2260',
  14663. equiv: '\u2261',
  14664. le: '\u2264',
  14665. ge: '\u2265',
  14666. sub: '\u2282',
  14667. sup: '\u2283',
  14668. nsub: '\u2284',
  14669. sube: '\u2286',
  14670. supe: '\u2287',
  14671. oplus: '\u2295',
  14672. otimes: '\u2297',
  14673. perp: '\u22A5',
  14674. sdot: '\u22C5',
  14675. lceil: '\u2308',
  14676. rceil: '\u2309',
  14677. lfloor: '\u230A',
  14678. rfloor: '\u230B',
  14679. loz: '\u25CA',
  14680. spades: '\u2660',
  14681. clubs: '\u2663',
  14682. hearts: '\u2665',
  14683. diams: '\u2666',
  14684. lang: '\u27E8',
  14685. rang: '\u27E9'
  14686. };
  14687. /***/ },
  14688. /* 15 */
  14689. /***/ function(module, exports, __webpack_require__) {
  14690. Object.defineProperty(exports, "__esModule", { value: true });
  14691. var error_handler_1 = __webpack_require__(10);
  14692. var scanner_1 = __webpack_require__(12);
  14693. var token_1 = __webpack_require__(13);
  14694. var Reader = (function () {
  14695. function Reader() {
  14696. this.values = [];
  14697. this.curly = this.paren = -1;
  14698. }
  14699. // A function following one of those tokens is an expression.
  14700. Reader.prototype.beforeFunctionExpression = function (t) {
  14701. return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  14702. 'return', 'case', 'delete', 'throw', 'void',
  14703. // assignment operators
  14704. '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=',
  14705. '&=', '|=', '^=', ',',
  14706. // binary/unary operators
  14707. '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  14708. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  14709. '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
  14710. };
  14711. // Determine if forward slash (/) is an operator or part of a regular expression
  14712. // https://github.com/mozilla/sweet.js/wiki/design
  14713. Reader.prototype.isRegexStart = function () {
  14714. var previous = this.values[this.values.length - 1];
  14715. var regex = (previous !== null);
  14716. switch (previous) {
  14717. case 'this':
  14718. case ']':
  14719. regex = false;
  14720. break;
  14721. case ')':
  14722. var keyword = this.values[this.paren - 1];
  14723. regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with');
  14724. break;
  14725. case '}':
  14726. // Dividing a function by anything makes little sense,
  14727. // but we have to check for that.
  14728. regex = false;
  14729. if (this.values[this.curly - 3] === 'function') {
  14730. // Anonymous function, e.g. function(){} /42
  14731. var check = this.values[this.curly - 4];
  14732. regex = check ? !this.beforeFunctionExpression(check) : false;
  14733. }
  14734. else if (this.values[this.curly - 4] === 'function') {
  14735. // Named function, e.g. function f(){} /42/
  14736. var check = this.values[this.curly - 5];
  14737. regex = check ? !this.beforeFunctionExpression(check) : true;
  14738. }
  14739. break;
  14740. }
  14741. return regex;
  14742. };
  14743. Reader.prototype.push = function (token) {
  14744. if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) {
  14745. if (token.value === '{') {
  14746. this.curly = this.values.length;
  14747. }
  14748. else if (token.value === '(') {
  14749. this.paren = this.values.length;
  14750. }
  14751. this.values.push(token.value);
  14752. }
  14753. else {
  14754. this.values.push(null);
  14755. }
  14756. };
  14757. return Reader;
  14758. }());
  14759. var Tokenizer = (function () {
  14760. function Tokenizer(code, config) {
  14761. this.errorHandler = new error_handler_1.ErrorHandler();
  14762. this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false;
  14763. this.scanner = new scanner_1.Scanner(code, this.errorHandler);
  14764. this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false;
  14765. this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false;
  14766. this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false;
  14767. this.buffer = [];
  14768. this.reader = new Reader();
  14769. }
  14770. Tokenizer.prototype.errors = function () {
  14771. return this.errorHandler.errors;
  14772. };
  14773. Tokenizer.prototype.getNextToken = function () {
  14774. if (this.buffer.length === 0) {
  14775. var comments = this.scanner.scanComments();
  14776. if (this.scanner.trackComment) {
  14777. for (var i = 0; i < comments.length; ++i) {
  14778. var e = comments[i];
  14779. var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
  14780. var comment = {
  14781. type: e.multiLine ? 'BlockComment' : 'LineComment',
  14782. value: value
  14783. };
  14784. if (this.trackRange) {
  14785. comment.range = e.range;
  14786. }
  14787. if (this.trackLoc) {
  14788. comment.loc = e.loc;
  14789. }
  14790. this.buffer.push(comment);
  14791. }
  14792. }
  14793. if (!this.scanner.eof()) {
  14794. var loc = void 0;
  14795. if (this.trackLoc) {
  14796. loc = {
  14797. start: {
  14798. line: this.scanner.lineNumber,
  14799. column: this.scanner.index - this.scanner.lineStart
  14800. },
  14801. end: {}
  14802. };
  14803. }
  14804. var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart();
  14805. var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
  14806. this.reader.push(token);
  14807. var entry = {
  14808. type: token_1.TokenName[token.type],
  14809. value: this.scanner.source.slice(token.start, token.end)
  14810. };
  14811. if (this.trackRange) {
  14812. entry.range = [token.start, token.end];
  14813. }
  14814. if (this.trackLoc) {
  14815. loc.end = {
  14816. line: this.scanner.lineNumber,
  14817. column: this.scanner.index - this.scanner.lineStart
  14818. };
  14819. entry.loc = loc;
  14820. }
  14821. if (token.type === 9 /* RegularExpression */) {
  14822. var pattern = token.pattern;
  14823. var flags = token.flags;
  14824. entry.regex = { pattern: pattern, flags: flags };
  14825. }
  14826. this.buffer.push(entry);
  14827. }
  14828. }
  14829. return this.buffer.shift();
  14830. };
  14831. return Tokenizer;
  14832. }());
  14833. exports.Tokenizer = Tokenizer;
  14834. /***/ }
  14835. /******/ ])
  14836. });
  14837. });
  14838. unwrapExports(esprima$1);
  14839. var esprima$2 = createCommonjsModule(function (module, exports) {
  14840. Object.defineProperty(exports, "__esModule", { value: true });
  14841. // This module is suitable for passing as options.parser when calling
  14842. // recast.parse to process ECMAScript code with Esprima:
  14843. //
  14844. // const ast = recast.parse(source, {
  14845. // parser: require("recast/parsers/esprima")
  14846. // });
  14847. //
  14848. function parse(source, options) {
  14849. var comments = [];
  14850. var ast = esprima$1.parse(source, {
  14851. loc: true,
  14852. locations: true,
  14853. comment: true,
  14854. onComment: comments,
  14855. range: util$1.getOption(options, "range", false),
  14856. tolerant: util$1.getOption(options, "tolerant", true),
  14857. tokens: true
  14858. });
  14859. if (!Array.isArray(ast.comments)) {
  14860. ast.comments = comments;
  14861. }
  14862. return ast;
  14863. }
  14864. exports.parse = parse;
  14865. });
  14866. unwrapExports(esprima$2);
  14867. var esprima_1 = esprima$2.parse;
  14868. /*
  14869. The MIT License (MIT)
  14870. Copyright (c) 2016 CoderPuppy
  14871. Permission is hereby granted, free of charge, to any person obtaining a copy
  14872. of this software and associated documentation files (the "Software"), to deal
  14873. in the Software without restriction, including without limitation the rights
  14874. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14875. copies of the Software, and to permit persons to whom the Software is
  14876. furnished to do so, subject to the following conditions:
  14877. The above copyright notice and this permission notice shall be included in all
  14878. copies or substantial portions of the Software.
  14879. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14880. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14881. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14882. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14883. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14884. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  14885. SOFTWARE.
  14886. */
  14887. var _endianness;
  14888. function endianness() {
  14889. if (typeof _endianness === 'undefined') {
  14890. var a = new ArrayBuffer(2);
  14891. var b = new Uint8Array(a);
  14892. var c = new Uint16Array(a);
  14893. b[0] = 1;
  14894. b[1] = 2;
  14895. if (c[0] === 258) {
  14896. _endianness = 'BE';
  14897. } else if (c[0] === 513){
  14898. _endianness = 'LE';
  14899. } else {
  14900. throw new Error('unable to figure out endianess');
  14901. }
  14902. }
  14903. return _endianness;
  14904. }
  14905. function hostname() {
  14906. if (typeof global.location !== 'undefined') {
  14907. return global.location.hostname
  14908. } else return '';
  14909. }
  14910. function loadavg() {
  14911. return [];
  14912. }
  14913. function uptime() {
  14914. return 0;
  14915. }
  14916. function freemem() {
  14917. return Number.MAX_VALUE;
  14918. }
  14919. function totalmem() {
  14920. return Number.MAX_VALUE;
  14921. }
  14922. function cpus() {
  14923. return [];
  14924. }
  14925. function type() {
  14926. return 'Browser';
  14927. }
  14928. function release () {
  14929. if (typeof global.navigator !== 'undefined') {
  14930. return global.navigator.appVersion;
  14931. }
  14932. return '';
  14933. }
  14934. function networkInterfaces(){}
  14935. function getNetworkInterfaces(){}
  14936. function tmpDir() {
  14937. return '/tmp';
  14938. }
  14939. var tmpdir = tmpDir;
  14940. var EOL = '\n';
  14941. var require$$1 = {
  14942. EOL: EOL,
  14943. tmpdir: tmpdir,
  14944. tmpDir: tmpDir,
  14945. networkInterfaces:networkInterfaces,
  14946. getNetworkInterfaces: getNetworkInterfaces,
  14947. release: release,
  14948. type: type,
  14949. cpus: cpus,
  14950. totalmem: totalmem,
  14951. freemem: freemem,
  14952. uptime: uptime,
  14953. loadavg: loadavg,
  14954. hostname: hostname,
  14955. endianness: endianness,
  14956. };
  14957. var options = createCommonjsModule(function (module, exports) {
  14958. Object.defineProperty(exports, "__esModule", { value: true });
  14959. var defaults = {
  14960. parser: esprima$2,
  14961. tabWidth: 4,
  14962. useTabs: false,
  14963. reuseWhitespace: true,
  14964. lineTerminator: require$$1.EOL ,
  14965. wrapColumn: 74,
  14966. sourceFileName: null,
  14967. sourceMapName: null,
  14968. sourceRoot: null,
  14969. inputSourceMap: null,
  14970. range: false,
  14971. tolerant: true,
  14972. quote: null,
  14973. trailingComma: false,
  14974. arrayBracketSpacing: false,
  14975. objectCurlySpacing: true,
  14976. arrowParensAlways: false,
  14977. flowObjectCommas: true,
  14978. tokens: true
  14979. }, hasOwn = defaults.hasOwnProperty;
  14980. // Copy options and fill in default values.
  14981. function normalize(opts) {
  14982. var options = opts || defaults;
  14983. function get(key) {
  14984. return hasOwn.call(options, key)
  14985. ? options[key]
  14986. : defaults[key];
  14987. }
  14988. return {
  14989. tabWidth: +get("tabWidth"),
  14990. useTabs: !!get("useTabs"),
  14991. reuseWhitespace: !!get("reuseWhitespace"),
  14992. lineTerminator: get("lineTerminator"),
  14993. wrapColumn: Math.max(get("wrapColumn"), 0),
  14994. sourceFileName: get("sourceFileName"),
  14995. sourceMapName: get("sourceMapName"),
  14996. sourceRoot: get("sourceRoot"),
  14997. inputSourceMap: get("inputSourceMap"),
  14998. parser: get("esprima") || get("parser"),
  14999. range: get("range"),
  15000. tolerant: get("tolerant"),
  15001. quote: get("quote"),
  15002. trailingComma: get("trailingComma"),
  15003. arrayBracketSpacing: get("arrayBracketSpacing"),
  15004. objectCurlySpacing: get("objectCurlySpacing"),
  15005. arrowParensAlways: get("arrowParensAlways"),
  15006. flowObjectCommas: get("flowObjectCommas"),
  15007. tokens: !!get("tokens")
  15008. };
  15009. }
  15010. exports.normalize = normalize;
  15011. });
  15012. unwrapExports(options);
  15013. var options_1 = options.normalize;
  15014. var mapping = createCommonjsModule(function (module, exports) {
  15015. var __importDefault = (this && this.__importDefault) || function (mod) {
  15016. return (mod && mod.__esModule) ? mod : { "default": mod };
  15017. };
  15018. Object.defineProperty(exports, "__esModule", { value: true });
  15019. var assert_1 = __importDefault(assert);
  15020. var Mapping = /** @class */ (function () {
  15021. function Mapping(sourceLines, sourceLoc, targetLoc) {
  15022. if (targetLoc === void 0) { targetLoc = sourceLoc; }
  15023. this.sourceLines = sourceLines;
  15024. this.sourceLoc = sourceLoc;
  15025. this.targetLoc = targetLoc;
  15026. }
  15027. Mapping.prototype.slice = function (lines, start, end) {
  15028. if (end === void 0) { end = lines.lastPos(); }
  15029. var sourceLines = this.sourceLines;
  15030. var sourceLoc = this.sourceLoc;
  15031. var targetLoc = this.targetLoc;
  15032. function skip(name) {
  15033. var sourceFromPos = sourceLoc[name];
  15034. var targetFromPos = targetLoc[name];
  15035. var targetToPos = start;
  15036. if (name === "end") {
  15037. targetToPos = end;
  15038. }
  15039. else {
  15040. assert_1.default.strictEqual(name, "start");
  15041. }
  15042. return skipChars(sourceLines, sourceFromPos, lines, targetFromPos, targetToPos);
  15043. }
  15044. if (util$1.comparePos(start, targetLoc.start) <= 0) {
  15045. if (util$1.comparePos(targetLoc.end, end) <= 0) {
  15046. targetLoc = {
  15047. start: subtractPos(targetLoc.start, start.line, start.column),
  15048. end: subtractPos(targetLoc.end, start.line, start.column)
  15049. };
  15050. // The sourceLoc can stay the same because the contents of the
  15051. // targetLoc have not changed.
  15052. }
  15053. else if (util$1.comparePos(end, targetLoc.start) <= 0) {
  15054. return null;
  15055. }
  15056. else {
  15057. sourceLoc = {
  15058. start: sourceLoc.start,
  15059. end: skip("end")
  15060. };
  15061. targetLoc = {
  15062. start: subtractPos(targetLoc.start, start.line, start.column),
  15063. end: subtractPos(end, start.line, start.column)
  15064. };
  15065. }
  15066. }
  15067. else {
  15068. if (util$1.comparePos(targetLoc.end, start) <= 0) {
  15069. return null;
  15070. }
  15071. if (util$1.comparePos(targetLoc.end, end) <= 0) {
  15072. sourceLoc = {
  15073. start: skip("start"),
  15074. end: sourceLoc.end
  15075. };
  15076. targetLoc = {
  15077. // Same as subtractPos(start, start.line, start.column):
  15078. start: { line: 1, column: 0 },
  15079. end: subtractPos(targetLoc.end, start.line, start.column)
  15080. };
  15081. }
  15082. else {
  15083. sourceLoc = {
  15084. start: skip("start"),
  15085. end: skip("end")
  15086. };
  15087. targetLoc = {
  15088. // Same as subtractPos(start, start.line, start.column):
  15089. start: { line: 1, column: 0 },
  15090. end: subtractPos(end, start.line, start.column)
  15091. };
  15092. }
  15093. }
  15094. return new Mapping(this.sourceLines, sourceLoc, targetLoc);
  15095. };
  15096. Mapping.prototype.add = function (line, column) {
  15097. return new Mapping(this.sourceLines, this.sourceLoc, {
  15098. start: addPos(this.targetLoc.start, line, column),
  15099. end: addPos(this.targetLoc.end, line, column)
  15100. });
  15101. };
  15102. Mapping.prototype.subtract = function (line, column) {
  15103. return new Mapping(this.sourceLines, this.sourceLoc, {
  15104. start: subtractPos(this.targetLoc.start, line, column),
  15105. end: subtractPos(this.targetLoc.end, line, column)
  15106. });
  15107. };
  15108. Mapping.prototype.indent = function (by, skipFirstLine, noNegativeColumns) {
  15109. if (skipFirstLine === void 0) { skipFirstLine = false; }
  15110. if (noNegativeColumns === void 0) { noNegativeColumns = false; }
  15111. if (by === 0) {
  15112. return this;
  15113. }
  15114. var targetLoc = this.targetLoc;
  15115. var startLine = targetLoc.start.line;
  15116. var endLine = targetLoc.end.line;
  15117. if (skipFirstLine && startLine === 1 && endLine === 1) {
  15118. return this;
  15119. }
  15120. targetLoc = {
  15121. start: targetLoc.start,
  15122. end: targetLoc.end
  15123. };
  15124. if (!skipFirstLine || startLine > 1) {
  15125. var startColumn = targetLoc.start.column + by;
  15126. targetLoc.start = {
  15127. line: startLine,
  15128. column: noNegativeColumns
  15129. ? Math.max(0, startColumn)
  15130. : startColumn
  15131. };
  15132. }
  15133. if (!skipFirstLine || endLine > 1) {
  15134. var endColumn = targetLoc.end.column + by;
  15135. targetLoc.end = {
  15136. line: endLine,
  15137. column: noNegativeColumns
  15138. ? Math.max(0, endColumn)
  15139. : endColumn
  15140. };
  15141. }
  15142. return new Mapping(this.sourceLines, this.sourceLoc, targetLoc);
  15143. };
  15144. return Mapping;
  15145. }());
  15146. exports.default = Mapping;
  15147. function addPos(toPos, line, column) {
  15148. return {
  15149. line: toPos.line + line - 1,
  15150. column: (toPos.line === 1)
  15151. ? toPos.column + column
  15152. : toPos.column
  15153. };
  15154. }
  15155. function subtractPos(fromPos, line, column) {
  15156. return {
  15157. line: fromPos.line - line + 1,
  15158. column: (fromPos.line === line)
  15159. ? fromPos.column - column
  15160. : fromPos.column
  15161. };
  15162. }
  15163. function skipChars(sourceLines, sourceFromPos, targetLines, targetFromPos, targetToPos) {
  15164. var targetComparison = util$1.comparePos(targetFromPos, targetToPos);
  15165. if (targetComparison === 0) {
  15166. // Trivial case: no characters to skip.
  15167. return sourceFromPos;
  15168. }
  15169. if (targetComparison < 0) {
  15170. // Skipping forward.
  15171. var sourceCursor = sourceLines.skipSpaces(sourceFromPos) || sourceLines.lastPos();
  15172. var targetCursor = targetLines.skipSpaces(targetFromPos) || targetLines.lastPos();
  15173. var lineDiff = targetToPos.line - targetCursor.line;
  15174. sourceCursor.line += lineDiff;
  15175. targetCursor.line += lineDiff;
  15176. if (lineDiff > 0) {
  15177. // If jumping to later lines, reset columns to the beginnings
  15178. // of those lines.
  15179. sourceCursor.column = 0;
  15180. targetCursor.column = 0;
  15181. }
  15182. else {
  15183. assert_1.default.strictEqual(lineDiff, 0);
  15184. }
  15185. while (util$1.comparePos(targetCursor, targetToPos) < 0 &&
  15186. targetLines.nextPos(targetCursor, true)) {
  15187. assert_1.default.ok(sourceLines.nextPos(sourceCursor, true));
  15188. assert_1.default.strictEqual(sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor));
  15189. }
  15190. }
  15191. else {
  15192. // Skipping backward.
  15193. var sourceCursor = sourceLines.skipSpaces(sourceFromPos, true) || sourceLines.firstPos();
  15194. var targetCursor = targetLines.skipSpaces(targetFromPos, true) || targetLines.firstPos();
  15195. var lineDiff = targetToPos.line - targetCursor.line;
  15196. sourceCursor.line += lineDiff;
  15197. targetCursor.line += lineDiff;
  15198. if (lineDiff < 0) {
  15199. // If jumping to earlier lines, reset columns to the ends of
  15200. // those lines.
  15201. sourceCursor.column = sourceLines.getLineLength(sourceCursor.line);
  15202. targetCursor.column = targetLines.getLineLength(targetCursor.line);
  15203. }
  15204. else {
  15205. assert_1.default.strictEqual(lineDiff, 0);
  15206. }
  15207. while (util$1.comparePos(targetToPos, targetCursor) < 0 &&
  15208. targetLines.prevPos(targetCursor, true)) {
  15209. assert_1.default.ok(sourceLines.prevPos(sourceCursor, true));
  15210. assert_1.default.strictEqual(sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor));
  15211. }
  15212. }
  15213. return sourceCursor;
  15214. }
  15215. });
  15216. unwrapExports(mapping);
  15217. var lines = createCommonjsModule(function (module, exports) {
  15218. var __assign = (this && this.__assign) || function () {
  15219. __assign = Object.assign || function(t) {
  15220. for (var s, i = 1, n = arguments.length; i < n; i++) {
  15221. s = arguments[i];
  15222. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  15223. t[p] = s[p];
  15224. }
  15225. return t;
  15226. };
  15227. return __assign.apply(this, arguments);
  15228. };
  15229. var __importDefault = (this && this.__importDefault) || function (mod) {
  15230. return (mod && mod.__esModule) ? mod : { "default": mod };
  15231. };
  15232. Object.defineProperty(exports, "__esModule", { value: true });
  15233. var assert_1 = __importDefault(assert);
  15234. var source_map_1 = __importDefault(sourceMap);
  15235. var mapping_1 = __importDefault(mapping);
  15236. var Lines = /** @class */ (function () {
  15237. function Lines(infos, sourceFileName) {
  15238. if (sourceFileName === void 0) { sourceFileName = null; }
  15239. this.infos = infos;
  15240. this.mappings = [];
  15241. this.cachedSourceMap = null;
  15242. this.cachedTabWidth = void 0;
  15243. assert_1.default.ok(infos.length > 0);
  15244. this.length = infos.length;
  15245. this.name = sourceFileName || null;
  15246. if (this.name) {
  15247. this.mappings.push(new mapping_1.default(this, {
  15248. start: this.firstPos(),
  15249. end: this.lastPos(),
  15250. }));
  15251. }
  15252. }
  15253. Lines.prototype.toString = function (options) {
  15254. return this.sliceString(this.firstPos(), this.lastPos(), options);
  15255. };
  15256. Lines.prototype.getSourceMap = function (sourceMapName, sourceRoot) {
  15257. if (!sourceMapName) {
  15258. // Although we could make up a name or generate an anonymous
  15259. // source map, instead we assume that any consumer who does not
  15260. // provide a name does not actually want a source map.
  15261. return null;
  15262. }
  15263. var targetLines = this;
  15264. function updateJSON(json) {
  15265. json = json || {};
  15266. json.file = sourceMapName;
  15267. if (sourceRoot) {
  15268. json.sourceRoot = sourceRoot;
  15269. }
  15270. return json;
  15271. }
  15272. if (targetLines.cachedSourceMap) {
  15273. // Since Lines objects are immutable, we can reuse any source map
  15274. // that was previously generated. Nevertheless, we return a new
  15275. // JSON object here to protect the cached source map from outside
  15276. // modification.
  15277. return updateJSON(targetLines.cachedSourceMap.toJSON());
  15278. }
  15279. var smg = new source_map_1.default.SourceMapGenerator(updateJSON());
  15280. var sourcesToContents = {};
  15281. targetLines.mappings.forEach(function (mapping) {
  15282. var sourceCursor = mapping.sourceLines.skipSpaces(mapping.sourceLoc.start) || mapping.sourceLines.lastPos();
  15283. var targetCursor = targetLines.skipSpaces(mapping.targetLoc.start) || targetLines.lastPos();
  15284. while (util$1.comparePos(sourceCursor, mapping.sourceLoc.end) < 0 &&
  15285. util$1.comparePos(targetCursor, mapping.targetLoc.end) < 0) {
  15286. var sourceChar = mapping.sourceLines.charAt(sourceCursor);
  15287. var targetChar = targetLines.charAt(targetCursor);
  15288. assert_1.default.strictEqual(sourceChar, targetChar);
  15289. var sourceName = mapping.sourceLines.name;
  15290. // Add mappings one character at a time for maximum resolution.
  15291. smg.addMapping({
  15292. source: sourceName,
  15293. original: { line: sourceCursor.line,
  15294. column: sourceCursor.column },
  15295. generated: { line: targetCursor.line,
  15296. column: targetCursor.column }
  15297. });
  15298. if (!hasOwn.call(sourcesToContents, sourceName)) {
  15299. var sourceContent = mapping.sourceLines.toString();
  15300. smg.setSourceContent(sourceName, sourceContent);
  15301. sourcesToContents[sourceName] = sourceContent;
  15302. }
  15303. targetLines.nextPos(targetCursor, true);
  15304. mapping.sourceLines.nextPos(sourceCursor, true);
  15305. }
  15306. });
  15307. targetLines.cachedSourceMap = smg;
  15308. return smg.toJSON();
  15309. };
  15310. Lines.prototype.bootstrapCharAt = function (pos) {
  15311. assert_1.default.strictEqual(typeof pos, "object");
  15312. assert_1.default.strictEqual(typeof pos.line, "number");
  15313. assert_1.default.strictEqual(typeof pos.column, "number");
  15314. var line = pos.line, column = pos.column, strings = this.toString().split(lineTerminatorSeqExp), string = strings[line - 1];
  15315. if (typeof string === "undefined")
  15316. return "";
  15317. if (column === string.length &&
  15318. line < strings.length)
  15319. return "\n";
  15320. if (column >= string.length)
  15321. return "";
  15322. return string.charAt(column);
  15323. };
  15324. Lines.prototype.charAt = function (pos) {
  15325. assert_1.default.strictEqual(typeof pos, "object");
  15326. assert_1.default.strictEqual(typeof pos.line, "number");
  15327. assert_1.default.strictEqual(typeof pos.column, "number");
  15328. var line = pos.line, column = pos.column, secret = this, infos = secret.infos, info = infos[line - 1], c = column;
  15329. if (typeof info === "undefined" || c < 0)
  15330. return "";
  15331. var indent = this.getIndentAt(line);
  15332. if (c < indent)
  15333. return " ";
  15334. c += info.sliceStart - indent;
  15335. if (c === info.sliceEnd &&
  15336. line < this.length)
  15337. return "\n";
  15338. if (c >= info.sliceEnd)
  15339. return "";
  15340. return info.line.charAt(c);
  15341. };
  15342. Lines.prototype.stripMargin = function (width, skipFirstLine) {
  15343. if (width === 0)
  15344. return this;
  15345. assert_1.default.ok(width > 0, "negative margin: " + width);
  15346. if (skipFirstLine && this.length === 1)
  15347. return this;
  15348. var lines = new Lines(this.infos.map(function (info, i) {
  15349. if (info.line && (i > 0 || !skipFirstLine)) {
  15350. info = __assign({}, info, { indent: Math.max(0, info.indent - width) });
  15351. }
  15352. return info;
  15353. }));
  15354. if (this.mappings.length > 0) {
  15355. var newMappings = lines.mappings;
  15356. assert_1.default.strictEqual(newMappings.length, 0);
  15357. this.mappings.forEach(function (mapping) {
  15358. newMappings.push(mapping.indent(width, skipFirstLine, true));
  15359. });
  15360. }
  15361. return lines;
  15362. };
  15363. Lines.prototype.indent = function (by) {
  15364. if (by === 0) {
  15365. return this;
  15366. }
  15367. var lines = new Lines(this.infos.map(function (info) {
  15368. if (info.line && !info.locked) {
  15369. info = __assign({}, info, { indent: info.indent + by });
  15370. }
  15371. return info;
  15372. }));
  15373. if (this.mappings.length > 0) {
  15374. var newMappings = lines.mappings;
  15375. assert_1.default.strictEqual(newMappings.length, 0);
  15376. this.mappings.forEach(function (mapping) {
  15377. newMappings.push(mapping.indent(by));
  15378. });
  15379. }
  15380. return lines;
  15381. };
  15382. Lines.prototype.indentTail = function (by) {
  15383. if (by === 0) {
  15384. return this;
  15385. }
  15386. if (this.length < 2) {
  15387. return this;
  15388. }
  15389. var lines = new Lines(this.infos.map(function (info, i) {
  15390. if (i > 0 && info.line && !info.locked) {
  15391. info = __assign({}, info, { indent: info.indent + by });
  15392. }
  15393. return info;
  15394. }));
  15395. if (this.mappings.length > 0) {
  15396. var newMappings = lines.mappings;
  15397. assert_1.default.strictEqual(newMappings.length, 0);
  15398. this.mappings.forEach(function (mapping) {
  15399. newMappings.push(mapping.indent(by, true));
  15400. });
  15401. }
  15402. return lines;
  15403. };
  15404. Lines.prototype.lockIndentTail = function () {
  15405. if (this.length < 2) {
  15406. return this;
  15407. }
  15408. return new Lines(this.infos.map(function (info, i) {
  15409. return __assign({}, info, { locked: i > 0 });
  15410. }));
  15411. };
  15412. Lines.prototype.getIndentAt = function (line) {
  15413. assert_1.default.ok(line >= 1, "no line " + line + " (line numbers start from 1)");
  15414. return Math.max(this.infos[line - 1].indent, 0);
  15415. };
  15416. Lines.prototype.guessTabWidth = function () {
  15417. if (typeof this.cachedTabWidth === "number") {
  15418. return this.cachedTabWidth;
  15419. }
  15420. var counts = []; // Sparse array.
  15421. var lastIndent = 0;
  15422. for (var line = 1, last = this.length; line <= last; ++line) {
  15423. var info = this.infos[line - 1];
  15424. var sliced = info.line.slice(info.sliceStart, info.sliceEnd);
  15425. // Whitespace-only lines don't tell us much about the likely tab
  15426. // width of this code.
  15427. if (isOnlyWhitespace(sliced)) {
  15428. continue;
  15429. }
  15430. var diff = Math.abs(info.indent - lastIndent);
  15431. counts[diff] = ~~counts[diff] + 1;
  15432. lastIndent = info.indent;
  15433. }
  15434. var maxCount = -1;
  15435. var result = 2;
  15436. for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) {
  15437. if (hasOwn.call(counts, tabWidth) &&
  15438. counts[tabWidth] > maxCount) {
  15439. maxCount = counts[tabWidth];
  15440. result = tabWidth;
  15441. }
  15442. }
  15443. return this.cachedTabWidth = result;
  15444. };
  15445. // Determine if the list of lines has a first line that starts with a //
  15446. // or /* comment. If this is the case, the code may need to be wrapped in
  15447. // parens to avoid ASI issues.
  15448. Lines.prototype.startsWithComment = function () {
  15449. if (this.infos.length === 0) {
  15450. return false;
  15451. }
  15452. var firstLineInfo = this.infos[0], sliceStart = firstLineInfo.sliceStart, sliceEnd = firstLineInfo.sliceEnd, firstLine = firstLineInfo.line.slice(sliceStart, sliceEnd).trim();
  15453. return firstLine.length === 0 ||
  15454. firstLine.slice(0, 2) === "//" ||
  15455. firstLine.slice(0, 2) === "/*";
  15456. };
  15457. Lines.prototype.isOnlyWhitespace = function () {
  15458. return isOnlyWhitespace(this.toString());
  15459. };
  15460. Lines.prototype.isPrecededOnlyByWhitespace = function (pos) {
  15461. var info = this.infos[pos.line - 1];
  15462. var indent = Math.max(info.indent, 0);
  15463. var diff = pos.column - indent;
  15464. if (diff <= 0) {
  15465. // If pos.column does not exceed the indentation amount, then
  15466. // there must be only whitespace before it.
  15467. return true;
  15468. }
  15469. var start = info.sliceStart;
  15470. var end = Math.min(start + diff, info.sliceEnd);
  15471. var prefix = info.line.slice(start, end);
  15472. return isOnlyWhitespace(prefix);
  15473. };
  15474. Lines.prototype.getLineLength = function (line) {
  15475. var info = this.infos[line - 1];
  15476. return this.getIndentAt(line) + info.sliceEnd - info.sliceStart;
  15477. };
  15478. Lines.prototype.nextPos = function (pos, skipSpaces) {
  15479. if (skipSpaces === void 0) { skipSpaces = false; }
  15480. var l = Math.max(pos.line, 0), c = Math.max(pos.column, 0);
  15481. if (c < this.getLineLength(l)) {
  15482. pos.column += 1;
  15483. return skipSpaces
  15484. ? !!this.skipSpaces(pos, false, true)
  15485. : true;
  15486. }
  15487. if (l < this.length) {
  15488. pos.line += 1;
  15489. pos.column = 0;
  15490. return skipSpaces
  15491. ? !!this.skipSpaces(pos, false, true)
  15492. : true;
  15493. }
  15494. return false;
  15495. };
  15496. Lines.prototype.prevPos = function (pos, skipSpaces) {
  15497. if (skipSpaces === void 0) { skipSpaces = false; }
  15498. var l = pos.line, c = pos.column;
  15499. if (c < 1) {
  15500. l -= 1;
  15501. if (l < 1)
  15502. return false;
  15503. c = this.getLineLength(l);
  15504. }
  15505. else {
  15506. c = Math.min(c - 1, this.getLineLength(l));
  15507. }
  15508. pos.line = l;
  15509. pos.column = c;
  15510. return skipSpaces
  15511. ? !!this.skipSpaces(pos, true, true)
  15512. : true;
  15513. };
  15514. Lines.prototype.firstPos = function () {
  15515. // Trivial, but provided for completeness.
  15516. return { line: 1, column: 0 };
  15517. };
  15518. Lines.prototype.lastPos = function () {
  15519. return {
  15520. line: this.length,
  15521. column: this.getLineLength(this.length)
  15522. };
  15523. };
  15524. Lines.prototype.skipSpaces = function (pos, backward, modifyInPlace) {
  15525. if (backward === void 0) { backward = false; }
  15526. if (modifyInPlace === void 0) { modifyInPlace = false; }
  15527. if (pos) {
  15528. pos = modifyInPlace ? pos : {
  15529. line: pos.line,
  15530. column: pos.column
  15531. };
  15532. }
  15533. else if (backward) {
  15534. pos = this.lastPos();
  15535. }
  15536. else {
  15537. pos = this.firstPos();
  15538. }
  15539. if (backward) {
  15540. while (this.prevPos(pos)) {
  15541. if (!isOnlyWhitespace(this.charAt(pos)) &&
  15542. this.nextPos(pos)) {
  15543. return pos;
  15544. }
  15545. }
  15546. return null;
  15547. }
  15548. else {
  15549. while (isOnlyWhitespace(this.charAt(pos))) {
  15550. if (!this.nextPos(pos)) {
  15551. return null;
  15552. }
  15553. }
  15554. return pos;
  15555. }
  15556. };
  15557. Lines.prototype.trimLeft = function () {
  15558. var pos = this.skipSpaces(this.firstPos(), false, true);
  15559. return pos ? this.slice(pos) : emptyLines;
  15560. };
  15561. Lines.prototype.trimRight = function () {
  15562. var pos = this.skipSpaces(this.lastPos(), true, true);
  15563. return pos ? this.slice(this.firstPos(), pos) : emptyLines;
  15564. };
  15565. Lines.prototype.trim = function () {
  15566. var start = this.skipSpaces(this.firstPos(), false, true);
  15567. if (start === null) {
  15568. return emptyLines;
  15569. }
  15570. var end = this.skipSpaces(this.lastPos(), true, true);
  15571. if (end === null) {
  15572. return emptyLines;
  15573. }
  15574. return this.slice(start, end);
  15575. };
  15576. Lines.prototype.eachPos = function (callback, startPos, skipSpaces) {
  15577. if (startPos === void 0) { startPos = this.firstPos(); }
  15578. if (skipSpaces === void 0) { skipSpaces = false; }
  15579. var pos = this.firstPos();
  15580. if (startPos) {
  15581. pos.line = startPos.line,
  15582. pos.column = startPos.column;
  15583. }
  15584. if (skipSpaces && !this.skipSpaces(pos, false, true)) {
  15585. return; // Encountered nothing but spaces.
  15586. }
  15587. do
  15588. callback.call(this, pos);
  15589. while (this.nextPos(pos, skipSpaces));
  15590. };
  15591. Lines.prototype.bootstrapSlice = function (start, end) {
  15592. var strings = this.toString().split(lineTerminatorSeqExp).slice(start.line - 1, end.line);
  15593. if (strings.length > 0) {
  15594. strings.push(strings.pop().slice(0, end.column));
  15595. strings[0] = strings[0].slice(start.column);
  15596. }
  15597. return fromString(strings.join("\n"));
  15598. };
  15599. Lines.prototype.slice = function (start, end) {
  15600. if (!end) {
  15601. if (!start) {
  15602. // The client seems to want a copy of this Lines object, but
  15603. // Lines objects are immutable, so it's perfectly adequate to
  15604. // return the same object.
  15605. return this;
  15606. }
  15607. // Slice to the end if no end position was provided.
  15608. end = this.lastPos();
  15609. }
  15610. if (!start) {
  15611. throw new Error("cannot slice with end but not start");
  15612. }
  15613. var sliced = this.infos.slice(start.line - 1, end.line);
  15614. if (start.line === end.line) {
  15615. sliced[0] = sliceInfo(sliced[0], start.column, end.column);
  15616. }
  15617. else {
  15618. assert_1.default.ok(start.line < end.line);
  15619. sliced[0] = sliceInfo(sliced[0], start.column);
  15620. sliced.push(sliceInfo(sliced.pop(), 0, end.column));
  15621. }
  15622. var lines = new Lines(sliced);
  15623. if (this.mappings.length > 0) {
  15624. var newMappings = lines.mappings;
  15625. assert_1.default.strictEqual(newMappings.length, 0);
  15626. this.mappings.forEach(function (mapping) {
  15627. var sliced = mapping.slice(this, start, end);
  15628. if (sliced) {
  15629. newMappings.push(sliced);
  15630. }
  15631. }, this);
  15632. }
  15633. return lines;
  15634. };
  15635. Lines.prototype.bootstrapSliceString = function (start, end, options) {
  15636. return this.slice(start, end).toString(options);
  15637. };
  15638. Lines.prototype.sliceString = function (start, end, options$1) {
  15639. if (start === void 0) { start = this.firstPos(); }
  15640. if (end === void 0) { end = this.lastPos(); }
  15641. options$1 = options.normalize(options$1);
  15642. var parts = [];
  15643. var _a = options$1.tabWidth, tabWidth = _a === void 0 ? 2 : _a;
  15644. for (var line = start.line; line <= end.line; ++line) {
  15645. var info = this.infos[line - 1];
  15646. if (line === start.line) {
  15647. if (line === end.line) {
  15648. info = sliceInfo(info, start.column, end.column);
  15649. }
  15650. else {
  15651. info = sliceInfo(info, start.column);
  15652. }
  15653. }
  15654. else if (line === end.line) {
  15655. info = sliceInfo(info, 0, end.column);
  15656. }
  15657. var indent = Math.max(info.indent, 0);
  15658. var before = info.line.slice(0, info.sliceStart);
  15659. if (options$1.reuseWhitespace &&
  15660. isOnlyWhitespace(before) &&
  15661. countSpaces(before, options$1.tabWidth) === indent) {
  15662. // Reuse original spaces if the indentation is correct.
  15663. parts.push(info.line.slice(0, info.sliceEnd));
  15664. continue;
  15665. }
  15666. var tabs = 0;
  15667. var spaces = indent;
  15668. if (options$1.useTabs) {
  15669. tabs = Math.floor(indent / tabWidth);
  15670. spaces -= tabs * tabWidth;
  15671. }
  15672. var result = "";
  15673. if (tabs > 0) {
  15674. result += new Array(tabs + 1).join("\t");
  15675. }
  15676. if (spaces > 0) {
  15677. result += new Array(spaces + 1).join(" ");
  15678. }
  15679. result += info.line.slice(info.sliceStart, info.sliceEnd);
  15680. parts.push(result);
  15681. }
  15682. return parts.join(options$1.lineTerminator);
  15683. };
  15684. Lines.prototype.isEmpty = function () {
  15685. return this.length < 2 && this.getLineLength(1) < 1;
  15686. };
  15687. Lines.prototype.join = function (elements) {
  15688. var separator = this;
  15689. var infos = [];
  15690. var mappings = [];
  15691. var prevInfo;
  15692. function appendLines(linesOrNull) {
  15693. if (linesOrNull === null) {
  15694. return;
  15695. }
  15696. if (prevInfo) {
  15697. var info = linesOrNull.infos[0];
  15698. var indent = new Array(info.indent + 1).join(" ");
  15699. var prevLine = infos.length;
  15700. var prevColumn = Math.max(prevInfo.indent, 0) +
  15701. prevInfo.sliceEnd - prevInfo.sliceStart;
  15702. prevInfo.line = prevInfo.line.slice(0, prevInfo.sliceEnd) + indent + info.line.slice(info.sliceStart, info.sliceEnd);
  15703. // If any part of a line is indentation-locked, the whole line
  15704. // will be indentation-locked.
  15705. prevInfo.locked = prevInfo.locked || info.locked;
  15706. prevInfo.sliceEnd = prevInfo.line.length;
  15707. if (linesOrNull.mappings.length > 0) {
  15708. linesOrNull.mappings.forEach(function (mapping) {
  15709. mappings.push(mapping.add(prevLine, prevColumn));
  15710. });
  15711. }
  15712. }
  15713. else if (linesOrNull.mappings.length > 0) {
  15714. mappings.push.apply(mappings, linesOrNull.mappings);
  15715. }
  15716. linesOrNull.infos.forEach(function (info, i) {
  15717. if (!prevInfo || i > 0) {
  15718. prevInfo = __assign({}, info);
  15719. infos.push(prevInfo);
  15720. }
  15721. });
  15722. }
  15723. function appendWithSeparator(linesOrNull, i) {
  15724. if (i > 0)
  15725. appendLines(separator);
  15726. appendLines(linesOrNull);
  15727. }
  15728. elements.map(function (elem) {
  15729. var lines = fromString(elem);
  15730. if (lines.isEmpty())
  15731. return null;
  15732. return lines;
  15733. }).forEach(function (linesOrNull, i) {
  15734. if (separator.isEmpty()) {
  15735. appendLines(linesOrNull);
  15736. }
  15737. else {
  15738. appendWithSeparator(linesOrNull, i);
  15739. }
  15740. });
  15741. if (infos.length < 1)
  15742. return emptyLines;
  15743. var lines = new Lines(infos);
  15744. lines.mappings = mappings;
  15745. return lines;
  15746. };
  15747. Lines.prototype.concat = function () {
  15748. var args = [];
  15749. for (var _i = 0; _i < arguments.length; _i++) {
  15750. args[_i] = arguments[_i];
  15751. }
  15752. var list = [this];
  15753. list.push.apply(list, args);
  15754. assert_1.default.strictEqual(list.length, args.length + 1);
  15755. return emptyLines.join(list);
  15756. };
  15757. return Lines;
  15758. }());
  15759. exports.Lines = Lines;
  15760. var fromStringCache = {};
  15761. var hasOwn = fromStringCache.hasOwnProperty;
  15762. var maxCacheKeyLen = 10;
  15763. function countSpaces(spaces, tabWidth) {
  15764. var count = 0;
  15765. var len = spaces.length;
  15766. for (var i = 0; i < len; ++i) {
  15767. switch (spaces.charCodeAt(i)) {
  15768. case 9: // '\t'
  15769. assert_1.default.strictEqual(typeof tabWidth, "number");
  15770. assert_1.default.ok(tabWidth > 0);
  15771. var next = Math.ceil(count / tabWidth) * tabWidth;
  15772. if (next === count) {
  15773. count += tabWidth;
  15774. }
  15775. else {
  15776. count = next;
  15777. }
  15778. break;
  15779. case 11: // '\v'
  15780. case 12: // '\f'
  15781. case 13: // '\r'
  15782. case 0xfeff: // zero-width non-breaking space
  15783. // These characters contribute nothing to indentation.
  15784. break;
  15785. case 32: // ' '
  15786. default: // Treat all other whitespace like ' '.
  15787. count += 1;
  15788. break;
  15789. }
  15790. }
  15791. return count;
  15792. }
  15793. exports.countSpaces = countSpaces;
  15794. var leadingSpaceExp = /^\s*/;
  15795. // As specified here: http://www.ecma-international.org/ecma-262/6.0/#sec-line-terminators
  15796. var lineTerminatorSeqExp = /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/;
  15797. /**
  15798. * @param {Object} options - Options object that configures printing.
  15799. */
  15800. function fromString(string, options$1) {
  15801. if (string instanceof Lines)
  15802. return string;
  15803. string += "";
  15804. var tabWidth = options$1 && options$1.tabWidth;
  15805. var tabless = string.indexOf("\t") < 0;
  15806. var cacheable = !options$1 && tabless && (string.length <= maxCacheKeyLen);
  15807. assert_1.default.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string);
  15808. if (cacheable && hasOwn.call(fromStringCache, string))
  15809. return fromStringCache[string];
  15810. var lines = new Lines(string.split(lineTerminatorSeqExp).map(function (line) {
  15811. // TODO: handle null exec result
  15812. var spaces = leadingSpaceExp.exec(line)[0];
  15813. return {
  15814. line: line,
  15815. indent: countSpaces(spaces, tabWidth),
  15816. // Boolean indicating whether this line can be reindented.
  15817. locked: false,
  15818. sliceStart: spaces.length,
  15819. sliceEnd: line.length
  15820. };
  15821. }), options.normalize(options$1).sourceFileName);
  15822. if (cacheable)
  15823. fromStringCache[string] = lines;
  15824. return lines;
  15825. }
  15826. exports.fromString = fromString;
  15827. function isOnlyWhitespace(string) {
  15828. return !/\S/.test(string);
  15829. }
  15830. function sliceInfo(info, startCol, endCol) {
  15831. var sliceStart = info.sliceStart;
  15832. var sliceEnd = info.sliceEnd;
  15833. var indent = Math.max(info.indent, 0);
  15834. var lineLength = indent + sliceEnd - sliceStart;
  15835. if (typeof endCol === "undefined") {
  15836. endCol = lineLength;
  15837. }
  15838. startCol = Math.max(startCol, 0);
  15839. endCol = Math.min(endCol, lineLength);
  15840. endCol = Math.max(endCol, startCol);
  15841. if (endCol < indent) {
  15842. indent = endCol;
  15843. sliceEnd = sliceStart;
  15844. }
  15845. else {
  15846. sliceEnd -= lineLength - endCol;
  15847. }
  15848. lineLength = endCol;
  15849. lineLength -= startCol;
  15850. if (startCol < indent) {
  15851. indent -= startCol;
  15852. }
  15853. else {
  15854. startCol -= indent;
  15855. indent = 0;
  15856. sliceStart += startCol;
  15857. }
  15858. assert_1.default.ok(indent >= 0);
  15859. assert_1.default.ok(sliceStart <= sliceEnd);
  15860. assert_1.default.strictEqual(lineLength, indent + sliceEnd - sliceStart);
  15861. if (info.indent === indent &&
  15862. info.sliceStart === sliceStart &&
  15863. info.sliceEnd === sliceEnd) {
  15864. return info;
  15865. }
  15866. return {
  15867. line: info.line,
  15868. indent: indent,
  15869. // A destructive slice always unlocks indentation.
  15870. locked: false,
  15871. sliceStart: sliceStart,
  15872. sliceEnd: sliceEnd
  15873. };
  15874. }
  15875. function concat(elements) {
  15876. return emptyLines.join(elements);
  15877. }
  15878. exports.concat = concat;
  15879. // The emptyLines object needs to be created all the way down here so that
  15880. // Lines.prototype will be fully populated.
  15881. var emptyLines = fromString("");
  15882. });
  15883. unwrapExports(lines);
  15884. var lines_1 = lines.Lines;
  15885. var lines_2 = lines.countSpaces;
  15886. var lines_3 = lines.fromString;
  15887. var lines_4 = lines.concat;
  15888. var originalObject = Object;
  15889. var originalDefProp = Object.defineProperty;
  15890. var originalCreate = Object.create;
  15891. function defProp(obj, name, value) {
  15892. if (originalDefProp) try {
  15893. originalDefProp.call(originalObject, obj, name, { value: value });
  15894. } catch (definePropertyIsBrokenInIE8) {
  15895. obj[name] = value;
  15896. } else {
  15897. obj[name] = value;
  15898. }
  15899. }
  15900. // For functions that will be invoked using .call or .apply, we need to
  15901. // define those methods on the function objects themselves, rather than
  15902. // inheriting them from Function.prototype, so that a malicious or clumsy
  15903. // third party cannot interfere with the functionality of this module by
  15904. // redefining Function.prototype.call or .apply.
  15905. function makeSafeToCall(fun) {
  15906. if (fun) {
  15907. defProp(fun, "call", fun.call);
  15908. defProp(fun, "apply", fun.apply);
  15909. }
  15910. return fun;
  15911. }
  15912. makeSafeToCall(originalDefProp);
  15913. makeSafeToCall(originalCreate);
  15914. var hasOwn$1 = makeSafeToCall(Object.prototype.hasOwnProperty);
  15915. var numToStr = makeSafeToCall(Number.prototype.toString);
  15916. var strSlice = makeSafeToCall(String.prototype.slice);
  15917. var cloner = function(){};
  15918. function create(prototype) {
  15919. if (originalCreate) {
  15920. return originalCreate.call(originalObject, prototype);
  15921. }
  15922. cloner.prototype = prototype || null;
  15923. return new cloner;
  15924. }
  15925. var rand = Math.random;
  15926. var uniqueKeys = create(null);
  15927. function makeUniqueKey() {
  15928. // Collisions are highly unlikely, but this module is in the business of
  15929. // making guarantees rather than safe bets.
  15930. do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2));
  15931. while (hasOwn$1.call(uniqueKeys, uniqueKey));
  15932. return uniqueKeys[uniqueKey] = uniqueKey;
  15933. }
  15934. function internString(str) {
  15935. var obj = {};
  15936. obj[str] = true;
  15937. return Object.keys(obj)[0];
  15938. }
  15939. // External users might find this function useful, but it is not necessary
  15940. // for the typical use of this module.
  15941. var makeUniqueKey_1 = makeUniqueKey;
  15942. // Object.getOwnPropertyNames is the only way to enumerate non-enumerable
  15943. // properties, so if we wrap it to ignore our secret keys, there should be
  15944. // no way (except guessing) to access those properties.
  15945. var originalGetOPNs = Object.getOwnPropertyNames;
  15946. Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
  15947. for (var names = originalGetOPNs(object),
  15948. src = 0,
  15949. dst = 0,
  15950. len = names.length;
  15951. src < len;
  15952. ++src) {
  15953. if (!hasOwn$1.call(uniqueKeys, names[src])) {
  15954. if (src > dst) {
  15955. names[dst] = names[src];
  15956. }
  15957. ++dst;
  15958. }
  15959. }
  15960. names.length = dst;
  15961. return names;
  15962. };
  15963. function defaultCreatorFn(object) {
  15964. return create(null);
  15965. }
  15966. function makeAccessor(secretCreatorFn) {
  15967. var brand = makeUniqueKey();
  15968. var passkey = create(null);
  15969. secretCreatorFn = secretCreatorFn || defaultCreatorFn;
  15970. function register(object) {
  15971. var secret; // Created lazily.
  15972. function vault(key, forget) {
  15973. // Only code that has access to the passkey can retrieve (or forget)
  15974. // the secret object.
  15975. if (key === passkey) {
  15976. return forget
  15977. ? secret = null
  15978. : secret || (secret = secretCreatorFn(object));
  15979. }
  15980. }
  15981. defProp(object, brand, vault);
  15982. }
  15983. function accessor(object) {
  15984. if (!hasOwn$1.call(object, brand))
  15985. register(object);
  15986. return object[brand](passkey);
  15987. }
  15988. accessor.forget = function(object) {
  15989. if (hasOwn$1.call(object, brand))
  15990. object[brand](passkey, true);
  15991. };
  15992. return accessor;
  15993. }
  15994. var makeAccessor_1 = makeAccessor;
  15995. var _private = {
  15996. makeUniqueKey: makeUniqueKey_1,
  15997. makeAccessor: makeAccessor_1
  15998. };
  15999. var comments = createCommonjsModule(function (module, exports) {
  16000. var __importDefault = (this && this.__importDefault) || function (mod) {
  16001. return (mod && mod.__esModule) ? mod : { "default": mod };
  16002. };
  16003. var __importStar = (this && this.__importStar) || function (mod) {
  16004. if (mod && mod.__esModule) return mod;
  16005. var result = {};
  16006. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  16007. result["default"] = mod;
  16008. return result;
  16009. };
  16010. Object.defineProperty(exports, "__esModule", { value: true });
  16011. var assert_1 = __importDefault(assert);
  16012. var types = __importStar(main);
  16013. var n = types.namedTypes;
  16014. var isArray = types.builtInTypes.array;
  16015. var isObject = types.builtInTypes.object;
  16016. var childNodesCacheKey = _private.makeUniqueKey();
  16017. // TODO Move a non-caching implementation of this function into ast-types,
  16018. // and implement a caching wrapper function here.
  16019. function getSortedChildNodes(node, lines, resultArray) {
  16020. if (!node) {
  16021. return;
  16022. }
  16023. // The .loc checks below are sensitive to some of the problems that
  16024. // are fixed by this utility function. Specifically, if it decides to
  16025. // set node.loc to null, indicating that the node's .loc information
  16026. // is unreliable, then we don't want to add node to the resultArray.
  16027. util$1.fixFaultyLocations(node, lines);
  16028. if (resultArray) {
  16029. if (n.Node.check(node) &&
  16030. n.SourceLocation.check(node.loc)) {
  16031. // This reverse insertion sort almost always takes constant
  16032. // time because we almost always (maybe always?) append the
  16033. // nodes in order anyway.
  16034. for (var i = resultArray.length - 1; i >= 0; --i) {
  16035. if (util$1.comparePos(resultArray[i].loc.end, node.loc.start) <= 0) {
  16036. break;
  16037. }
  16038. }
  16039. resultArray.splice(i + 1, 0, node);
  16040. return;
  16041. }
  16042. }
  16043. else if (node[childNodesCacheKey]) {
  16044. return node[childNodesCacheKey];
  16045. }
  16046. var names;
  16047. if (isArray.check(node)) {
  16048. names = Object.keys(node);
  16049. }
  16050. else if (isObject.check(node)) {
  16051. names = types.getFieldNames(node);
  16052. }
  16053. else {
  16054. return;
  16055. }
  16056. if (!resultArray) {
  16057. Object.defineProperty(node, childNodesCacheKey, {
  16058. value: resultArray = [],
  16059. enumerable: false
  16060. });
  16061. }
  16062. for (var i = 0, nameCount = names.length; i < nameCount; ++i) {
  16063. getSortedChildNodes(node[names[i]], lines, resultArray);
  16064. }
  16065. return resultArray;
  16066. }
  16067. // As efficiently as possible, decorate the comment object with
  16068. // .precedingNode, .enclosingNode, and/or .followingNode properties, at
  16069. // least one of which is guaranteed to be defined.
  16070. function decorateComment(node, comment, lines) {
  16071. var childNodes = getSortedChildNodes(node, lines);
  16072. // Time to dust off the old binary search robes and wizard hat.
  16073. var left = 0, right = childNodes.length;
  16074. while (left < right) {
  16075. var middle = (left + right) >> 1;
  16076. var child = childNodes[middle];
  16077. if (util$1.comparePos(child.loc.start, comment.loc.start) <= 0 &&
  16078. util$1.comparePos(comment.loc.end, child.loc.end) <= 0) {
  16079. // The comment is completely contained by this child node.
  16080. decorateComment(comment.enclosingNode = child, comment, lines);
  16081. return; // Abandon the binary search at this level.
  16082. }
  16083. if (util$1.comparePos(child.loc.end, comment.loc.start) <= 0) {
  16084. // This child node falls completely before the comment.
  16085. // Because we will never consider this node or any nodes
  16086. // before it again, this node must be the closest preceding
  16087. // node we have encountered so far.
  16088. var precedingNode = child;
  16089. left = middle + 1;
  16090. continue;
  16091. }
  16092. if (util$1.comparePos(comment.loc.end, child.loc.start) <= 0) {
  16093. // This child node falls completely after the comment.
  16094. // Because we will never consider this node or any nodes after
  16095. // it again, this node must be the closest following node we
  16096. // have encountered so far.
  16097. var followingNode = child;
  16098. right = middle;
  16099. continue;
  16100. }
  16101. throw new Error("Comment location overlaps with node location");
  16102. }
  16103. if (precedingNode) {
  16104. comment.precedingNode = precedingNode;
  16105. }
  16106. if (followingNode) {
  16107. comment.followingNode = followingNode;
  16108. }
  16109. }
  16110. function attach(comments, ast, lines) {
  16111. if (!isArray.check(comments)) {
  16112. return;
  16113. }
  16114. var tiesToBreak = [];
  16115. comments.forEach(function (comment) {
  16116. comment.loc.lines = lines;
  16117. decorateComment(ast, comment, lines);
  16118. var pn = comment.precedingNode;
  16119. var en = comment.enclosingNode;
  16120. var fn = comment.followingNode;
  16121. if (pn && fn) {
  16122. var tieCount = tiesToBreak.length;
  16123. if (tieCount > 0) {
  16124. var lastTie = tiesToBreak[tieCount - 1];
  16125. assert_1.default.strictEqual(lastTie.precedingNode === comment.precedingNode, lastTie.followingNode === comment.followingNode);
  16126. if (lastTie.followingNode !== comment.followingNode) {
  16127. breakTies(tiesToBreak, lines);
  16128. }
  16129. }
  16130. tiesToBreak.push(comment);
  16131. }
  16132. else if (pn) {
  16133. // No contest: we have a trailing comment.
  16134. breakTies(tiesToBreak, lines);
  16135. addTrailingComment(pn, comment);
  16136. }
  16137. else if (fn) {
  16138. // No contest: we have a leading comment.
  16139. breakTies(tiesToBreak, lines);
  16140. addLeadingComment(fn, comment);
  16141. }
  16142. else if (en) {
  16143. // The enclosing node has no child nodes at all, so what we
  16144. // have here is a dangling comment, e.g. [/* crickets */].
  16145. breakTies(tiesToBreak, lines);
  16146. addDanglingComment(en, comment);
  16147. }
  16148. else {
  16149. throw new Error("AST contains no nodes at all?");
  16150. }
  16151. });
  16152. breakTies(tiesToBreak, lines);
  16153. comments.forEach(function (comment) {
  16154. // These node references were useful for breaking ties, but we
  16155. // don't need them anymore, and they create cycles in the AST that
  16156. // may lead to infinite recursion if we don't delete them here.
  16157. delete comment.precedingNode;
  16158. delete comment.enclosingNode;
  16159. delete comment.followingNode;
  16160. });
  16161. }
  16162. exports.attach = attach;
  16163. function breakTies(tiesToBreak, lines) {
  16164. var tieCount = tiesToBreak.length;
  16165. if (tieCount === 0) {
  16166. return;
  16167. }
  16168. var pn = tiesToBreak[0].precedingNode;
  16169. var fn = tiesToBreak[0].followingNode;
  16170. var gapEndPos = fn.loc.start;
  16171. // Iterate backwards through tiesToBreak, examining the gaps
  16172. // between the tied comments. In order to qualify as leading, a
  16173. // comment must be separated from fn by an unbroken series of
  16174. // whitespace-only gaps (or other comments).
  16175. for (var indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
  16176. var comment = tiesToBreak[indexOfFirstLeadingComment - 1];
  16177. assert_1.default.strictEqual(comment.precedingNode, pn);
  16178. assert_1.default.strictEqual(comment.followingNode, fn);
  16179. var gap = lines.sliceString(comment.loc.end, gapEndPos);
  16180. if (/\S/.test(gap)) {
  16181. // The gap string contained something other than whitespace.
  16182. break;
  16183. }
  16184. gapEndPos = comment.loc.start;
  16185. }
  16186. while (indexOfFirstLeadingComment <= tieCount &&
  16187. (comment = tiesToBreak[indexOfFirstLeadingComment]) &&
  16188. // If the comment is a //-style comment and indented more
  16189. // deeply than the node itself, reconsider it as trailing.
  16190. (comment.type === "Line" || comment.type === "CommentLine") &&
  16191. comment.loc.start.column > fn.loc.start.column) {
  16192. ++indexOfFirstLeadingComment;
  16193. }
  16194. tiesToBreak.forEach(function (comment, i) {
  16195. if (i < indexOfFirstLeadingComment) {
  16196. addTrailingComment(pn, comment);
  16197. }
  16198. else {
  16199. addLeadingComment(fn, comment);
  16200. }
  16201. });
  16202. tiesToBreak.length = 0;
  16203. }
  16204. function addCommentHelper(node, comment) {
  16205. var comments = node.comments || (node.comments = []);
  16206. comments.push(comment);
  16207. }
  16208. function addLeadingComment(node, comment) {
  16209. comment.leading = true;
  16210. comment.trailing = false;
  16211. addCommentHelper(node, comment);
  16212. }
  16213. function addDanglingComment(node, comment) {
  16214. comment.leading = false;
  16215. comment.trailing = false;
  16216. addCommentHelper(node, comment);
  16217. }
  16218. function addTrailingComment(node, comment) {
  16219. comment.leading = false;
  16220. comment.trailing = true;
  16221. addCommentHelper(node, comment);
  16222. }
  16223. function printLeadingComment(commentPath, print) {
  16224. var comment = commentPath.getValue();
  16225. n.Comment.assert(comment);
  16226. var loc = comment.loc;
  16227. var lines$1 = loc && loc.lines;
  16228. var parts = [print(commentPath)];
  16229. if (comment.trailing) {
  16230. // When we print trailing comments as leading comments, we don't
  16231. // want to bring any trailing spaces along.
  16232. parts.push("\n");
  16233. }
  16234. else if (lines$1 instanceof lines.Lines) {
  16235. var trailingSpace = lines$1.slice(loc.end, lines$1.skipSpaces(loc.end) || lines$1.lastPos());
  16236. if (trailingSpace.length === 1) {
  16237. // If the trailing space contains no newlines, then we want to
  16238. // preserve it exactly as we found it.
  16239. parts.push(trailingSpace);
  16240. }
  16241. else {
  16242. // If the trailing space contains newlines, then replace it
  16243. // with just that many newlines, with all other spaces removed.
  16244. parts.push(new Array(trailingSpace.length).join("\n"));
  16245. }
  16246. }
  16247. else {
  16248. parts.push("\n");
  16249. }
  16250. return lines.concat(parts);
  16251. }
  16252. function printTrailingComment(commentPath, print) {
  16253. var comment = commentPath.getValue(commentPath);
  16254. n.Comment.assert(comment);
  16255. var loc = comment.loc;
  16256. var lines$1 = loc && loc.lines;
  16257. var parts = [];
  16258. if (lines$1 instanceof lines.Lines) {
  16259. var fromPos = lines$1.skipSpaces(loc.start, true) || lines$1.firstPos();
  16260. var leadingSpace = lines$1.slice(fromPos, loc.start);
  16261. if (leadingSpace.length === 1) {
  16262. // If the leading space contains no newlines, then we want to
  16263. // preserve it exactly as we found it.
  16264. parts.push(leadingSpace);
  16265. }
  16266. else {
  16267. // If the leading space contains newlines, then replace it
  16268. // with just that many newlines, sans all other spaces.
  16269. parts.push(new Array(leadingSpace.length).join("\n"));
  16270. }
  16271. }
  16272. parts.push(print(commentPath));
  16273. return lines.concat(parts);
  16274. }
  16275. function printComments(path, print) {
  16276. var value = path.getValue();
  16277. var innerLines = print(path);
  16278. var comments = n.Node.check(value) &&
  16279. types.getFieldValue(value, "comments");
  16280. if (!comments || comments.length === 0) {
  16281. return innerLines;
  16282. }
  16283. var leadingParts = [];
  16284. var trailingParts = [innerLines];
  16285. path.each(function (commentPath) {
  16286. var comment = commentPath.getValue();
  16287. var leading = types.getFieldValue(comment, "leading");
  16288. var trailing = types.getFieldValue(comment, "trailing");
  16289. if (leading || (trailing && !(n.Statement.check(value) ||
  16290. comment.type === "Block" ||
  16291. comment.type === "CommentBlock"))) {
  16292. leadingParts.push(printLeadingComment(commentPath, print));
  16293. }
  16294. else if (trailing) {
  16295. trailingParts.push(printTrailingComment(commentPath, print));
  16296. }
  16297. }, "comments");
  16298. leadingParts.push.apply(leadingParts, trailingParts);
  16299. return lines.concat(leadingParts);
  16300. }
  16301. exports.printComments = printComments;
  16302. });
  16303. unwrapExports(comments);
  16304. var comments_1 = comments.attach;
  16305. var comments_2 = comments.printComments;
  16306. var parser = createCommonjsModule(function (module, exports) {
  16307. var __importDefault = (this && this.__importDefault) || function (mod) {
  16308. return (mod && mod.__esModule) ? mod : { "default": mod };
  16309. };
  16310. var __importStar = (this && this.__importStar) || function (mod) {
  16311. if (mod && mod.__esModule) return mod;
  16312. var result = {};
  16313. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  16314. result["default"] = mod;
  16315. return result;
  16316. };
  16317. Object.defineProperty(exports, "__esModule", { value: true });
  16318. var assert_1 = __importDefault(assert);
  16319. var types = __importStar(main);
  16320. var b = types.builders;
  16321. var isObject = types.builtInTypes.object;
  16322. var isArray = types.builtInTypes.array;
  16323. var util = __importStar(util$1);
  16324. function parse(source, options$1) {
  16325. options$1 = options.normalize(options$1);
  16326. var lines$1 = lines.fromString(source, options$1);
  16327. var sourceWithoutTabs = lines$1.toString({
  16328. tabWidth: options$1.tabWidth,
  16329. reuseWhitespace: false,
  16330. useTabs: false
  16331. });
  16332. var comments$1 = [];
  16333. var ast = options$1.parser.parse(sourceWithoutTabs, {
  16334. jsx: true,
  16335. loc: true,
  16336. locations: true,
  16337. range: options$1.range,
  16338. comment: true,
  16339. onComment: comments$1,
  16340. tolerant: util.getOption(options$1, "tolerant", true),
  16341. ecmaVersion: 6,
  16342. sourceType: util.getOption(options$1, "sourceType", "module")
  16343. });
  16344. // Use ast.tokens if possible, and otherwise fall back to the Esprima
  16345. // tokenizer. All the preconfigured ../parsers/* expose ast.tokens
  16346. // automatically, but custom parsers might need additional configuration
  16347. // to avoid this fallback.
  16348. var tokens = Array.isArray(ast.tokens)
  16349. ? ast.tokens
  16350. : esprima$1.tokenize(sourceWithoutTabs, {
  16351. loc: true
  16352. });
  16353. // We will reattach the tokens array to the file object below.
  16354. delete ast.tokens;
  16355. // Make sure every token has a token.value string.
  16356. tokens.forEach(function (token) {
  16357. if (typeof token.value !== "string") {
  16358. token.value = lines$1.sliceString(token.loc.start, token.loc.end);
  16359. }
  16360. });
  16361. if (Array.isArray(ast.comments)) {
  16362. comments$1 = ast.comments;
  16363. delete ast.comments;
  16364. }
  16365. if (ast.loc) {
  16366. // If the source was empty, some parsers give loc.{start,end}.line
  16367. // values of 0, instead of the minimum of 1.
  16368. util.fixFaultyLocations(ast, lines$1);
  16369. }
  16370. else {
  16371. ast.loc = {
  16372. start: lines$1.firstPos(),
  16373. end: lines$1.lastPos()
  16374. };
  16375. }
  16376. ast.loc.lines = lines$1;
  16377. ast.loc.indent = 0;
  16378. var file;
  16379. var program;
  16380. if (ast.type === "Program") {
  16381. program = ast;
  16382. // In order to ensure we reprint leading and trailing program
  16383. // comments, wrap the original Program node with a File node. Only
  16384. // ESTree parsers (Acorn and Esprima) return a Program as the root AST
  16385. // node. Most other (Babylon-like) parsers return a File.
  16386. file = b.file(ast, options$1.sourceFileName || null);
  16387. file.loc = {
  16388. start: lines$1.firstPos(),
  16389. end: lines$1.lastPos(),
  16390. lines: lines$1,
  16391. indent: 0
  16392. };
  16393. }
  16394. else if (ast.type === "File") {
  16395. file = ast;
  16396. program = file.program;
  16397. }
  16398. // Expose file.tokens unless the caller passed false for options.tokens.
  16399. if (options$1.tokens) {
  16400. file.tokens = tokens;
  16401. }
  16402. // Expand the Program's .loc to include all comments (not just those
  16403. // attached to the Program node, as its children may have comments as
  16404. // well), since sometimes program.loc.{start,end} will coincide with the
  16405. // .loc.{start,end} of the first and last *statements*, mistakenly
  16406. // excluding comments that fall outside that region.
  16407. var trueProgramLoc = util.getTrueLoc({
  16408. type: program.type,
  16409. loc: program.loc,
  16410. body: [],
  16411. comments: comments$1
  16412. }, lines$1);
  16413. program.loc.start = trueProgramLoc.start;
  16414. program.loc.end = trueProgramLoc.end;
  16415. // Passing file.program here instead of just file means that initial
  16416. // comments will be attached to program.body[0] instead of program.
  16417. comments.attach(comments$1, program.body.length ? file.program : file, lines$1);
  16418. // Return a copy of the original AST so that any changes made may be
  16419. // compared to the original.
  16420. return new TreeCopier(lines$1, tokens).copy(file);
  16421. }
  16422. exports.parse = parse;
  16423. var TreeCopier = function TreeCopier(lines, tokens) {
  16424. assert_1.default.ok(this instanceof TreeCopier);
  16425. this.lines = lines;
  16426. this.tokens = tokens;
  16427. this.startTokenIndex = 0;
  16428. this.endTokenIndex = tokens.length;
  16429. this.indent = 0;
  16430. this.seen = new Map;
  16431. };
  16432. var TCp = TreeCopier.prototype;
  16433. TCp.copy = function (node) {
  16434. if (this.seen.has(node)) {
  16435. return this.seen.get(node);
  16436. }
  16437. if (isArray.check(node)) {
  16438. var copy = new Array(node.length);
  16439. this.seen.set(node, copy);
  16440. node.forEach(function (item, i) {
  16441. copy[i] = this.copy(item);
  16442. }, this);
  16443. return copy;
  16444. }
  16445. if (!isObject.check(node)) {
  16446. return node;
  16447. }
  16448. util.fixFaultyLocations(node, this.lines);
  16449. var copy = Object.create(Object.getPrototypeOf(node), {
  16450. original: {
  16451. value: node,
  16452. configurable: false,
  16453. enumerable: false,
  16454. writable: true
  16455. }
  16456. });
  16457. this.seen.set(node, copy);
  16458. var loc = node.loc;
  16459. var oldIndent = this.indent;
  16460. var newIndent = oldIndent;
  16461. var oldStartTokenIndex = this.startTokenIndex;
  16462. var oldEndTokenIndex = this.endTokenIndex;
  16463. if (loc) {
  16464. // When node is a comment, we set node.loc.indent to
  16465. // node.loc.start.column so that, when/if we print the comment by
  16466. // itself, we can strip that much whitespace from the left margin of
  16467. // the comment. This only really matters for multiline Block comments,
  16468. // but it doesn't hurt for Line comments.
  16469. if (node.type === "Block" || node.type === "Line" ||
  16470. node.type === "CommentBlock" || node.type === "CommentLine" ||
  16471. this.lines.isPrecededOnlyByWhitespace(loc.start)) {
  16472. newIndent = this.indent = loc.start.column;
  16473. }
  16474. // Every node.loc has a reference to the original source lines as well
  16475. // as a complete list of source tokens.
  16476. loc.lines = this.lines;
  16477. loc.tokens = this.tokens;
  16478. loc.indent = newIndent;
  16479. // Set loc.start.token and loc.end.token such that
  16480. // loc.tokens.slice(loc.start.token, loc.end.token) returns a list of
  16481. // all the tokens that make up this node.
  16482. this.findTokenRange(loc);
  16483. }
  16484. var keys = Object.keys(node);
  16485. var keyCount = keys.length;
  16486. for (var i = 0; i < keyCount; ++i) {
  16487. var key = keys[i];
  16488. if (key === "loc") {
  16489. copy[key] = node[key];
  16490. }
  16491. else if (key === "tokens" &&
  16492. node.type === "File") {
  16493. // Preserve file.tokens (uncopied) in case client code cares about
  16494. // it, even though Recast ignores it when reprinting.
  16495. copy[key] = node[key];
  16496. }
  16497. else {
  16498. copy[key] = this.copy(node[key]);
  16499. }
  16500. }
  16501. this.indent = oldIndent;
  16502. this.startTokenIndex = oldStartTokenIndex;
  16503. this.endTokenIndex = oldEndTokenIndex;
  16504. return copy;
  16505. };
  16506. // If we didn't have any idea where in loc.tokens to look for tokens
  16507. // contained by this loc, a binary search would be appropriate, but
  16508. // because we maintain this.startTokenIndex and this.endTokenIndex as we
  16509. // traverse the AST, we only need to make small (linear) adjustments to
  16510. // those indexes with each recursive iteration.
  16511. TCp.findTokenRange = function (loc) {
  16512. // In the unlikely event that loc.tokens[this.startTokenIndex] starts
  16513. // *after* loc.start, we need to rewind this.startTokenIndex first.
  16514. while (this.startTokenIndex > 0) {
  16515. var token = loc.tokens[this.startTokenIndex];
  16516. if (util.comparePos(loc.start, token.loc.start) < 0) {
  16517. --this.startTokenIndex;
  16518. }
  16519. else
  16520. break;
  16521. }
  16522. // In the unlikely event that loc.tokens[this.endTokenIndex - 1] ends
  16523. // *before* loc.end, we need to fast-forward this.endTokenIndex first.
  16524. while (this.endTokenIndex < loc.tokens.length) {
  16525. var token = loc.tokens[this.endTokenIndex];
  16526. if (util.comparePos(token.loc.end, loc.end) < 0) {
  16527. ++this.endTokenIndex;
  16528. }
  16529. else
  16530. break;
  16531. }
  16532. // Increment this.startTokenIndex until we've found the first token
  16533. // contained by this node.
  16534. while (this.startTokenIndex < this.endTokenIndex) {
  16535. var token = loc.tokens[this.startTokenIndex];
  16536. if (util.comparePos(token.loc.start, loc.start) < 0) {
  16537. ++this.startTokenIndex;
  16538. }
  16539. else
  16540. break;
  16541. }
  16542. // Index into loc.tokens of the first token within this node.
  16543. loc.start.token = this.startTokenIndex;
  16544. // Decrement this.endTokenIndex until we've found the first token after
  16545. // this node (not contained by the node).
  16546. while (this.endTokenIndex > this.startTokenIndex) {
  16547. var token = loc.tokens[this.endTokenIndex - 1];
  16548. if (util.comparePos(loc.end, token.loc.end) < 0) {
  16549. --this.endTokenIndex;
  16550. }
  16551. else
  16552. break;
  16553. }
  16554. // Index into loc.tokens of the first token *after* this node.
  16555. // If loc.start.token === loc.end.token, the node contains no tokens,
  16556. // and the index is that of the next token following this node.
  16557. loc.end.token = this.endTokenIndex;
  16558. };
  16559. });
  16560. unwrapExports(parser);
  16561. var parser_1 = parser.parse;
  16562. var fastPath = createCommonjsModule(function (module, exports) {
  16563. var __importDefault = (this && this.__importDefault) || function (mod) {
  16564. return (mod && mod.__esModule) ? mod : { "default": mod };
  16565. };
  16566. var __importStar = (this && this.__importStar) || function (mod) {
  16567. if (mod && mod.__esModule) return mod;
  16568. var result = {};
  16569. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  16570. result["default"] = mod;
  16571. return result;
  16572. };
  16573. Object.defineProperty(exports, "__esModule", { value: true });
  16574. var assert_1 = __importDefault(assert);
  16575. var types = __importStar(main);
  16576. var n = types.namedTypes;
  16577. var isArray = types.builtInTypes.array;
  16578. var isNumber = types.builtInTypes.number;
  16579. var util = __importStar(util$1);
  16580. var FastPath = function FastPath(value) {
  16581. assert_1.default.ok(this instanceof FastPath);
  16582. this.stack = [value];
  16583. };
  16584. var FPp = FastPath.prototype;
  16585. // Static convenience function for coercing a value to a FastPath.
  16586. FastPath.from = function (obj) {
  16587. if (obj instanceof FastPath) {
  16588. // Return a defensive copy of any existing FastPath instances.
  16589. return obj.copy();
  16590. }
  16591. if (obj instanceof types.NodePath) {
  16592. // For backwards compatibility, unroll NodePath instances into
  16593. // lightweight FastPath [..., name, value] stacks.
  16594. var copy = Object.create(FastPath.prototype);
  16595. var stack = [obj.value];
  16596. for (var pp; (pp = obj.parentPath); obj = pp)
  16597. stack.push(obj.name, pp.value);
  16598. copy.stack = stack.reverse();
  16599. return copy;
  16600. }
  16601. // Otherwise use obj as the value of the new FastPath instance.
  16602. return new FastPath(obj);
  16603. };
  16604. FPp.copy = function copy() {
  16605. var copy = Object.create(FastPath.prototype);
  16606. copy.stack = this.stack.slice(0);
  16607. return copy;
  16608. };
  16609. // The name of the current property is always the penultimate element of
  16610. // this.stack, and always a String.
  16611. FPp.getName = function getName() {
  16612. var s = this.stack;
  16613. var len = s.length;
  16614. if (len > 1) {
  16615. return s[len - 2];
  16616. }
  16617. // Since the name is always a string, null is a safe sentinel value to
  16618. // return if we do not know the name of the (root) value.
  16619. return null;
  16620. };
  16621. // The value of the current property is always the final element of
  16622. // this.stack.
  16623. FPp.getValue = function getValue() {
  16624. var s = this.stack;
  16625. return s[s.length - 1];
  16626. };
  16627. FPp.valueIsDuplicate = function () {
  16628. var s = this.stack;
  16629. var valueIndex = s.length - 1;
  16630. return s.lastIndexOf(s[valueIndex], valueIndex - 1) >= 0;
  16631. };
  16632. function getNodeHelper(path, count) {
  16633. var s = path.stack;
  16634. for (var i = s.length - 1; i >= 0; i -= 2) {
  16635. var value = s[i];
  16636. if (n.Node.check(value) && --count < 0) {
  16637. return value;
  16638. }
  16639. }
  16640. return null;
  16641. }
  16642. FPp.getNode = function getNode(count) {
  16643. if (count === void 0) { count = 0; }
  16644. return getNodeHelper(this, ~~count);
  16645. };
  16646. FPp.getParentNode = function getParentNode(count) {
  16647. if (count === void 0) { count = 0; }
  16648. return getNodeHelper(this, ~~count + 1);
  16649. };
  16650. // The length of the stack can be either even or odd, depending on whether
  16651. // or not we have a name for the root value. The difference between the
  16652. // index of the root value and the index of the final value is always
  16653. // even, though, which allows us to return the root value in constant time
  16654. // (i.e. without iterating backwards through the stack).
  16655. FPp.getRootValue = function getRootValue() {
  16656. var s = this.stack;
  16657. if (s.length % 2 === 0) {
  16658. return s[1];
  16659. }
  16660. return s[0];
  16661. };
  16662. // Temporarily push properties named by string arguments given after the
  16663. // callback function onto this.stack, then call the callback with a
  16664. // reference to this (modified) FastPath object. Note that the stack will
  16665. // be restored to its original state after the callback is finished, so it
  16666. // is probably a mistake to retain a reference to the path.
  16667. FPp.call = function call(callback /*, name1, name2, ... */) {
  16668. var s = this.stack;
  16669. var origLen = s.length;
  16670. var value = s[origLen - 1];
  16671. var argc = arguments.length;
  16672. for (var i = 1; i < argc; ++i) {
  16673. var name = arguments[i];
  16674. value = value[name];
  16675. s.push(name, value);
  16676. }
  16677. var result = callback(this);
  16678. s.length = origLen;
  16679. return result;
  16680. };
  16681. // Similar to FastPath.prototype.call, except that the value obtained by
  16682. // accessing this.getValue()[name1][name2]... should be array-like. The
  16683. // callback will be called with a reference to this path object for each
  16684. // element of the array.
  16685. FPp.each = function each(callback /*, name1, name2, ... */) {
  16686. var s = this.stack;
  16687. var origLen = s.length;
  16688. var value = s[origLen - 1];
  16689. var argc = arguments.length;
  16690. for (var i = 1; i < argc; ++i) {
  16691. var name = arguments[i];
  16692. value = value[name];
  16693. s.push(name, value);
  16694. }
  16695. for (var i = 0; i < value.length; ++i) {
  16696. if (i in value) {
  16697. s.push(i, value[i]);
  16698. // If the callback needs to know the value of i, call
  16699. // path.getName(), assuming path is the parameter name.
  16700. callback(this);
  16701. s.length -= 2;
  16702. }
  16703. }
  16704. s.length = origLen;
  16705. };
  16706. // Similar to FastPath.prototype.each, except that the results of the
  16707. // callback function invocations are stored in an array and returned at
  16708. // the end of the iteration.
  16709. FPp.map = function map(callback /*, name1, name2, ... */) {
  16710. var s = this.stack;
  16711. var origLen = s.length;
  16712. var value = s[origLen - 1];
  16713. var argc = arguments.length;
  16714. for (var i = 1; i < argc; ++i) {
  16715. var name = arguments[i];
  16716. value = value[name];
  16717. s.push(name, value);
  16718. }
  16719. var result = new Array(value.length);
  16720. for (var i = 0; i < value.length; ++i) {
  16721. if (i in value) {
  16722. s.push(i, value[i]);
  16723. result[i] = callback(this, i);
  16724. s.length -= 2;
  16725. }
  16726. }
  16727. s.length = origLen;
  16728. return result;
  16729. };
  16730. // Returns true if the node at the tip of the path is wrapped with
  16731. // parentheses, OR if the only reason the node needed parentheses was that
  16732. // it couldn't be the first expression in the enclosing statement (see
  16733. // FastPath#canBeFirstInStatement), and it has an opening `(` character.
  16734. // For example, the FunctionExpression in `(function(){}())` appears to
  16735. // need parentheses only because it's the first expression in the AST, but
  16736. // since it happens to be preceded by a `(` (which is not apparent from
  16737. // the AST but can be determined using FastPath#getPrevToken), there is no
  16738. // ambiguity about how to parse it, so it counts as having parentheses,
  16739. // even though it is not immediately followed by a `)`.
  16740. FPp.hasParens = function () {
  16741. var node = this.getNode();
  16742. var prevToken = this.getPrevToken(node);
  16743. if (!prevToken) {
  16744. return false;
  16745. }
  16746. var nextToken = this.getNextToken(node);
  16747. if (!nextToken) {
  16748. return false;
  16749. }
  16750. if (prevToken.value === "(") {
  16751. if (nextToken.value === ")") {
  16752. // If the node preceded by a `(` token and followed by a `)` token,
  16753. // then of course it has parentheses.
  16754. return true;
  16755. }
  16756. // If this is one of the few Expression types that can't come first in
  16757. // the enclosing statement because of parsing ambiguities (namely,
  16758. // FunctionExpression, ObjectExpression, and ClassExpression) and
  16759. // this.firstInStatement() returns true, and the node would not need
  16760. // parentheses in an expression context because this.needsParens(true)
  16761. // returns false, then it just needs an opening parenthesis to resolve
  16762. // the parsing ambiguity that made it appear to need parentheses.
  16763. var justNeedsOpeningParen = !this.canBeFirstInStatement() &&
  16764. this.firstInStatement() &&
  16765. !this.needsParens(true);
  16766. if (justNeedsOpeningParen) {
  16767. return true;
  16768. }
  16769. }
  16770. return false;
  16771. };
  16772. FPp.getPrevToken = function (node) {
  16773. node = node || this.getNode();
  16774. var loc = node && node.loc;
  16775. var tokens = loc && loc.tokens;
  16776. if (tokens && loc.start.token > 0) {
  16777. var token = tokens[loc.start.token - 1];
  16778. if (token) {
  16779. // Do not return tokens that fall outside the root subtree.
  16780. var rootLoc = this.getRootValue().loc;
  16781. if (util.comparePos(rootLoc.start, token.loc.start) <= 0) {
  16782. return token;
  16783. }
  16784. }
  16785. }
  16786. return null;
  16787. };
  16788. FPp.getNextToken = function (node) {
  16789. node = node || this.getNode();
  16790. var loc = node && node.loc;
  16791. var tokens = loc && loc.tokens;
  16792. if (tokens && loc.end.token < tokens.length) {
  16793. var token = tokens[loc.end.token];
  16794. if (token) {
  16795. // Do not return tokens that fall outside the root subtree.
  16796. var rootLoc = this.getRootValue().loc;
  16797. if (util.comparePos(token.loc.end, rootLoc.end) <= 0) {
  16798. return token;
  16799. }
  16800. }
  16801. }
  16802. return null;
  16803. };
  16804. // Inspired by require("ast-types").NodePath.prototype.needsParens, but
  16805. // more efficient because we're iterating backwards through a stack.
  16806. FPp.needsParens = function (assumeExpressionContext) {
  16807. var node = this.getNode();
  16808. // This needs to come before `if (!parent) { return false }` because
  16809. // an object destructuring assignment requires parens for
  16810. // correctness even when it's the topmost expression.
  16811. if (node.type === "AssignmentExpression" && node.left.type === 'ObjectPattern') {
  16812. return true;
  16813. }
  16814. var parent = this.getParentNode();
  16815. if (!parent) {
  16816. return false;
  16817. }
  16818. var name = this.getName();
  16819. // If the value of this path is some child of a Node and not a Node
  16820. // itself, then it doesn't need parentheses. Only Node objects (in fact,
  16821. // only Expression nodes) need parentheses.
  16822. if (this.getValue() !== node) {
  16823. return false;
  16824. }
  16825. // Only statements don't need parentheses.
  16826. if (n.Statement.check(node)) {
  16827. return false;
  16828. }
  16829. // Identifiers never need parentheses.
  16830. if (node.type === "Identifier") {
  16831. return false;
  16832. }
  16833. if (parent.type === "ParenthesizedExpression") {
  16834. return false;
  16835. }
  16836. switch (node.type) {
  16837. case "UnaryExpression":
  16838. case "SpreadElement":
  16839. case "SpreadProperty":
  16840. return parent.type === "MemberExpression"
  16841. && name === "object"
  16842. && parent.object === node;
  16843. case "BinaryExpression":
  16844. case "LogicalExpression":
  16845. switch (parent.type) {
  16846. case "CallExpression":
  16847. return name === "callee"
  16848. && parent.callee === node;
  16849. case "UnaryExpression":
  16850. case "SpreadElement":
  16851. case "SpreadProperty":
  16852. return true;
  16853. case "MemberExpression":
  16854. return name === "object"
  16855. && parent.object === node;
  16856. case "BinaryExpression":
  16857. case "LogicalExpression":
  16858. var po = parent.operator;
  16859. var pp = PRECEDENCE[po];
  16860. var no = node.operator;
  16861. var np = PRECEDENCE[no];
  16862. if (pp > np) {
  16863. return true;
  16864. }
  16865. if (pp === np && name === "right") {
  16866. assert_1.default.strictEqual(parent.right, node);
  16867. return true;
  16868. }
  16869. default:
  16870. return false;
  16871. }
  16872. case "SequenceExpression":
  16873. switch (parent.type) {
  16874. case "ReturnStatement":
  16875. return false;
  16876. case "ForStatement":
  16877. // Although parentheses wouldn't hurt around sequence expressions in
  16878. // the head of for loops, traditional style dictates that e.g. i++,
  16879. // j++ should not be wrapped with parentheses.
  16880. return false;
  16881. case "ExpressionStatement":
  16882. return name !== "expression";
  16883. default:
  16884. // Otherwise err on the side of overparenthesization, adding
  16885. // explicit exceptions above if this proves overzealous.
  16886. return true;
  16887. }
  16888. case "YieldExpression":
  16889. switch (parent.type) {
  16890. case "BinaryExpression":
  16891. case "LogicalExpression":
  16892. case "UnaryExpression":
  16893. case "SpreadElement":
  16894. case "SpreadProperty":
  16895. case "CallExpression":
  16896. case "MemberExpression":
  16897. case "NewExpression":
  16898. case "ConditionalExpression":
  16899. case "YieldExpression":
  16900. return true;
  16901. default:
  16902. return false;
  16903. }
  16904. case "IntersectionTypeAnnotation":
  16905. case "UnionTypeAnnotation":
  16906. return parent.type === "NullableTypeAnnotation";
  16907. case "Literal":
  16908. return parent.type === "MemberExpression"
  16909. && isNumber.check(node.value)
  16910. && name === "object"
  16911. && parent.object === node;
  16912. // Babel 6 Literal split
  16913. case "NumericLiteral":
  16914. return parent.type === "MemberExpression"
  16915. && name === "object"
  16916. && parent.object === node;
  16917. case "AssignmentExpression":
  16918. case "ConditionalExpression":
  16919. switch (parent.type) {
  16920. case "UnaryExpression":
  16921. case "SpreadElement":
  16922. case "SpreadProperty":
  16923. case "BinaryExpression":
  16924. case "LogicalExpression":
  16925. return true;
  16926. case "CallExpression":
  16927. case "NewExpression":
  16928. return name === "callee"
  16929. && parent.callee === node;
  16930. case "ConditionalExpression":
  16931. return name === "test"
  16932. && parent.test === node;
  16933. case "MemberExpression":
  16934. return name === "object"
  16935. && parent.object === node;
  16936. default:
  16937. return false;
  16938. }
  16939. case "ArrowFunctionExpression":
  16940. if (n.CallExpression.check(parent) &&
  16941. name === 'callee') {
  16942. return true;
  16943. }
  16944. if (n.MemberExpression.check(parent) &&
  16945. name === 'object') {
  16946. return true;
  16947. }
  16948. return isBinary(parent);
  16949. case "ObjectExpression":
  16950. if (parent.type === "ArrowFunctionExpression" &&
  16951. name === "body") {
  16952. return true;
  16953. }
  16954. break;
  16955. case 'TSAsExpression':
  16956. if (parent.type === 'ArrowFunctionExpression' &&
  16957. name === 'body' &&
  16958. node.expression.type === 'ObjectExpression') {
  16959. return true;
  16960. }
  16961. break;
  16962. case "CallExpression":
  16963. if (name === "declaration" &&
  16964. n.ExportDefaultDeclaration.check(parent) &&
  16965. n.FunctionExpression.check(node.callee)) {
  16966. return true;
  16967. }
  16968. }
  16969. if (parent.type === "NewExpression" &&
  16970. name === "callee" &&
  16971. parent.callee === node) {
  16972. return containsCallExpression(node);
  16973. }
  16974. if (assumeExpressionContext !== true &&
  16975. !this.canBeFirstInStatement() &&
  16976. this.firstInStatement()) {
  16977. return true;
  16978. }
  16979. return false;
  16980. };
  16981. function isBinary(node) {
  16982. return n.BinaryExpression.check(node)
  16983. || n.LogicalExpression.check(node);
  16984. }
  16985. var PRECEDENCE = {};
  16986. [["||"],
  16987. ["&&"],
  16988. ["|"],
  16989. ["^"],
  16990. ["&"],
  16991. ["==", "===", "!=", "!=="],
  16992. ["<", ">", "<=", ">=", "in", "instanceof"],
  16993. [">>", "<<", ">>>"],
  16994. ["+", "-"],
  16995. ["*", "/", "%", "**"]
  16996. ].forEach(function (tier, i) {
  16997. tier.forEach(function (op) {
  16998. PRECEDENCE[op] = i;
  16999. });
  17000. });
  17001. function containsCallExpression(node) {
  17002. if (n.CallExpression.check(node)) {
  17003. return true;
  17004. }
  17005. if (isArray.check(node)) {
  17006. return node.some(containsCallExpression);
  17007. }
  17008. if (n.Node.check(node)) {
  17009. return types.someField(node, function (_name, child) {
  17010. return containsCallExpression(child);
  17011. });
  17012. }
  17013. return false;
  17014. }
  17015. FPp.canBeFirstInStatement = function () {
  17016. var node = this.getNode();
  17017. if (n.FunctionExpression.check(node)) {
  17018. return false;
  17019. }
  17020. if (n.ObjectExpression.check(node)) {
  17021. return false;
  17022. }
  17023. if (n.ClassExpression.check(node)) {
  17024. return false;
  17025. }
  17026. return true;
  17027. };
  17028. FPp.firstInStatement = function () {
  17029. var s = this.stack;
  17030. var parentName, parent;
  17031. var childName, child;
  17032. for (var i = s.length - 1; i >= 0; i -= 2) {
  17033. if (n.Node.check(s[i])) {
  17034. childName = parentName;
  17035. child = parent;
  17036. parentName = s[i - 1];
  17037. parent = s[i];
  17038. }
  17039. if (!parent || !child) {
  17040. continue;
  17041. }
  17042. if (n.BlockStatement.check(parent) &&
  17043. parentName === "body" &&
  17044. childName === 0) {
  17045. assert_1.default.strictEqual(parent.body[0], child);
  17046. return true;
  17047. }
  17048. if (n.ExpressionStatement.check(parent) &&
  17049. childName === "expression") {
  17050. assert_1.default.strictEqual(parent.expression, child);
  17051. return true;
  17052. }
  17053. if (n.AssignmentExpression.check(parent) &&
  17054. childName === "left") {
  17055. assert_1.default.strictEqual(parent.left, child);
  17056. return true;
  17057. }
  17058. if (n.ArrowFunctionExpression.check(parent) &&
  17059. childName === "body") {
  17060. assert_1.default.strictEqual(parent.body, child);
  17061. return true;
  17062. }
  17063. if (n.SequenceExpression.check(parent) &&
  17064. parentName === "expressions" &&
  17065. childName === 0) {
  17066. assert_1.default.strictEqual(parent.expressions[0], child);
  17067. continue;
  17068. }
  17069. if (n.CallExpression.check(parent) &&
  17070. childName === "callee") {
  17071. assert_1.default.strictEqual(parent.callee, child);
  17072. continue;
  17073. }
  17074. if (n.MemberExpression.check(parent) &&
  17075. childName === "object") {
  17076. assert_1.default.strictEqual(parent.object, child);
  17077. continue;
  17078. }
  17079. if (n.ConditionalExpression.check(parent) &&
  17080. childName === "test") {
  17081. assert_1.default.strictEqual(parent.test, child);
  17082. continue;
  17083. }
  17084. if (isBinary(parent) &&
  17085. childName === "left") {
  17086. assert_1.default.strictEqual(parent.left, child);
  17087. continue;
  17088. }
  17089. if (n.UnaryExpression.check(parent) &&
  17090. !parent.prefix &&
  17091. childName === "argument") {
  17092. assert_1.default.strictEqual(parent.argument, child);
  17093. continue;
  17094. }
  17095. return false;
  17096. }
  17097. return true;
  17098. };
  17099. exports.default = FastPath;
  17100. });
  17101. unwrapExports(fastPath);
  17102. var patcher = createCommonjsModule(function (module, exports) {
  17103. var __importDefault = (this && this.__importDefault) || function (mod) {
  17104. return (mod && mod.__esModule) ? mod : { "default": mod };
  17105. };
  17106. var __importStar = (this && this.__importStar) || function (mod) {
  17107. if (mod && mod.__esModule) return mod;
  17108. var result = {};
  17109. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  17110. result["default"] = mod;
  17111. return result;
  17112. };
  17113. Object.defineProperty(exports, "__esModule", { value: true });
  17114. var assert_1 = __importDefault(assert);
  17115. var linesModule = __importStar(lines);
  17116. var types = __importStar(main);
  17117. var Printable = types.namedTypes.Printable;
  17118. var Expression = types.namedTypes.Expression;
  17119. var ReturnStatement = types.namedTypes.ReturnStatement;
  17120. var SourceLocation = types.namedTypes.SourceLocation;
  17121. var fast_path_1 = __importDefault(fastPath);
  17122. var isObject = types.builtInTypes.object;
  17123. var isArray = types.builtInTypes.array;
  17124. var isString = types.builtInTypes.string;
  17125. var riskyAdjoiningCharExp = /[0-9a-z_$]/i;
  17126. var Patcher = function Patcher(lines) {
  17127. assert_1.default.ok(this instanceof Patcher);
  17128. assert_1.default.ok(lines instanceof linesModule.Lines);
  17129. var self = this, replacements = [];
  17130. self.replace = function (loc, lines) {
  17131. if (isString.check(lines))
  17132. lines = linesModule.fromString(lines);
  17133. replacements.push({
  17134. lines: lines,
  17135. start: loc.start,
  17136. end: loc.end
  17137. });
  17138. };
  17139. self.get = function (loc) {
  17140. // If no location is provided, return the complete Lines object.
  17141. loc = loc || {
  17142. start: { line: 1, column: 0 },
  17143. end: { line: lines.length,
  17144. column: lines.getLineLength(lines.length) }
  17145. };
  17146. var sliceFrom = loc.start, toConcat = [];
  17147. function pushSlice(from, to) {
  17148. assert_1.default.ok(util$1.comparePos(from, to) <= 0);
  17149. toConcat.push(lines.slice(from, to));
  17150. }
  17151. replacements.sort(function (a, b) {
  17152. return util$1.comparePos(a.start, b.start);
  17153. }).forEach(function (rep) {
  17154. if (util$1.comparePos(sliceFrom, rep.start) > 0) ;
  17155. else {
  17156. pushSlice(sliceFrom, rep.start);
  17157. toConcat.push(rep.lines);
  17158. sliceFrom = rep.end;
  17159. }
  17160. });
  17161. pushSlice(sliceFrom, loc.end);
  17162. return linesModule.concat(toConcat);
  17163. };
  17164. };
  17165. exports.Patcher = Patcher;
  17166. var Pp = Patcher.prototype;
  17167. Pp.tryToReprintComments = function (newNode, oldNode, print) {
  17168. var patcher = this;
  17169. if (!newNode.comments &&
  17170. !oldNode.comments) {
  17171. // We were (vacuously) able to reprint all the comments!
  17172. return true;
  17173. }
  17174. var newPath = fast_path_1.default.from(newNode);
  17175. var oldPath = fast_path_1.default.from(oldNode);
  17176. newPath.stack.push("comments", getSurroundingComments(newNode));
  17177. oldPath.stack.push("comments", getSurroundingComments(oldNode));
  17178. var reprints = [];
  17179. var ableToReprintComments = findArrayReprints(newPath, oldPath, reprints);
  17180. // No need to pop anything from newPath.stack or oldPath.stack, since
  17181. // newPath and oldPath are fresh local variables.
  17182. if (ableToReprintComments && reprints.length > 0) {
  17183. reprints.forEach(function (reprint) {
  17184. var oldComment = reprint.oldPath.getValue();
  17185. assert_1.default.ok(oldComment.leading || oldComment.trailing);
  17186. patcher.replace(oldComment.loc,
  17187. // Comments can't have .comments, so it doesn't matter whether we
  17188. // print with comments or without.
  17189. print(reprint.newPath).indentTail(oldComment.loc.indent));
  17190. });
  17191. }
  17192. return ableToReprintComments;
  17193. };
  17194. // Get all comments that are either leading or trailing, ignoring any
  17195. // comments that occur inside node.loc. Returns an empty array for nodes
  17196. // with no leading or trailing comments.
  17197. function getSurroundingComments(node) {
  17198. var result = [];
  17199. if (node.comments &&
  17200. node.comments.length > 0) {
  17201. node.comments.forEach(function (comment) {
  17202. if (comment.leading || comment.trailing) {
  17203. result.push(comment);
  17204. }
  17205. });
  17206. }
  17207. return result;
  17208. }
  17209. Pp.deleteComments = function (node) {
  17210. if (!node.comments) {
  17211. return;
  17212. }
  17213. var patcher = this;
  17214. node.comments.forEach(function (comment) {
  17215. if (comment.leading) {
  17216. // Delete leading comments along with any trailing whitespace they
  17217. // might have.
  17218. patcher.replace({
  17219. start: comment.loc.start,
  17220. end: node.loc.lines.skipSpaces(comment.loc.end, false, false)
  17221. }, "");
  17222. }
  17223. else if (comment.trailing) {
  17224. // Delete trailing comments along with any leading whitespace they
  17225. // might have.
  17226. patcher.replace({
  17227. start: node.loc.lines.skipSpaces(comment.loc.start, true, false),
  17228. end: comment.loc.end
  17229. }, "");
  17230. }
  17231. });
  17232. };
  17233. function getReprinter(path) {
  17234. assert_1.default.ok(path instanceof fast_path_1.default);
  17235. // Make sure that this path refers specifically to a Node, rather than
  17236. // some non-Node subproperty of a Node.
  17237. var node = path.getValue();
  17238. if (!Printable.check(node))
  17239. return;
  17240. var orig = node.original;
  17241. var origLoc = orig && orig.loc;
  17242. var lines = origLoc && origLoc.lines;
  17243. var reprints = [];
  17244. if (!lines || !findReprints(path, reprints))
  17245. return;
  17246. return function (print) {
  17247. var patcher = new Patcher(lines);
  17248. reprints.forEach(function (reprint) {
  17249. var newNode = reprint.newPath.getValue();
  17250. var oldNode = reprint.oldPath.getValue();
  17251. SourceLocation.assert(oldNode.loc, true);
  17252. var needToPrintNewPathWithComments = !patcher.tryToReprintComments(newNode, oldNode, print);
  17253. if (needToPrintNewPathWithComments) {
  17254. // Since we were not able to preserve all leading/trailing
  17255. // comments, we delete oldNode's comments, print newPath with
  17256. // comments, and then patch the resulting lines where oldNode used
  17257. // to be.
  17258. patcher.deleteComments(oldNode);
  17259. }
  17260. var newLines = print(reprint.newPath, {
  17261. includeComments: needToPrintNewPathWithComments,
  17262. // If the oldNode we're replacing already had parentheses, we may
  17263. // not need to print the new node with any extra parentheses,
  17264. // because the existing parentheses will suffice. However, if the
  17265. // newNode has a different type than the oldNode, let the printer
  17266. // decide if reprint.newPath needs parentheses, as usual.
  17267. avoidRootParens: (oldNode.type === newNode.type &&
  17268. reprint.oldPath.hasParens())
  17269. }).indentTail(oldNode.loc.indent);
  17270. var nls = needsLeadingSpace(lines, oldNode.loc, newLines);
  17271. var nts = needsTrailingSpace(lines, oldNode.loc, newLines);
  17272. // If we try to replace the argument of a ReturnStatement like
  17273. // return"asdf" with e.g. a literal null expression, we run the risk
  17274. // of ending up with returnnull, so we need to add an extra leading
  17275. // space in situations where that might happen. Likewise for
  17276. // "asdf"in obj. See #170.
  17277. if (nls || nts) {
  17278. var newParts = [];
  17279. nls && newParts.push(" ");
  17280. newParts.push(newLines);
  17281. nts && newParts.push(" ");
  17282. newLines = linesModule.concat(newParts);
  17283. }
  17284. patcher.replace(oldNode.loc, newLines);
  17285. });
  17286. // Recall that origLoc is the .loc of an ancestor node that is
  17287. // guaranteed to contain all the reprinted nodes and comments.
  17288. var patchedLines = patcher.get(origLoc).indentTail(-orig.loc.indent);
  17289. if (path.needsParens()) {
  17290. return linesModule.concat(["(", patchedLines, ")"]);
  17291. }
  17292. return patchedLines;
  17293. };
  17294. }
  17295. exports.getReprinter = getReprinter;
  17296. // If the last character before oldLoc and the first character of newLines
  17297. // are both identifier characters, they must be separated by a space,
  17298. // otherwise they will most likely get fused together into a single token.
  17299. function needsLeadingSpace(oldLines, oldLoc, newLines) {
  17300. var posBeforeOldLoc = util$1.copyPos(oldLoc.start);
  17301. // The character just before the location occupied by oldNode.
  17302. var charBeforeOldLoc = oldLines.prevPos(posBeforeOldLoc) &&
  17303. oldLines.charAt(posBeforeOldLoc);
  17304. // First character of the reprinted node.
  17305. var newFirstChar = newLines.charAt(newLines.firstPos());
  17306. return charBeforeOldLoc &&
  17307. riskyAdjoiningCharExp.test(charBeforeOldLoc) &&
  17308. newFirstChar &&
  17309. riskyAdjoiningCharExp.test(newFirstChar);
  17310. }
  17311. // If the last character of newLines and the first character after oldLoc
  17312. // are both identifier characters, they must be separated by a space,
  17313. // otherwise they will most likely get fused together into a single token.
  17314. function needsTrailingSpace(oldLines, oldLoc, newLines) {
  17315. // The character just after the location occupied by oldNode.
  17316. var charAfterOldLoc = oldLines.charAt(oldLoc.end);
  17317. var newLastPos = newLines.lastPos();
  17318. // Last character of the reprinted node.
  17319. var newLastChar = newLines.prevPos(newLastPos) &&
  17320. newLines.charAt(newLastPos);
  17321. return newLastChar &&
  17322. riskyAdjoiningCharExp.test(newLastChar) &&
  17323. charAfterOldLoc &&
  17324. riskyAdjoiningCharExp.test(charAfterOldLoc);
  17325. }
  17326. function findReprints(newPath, reprints) {
  17327. var newNode = newPath.getValue();
  17328. Printable.assert(newNode);
  17329. var oldNode = newNode.original;
  17330. Printable.assert(oldNode);
  17331. assert_1.default.deepEqual(reprints, []);
  17332. if (newNode.type !== oldNode.type) {
  17333. return false;
  17334. }
  17335. var oldPath = new fast_path_1.default(oldNode);
  17336. var canReprint = findChildReprints(newPath, oldPath, reprints);
  17337. if (!canReprint) {
  17338. // Make absolutely sure the calling code does not attempt to reprint
  17339. // any nodes.
  17340. reprints.length = 0;
  17341. }
  17342. return canReprint;
  17343. }
  17344. function findAnyReprints(newPath, oldPath, reprints) {
  17345. var newNode = newPath.getValue();
  17346. var oldNode = oldPath.getValue();
  17347. if (newNode === oldNode)
  17348. return true;
  17349. if (isArray.check(newNode))
  17350. return findArrayReprints(newPath, oldPath, reprints);
  17351. if (isObject.check(newNode))
  17352. return findObjectReprints(newPath, oldPath, reprints);
  17353. return false;
  17354. }
  17355. function findArrayReprints(newPath, oldPath, reprints) {
  17356. var newNode = newPath.getValue();
  17357. var oldNode = oldPath.getValue();
  17358. if (newNode === oldNode ||
  17359. newPath.valueIsDuplicate() ||
  17360. oldPath.valueIsDuplicate()) {
  17361. return true;
  17362. }
  17363. isArray.assert(newNode);
  17364. var len = newNode.length;
  17365. if (!(isArray.check(oldNode) &&
  17366. oldNode.length === len))
  17367. return false;
  17368. for (var i = 0; i < len; ++i) {
  17369. newPath.stack.push(i, newNode[i]);
  17370. oldPath.stack.push(i, oldNode[i]);
  17371. var canReprint = findAnyReprints(newPath, oldPath, reprints);
  17372. newPath.stack.length -= 2;
  17373. oldPath.stack.length -= 2;
  17374. if (!canReprint) {
  17375. return false;
  17376. }
  17377. }
  17378. return true;
  17379. }
  17380. function findObjectReprints(newPath, oldPath, reprints) {
  17381. var newNode = newPath.getValue();
  17382. isObject.assert(newNode);
  17383. if (newNode.original === null) {
  17384. // If newNode.original node was set to null, reprint the node.
  17385. return false;
  17386. }
  17387. var oldNode = oldPath.getValue();
  17388. if (!isObject.check(oldNode))
  17389. return false;
  17390. if (newNode === oldNode ||
  17391. newPath.valueIsDuplicate() ||
  17392. oldPath.valueIsDuplicate()) {
  17393. return true;
  17394. }
  17395. if (Printable.check(newNode)) {
  17396. if (!Printable.check(oldNode)) {
  17397. return false;
  17398. }
  17399. // Here we need to decide whether the reprinted code for newNode is
  17400. // appropriate for patching into the location of oldNode.
  17401. if (newNode.type === oldNode.type) {
  17402. var childReprints = [];
  17403. if (findChildReprints(newPath, oldPath, childReprints)) {
  17404. reprints.push.apply(reprints, childReprints);
  17405. }
  17406. else if (oldNode.loc) {
  17407. // If we have no .loc information for oldNode, then we won't be
  17408. // able to reprint it.
  17409. reprints.push({
  17410. oldPath: oldPath.copy(),
  17411. newPath: newPath.copy()
  17412. });
  17413. }
  17414. else {
  17415. return false;
  17416. }
  17417. return true;
  17418. }
  17419. if (Expression.check(newNode) &&
  17420. Expression.check(oldNode) &&
  17421. // If we have no .loc information for oldNode, then we won't be
  17422. // able to reprint it.
  17423. oldNode.loc) {
  17424. // If both nodes are subtypes of Expression, then we should be able
  17425. // to fill the location occupied by the old node with code printed
  17426. // for the new node with no ill consequences.
  17427. reprints.push({
  17428. oldPath: oldPath.copy(),
  17429. newPath: newPath.copy()
  17430. });
  17431. return true;
  17432. }
  17433. // The nodes have different types, and at least one of the types is
  17434. // not a subtype of the Expression type, so we cannot safely assume
  17435. // the nodes are syntactically interchangeable.
  17436. return false;
  17437. }
  17438. return findChildReprints(newPath, oldPath, reprints);
  17439. }
  17440. function findChildReprints(newPath, oldPath, reprints) {
  17441. var newNode = newPath.getValue();
  17442. var oldNode = oldPath.getValue();
  17443. isObject.assert(newNode);
  17444. isObject.assert(oldNode);
  17445. if (newNode.original === null) {
  17446. // If newNode.original node was set to null, reprint the node.
  17447. return false;
  17448. }
  17449. // If this node needs parentheses and will not be wrapped with
  17450. // parentheses when reprinted, then return false to skip reprinting and
  17451. // let it be printed generically.
  17452. if (newPath.needsParens() &&
  17453. !oldPath.hasParens()) {
  17454. return false;
  17455. }
  17456. var keys = util$1.getUnionOfKeys(oldNode, newNode);
  17457. if (oldNode.type === "File" ||
  17458. newNode.type === "File") {
  17459. // Don't bother traversing file.tokens, an often very large array
  17460. // returned by Babylon, and useless for our purposes.
  17461. delete keys.tokens;
  17462. }
  17463. // Don't bother traversing .loc objects looking for reprintable nodes.
  17464. delete keys.loc;
  17465. var originalReprintCount = reprints.length;
  17466. for (var k in keys) {
  17467. if (k.charAt(0) === "_") {
  17468. // Ignore "private" AST properties added by e.g. Babel plugins and
  17469. // parsers like Babylon.
  17470. continue;
  17471. }
  17472. newPath.stack.push(k, types.getFieldValue(newNode, k));
  17473. oldPath.stack.push(k, types.getFieldValue(oldNode, k));
  17474. var canReprint = findAnyReprints(newPath, oldPath, reprints);
  17475. newPath.stack.length -= 2;
  17476. oldPath.stack.length -= 2;
  17477. if (!canReprint) {
  17478. return false;
  17479. }
  17480. }
  17481. // Return statements might end up running into ASI issues due to
  17482. // comments inserted deep within the tree, so reprint them if anything
  17483. // changed within them.
  17484. if (ReturnStatement.check(newPath.getNode()) &&
  17485. reprints.length > originalReprintCount) {
  17486. return false;
  17487. }
  17488. return true;
  17489. }
  17490. });
  17491. unwrapExports(patcher);
  17492. var patcher_1 = patcher.Patcher;
  17493. var patcher_2 = patcher.getReprinter;
  17494. var printer = createCommonjsModule(function (module, exports) {
  17495. var __importDefault = (this && this.__importDefault) || function (mod) {
  17496. return (mod && mod.__esModule) ? mod : { "default": mod };
  17497. };
  17498. var __importStar = (this && this.__importStar) || function (mod) {
  17499. if (mod && mod.__esModule) return mod;
  17500. var result = {};
  17501. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  17502. result["default"] = mod;
  17503. return result;
  17504. };
  17505. Object.defineProperty(exports, "__esModule", { value: true });
  17506. var assert_1 = __importDefault(assert);
  17507. var types = __importStar(main);
  17508. var namedTypes = types.namedTypes;
  17509. var isString = types.builtInTypes.string;
  17510. var isObject = types.builtInTypes.object;
  17511. var fast_path_1 = __importDefault(fastPath);
  17512. var util = __importStar(util$1);
  17513. var PrintResult = function PrintResult(code, sourceMap) {
  17514. assert_1.default.ok(this instanceof PrintResult);
  17515. isString.assert(code);
  17516. this.code = code;
  17517. if (sourceMap) {
  17518. isObject.assert(sourceMap);
  17519. this.map = sourceMap;
  17520. }
  17521. };
  17522. var PRp = PrintResult.prototype;
  17523. var warnedAboutToString = false;
  17524. PRp.toString = function () {
  17525. if (!warnedAboutToString) {
  17526. console.warn("Deprecation warning: recast.print now returns an object with " +
  17527. "a .code property. You appear to be treating the object as a " +
  17528. "string, which might still work but is strongly discouraged.");
  17529. warnedAboutToString = true;
  17530. }
  17531. return this.code;
  17532. };
  17533. var emptyPrintResult = new PrintResult("");
  17534. var Printer = function Printer(config) {
  17535. assert_1.default.ok(this instanceof Printer);
  17536. var explicitTabWidth = config && config.tabWidth;
  17537. config = options.normalize(config);
  17538. // It's common for client code to pass the same options into both
  17539. // recast.parse and recast.print, but the Printer doesn't need (and
  17540. // can be confused by) config.sourceFileName, so we null it out.
  17541. config.sourceFileName = null;
  17542. // Non-destructively modifies options with overrides, and returns a
  17543. // new print function that uses the modified options.
  17544. function makePrintFunctionWith(options, overrides) {
  17545. options = Object.assign({}, options, overrides);
  17546. return function (path) {
  17547. return print(path, options);
  17548. };
  17549. }
  17550. function print(path, options) {
  17551. assert_1.default.ok(path instanceof fast_path_1.default);
  17552. options = options || {};
  17553. if (options.includeComments) {
  17554. return comments.printComments(path, makePrintFunctionWith(options, {
  17555. includeComments: false
  17556. }));
  17557. }
  17558. var oldTabWidth = config.tabWidth;
  17559. if (!explicitTabWidth) {
  17560. var loc = path.getNode().loc;
  17561. if (loc && loc.lines && loc.lines.guessTabWidth) {
  17562. config.tabWidth = loc.lines.guessTabWidth();
  17563. }
  17564. }
  17565. var reprinter = patcher.getReprinter(path);
  17566. var lines = reprinter
  17567. // Since the print function that we pass to the reprinter will
  17568. // be used to print "new" nodes, it's tempting to think we
  17569. // should pass printRootGenerically instead of print, to avoid
  17570. // calling maybeReprint again, but that would be a mistake
  17571. // because the new nodes might not be entirely new, but merely
  17572. // moved from elsewhere in the AST. The print function is the
  17573. // right choice because it gives us the opportunity to reprint
  17574. // such nodes using their original source.
  17575. ? reprinter(print)
  17576. : genericPrint(path, config, options, makePrintFunctionWith(options, {
  17577. includeComments: true,
  17578. avoidRootParens: false
  17579. }));
  17580. config.tabWidth = oldTabWidth;
  17581. return lines;
  17582. }
  17583. this.print = function (ast) {
  17584. if (!ast) {
  17585. return emptyPrintResult;
  17586. }
  17587. var lines = print(fast_path_1.default.from(ast), {
  17588. includeComments: true,
  17589. avoidRootParens: false
  17590. });
  17591. return new PrintResult(lines.toString(config), util.composeSourceMaps(config.inputSourceMap, lines.getSourceMap(config.sourceMapName, config.sourceRoot)));
  17592. };
  17593. this.printGenerically = function (ast) {
  17594. if (!ast) {
  17595. return emptyPrintResult;
  17596. }
  17597. // Print the entire AST generically.
  17598. function printGenerically(path) {
  17599. return comments.printComments(path, function (path) {
  17600. return genericPrint(path, config, {
  17601. includeComments: true,
  17602. avoidRootParens: false
  17603. }, printGenerically);
  17604. });
  17605. }
  17606. var path = fast_path_1.default.from(ast);
  17607. var oldReuseWhitespace = config.reuseWhitespace;
  17608. // Do not reuse whitespace (or anything else, for that matter)
  17609. // when printing generically.
  17610. config.reuseWhitespace = false;
  17611. // TODO Allow printing of comments?
  17612. var pr = new PrintResult(printGenerically(path).toString(config));
  17613. config.reuseWhitespace = oldReuseWhitespace;
  17614. return pr;
  17615. };
  17616. };
  17617. exports.Printer = Printer;
  17618. function genericPrint(path, config, options, printPath) {
  17619. assert_1.default.ok(path instanceof fast_path_1.default);
  17620. var node = path.getValue();
  17621. var parts = [];
  17622. var linesWithoutParens = genericPrintNoParens(path, config, printPath);
  17623. if (!node || linesWithoutParens.isEmpty()) {
  17624. return linesWithoutParens;
  17625. }
  17626. var shouldAddParens = false;
  17627. var decoratorsLines = printDecorators(path, printPath);
  17628. if (decoratorsLines.isEmpty()) {
  17629. // Nodes with decorators can't have parentheses, so we can avoid
  17630. // computing path.needsParens() except in this case.
  17631. if (!options.avoidRootParens) {
  17632. shouldAddParens = path.needsParens();
  17633. }
  17634. }
  17635. else {
  17636. parts.push(decoratorsLines);
  17637. }
  17638. if (shouldAddParens) {
  17639. parts.unshift("(");
  17640. }
  17641. parts.push(linesWithoutParens);
  17642. if (shouldAddParens) {
  17643. parts.push(")");
  17644. }
  17645. return lines.concat(parts);
  17646. }
  17647. // Note that the `options` parameter of this function is what other
  17648. // functions in this file call the `config` object (that is, the
  17649. // configuration object originally passed into the Printer constructor).
  17650. // Its properties are documented in lib/options.js.
  17651. function genericPrintNoParens(path, options, print) {
  17652. var n = path.getValue();
  17653. if (!n) {
  17654. return lines.fromString("");
  17655. }
  17656. if (typeof n === "string") {
  17657. return lines.fromString(n, options);
  17658. }
  17659. namedTypes.Printable.assert(n);
  17660. var parts = [];
  17661. switch (n.type) {
  17662. case "File":
  17663. return path.call(print, "program");
  17664. case "Program":
  17665. // Babel 6
  17666. if (n.directives) {
  17667. path.each(function (childPath) {
  17668. parts.push(print(childPath), ";\n");
  17669. }, "directives");
  17670. }
  17671. if (n.interpreter) {
  17672. parts.push(path.call(print, "interpreter"));
  17673. }
  17674. parts.push(path.call(function (bodyPath) {
  17675. return printStatementSequence(bodyPath, options, print);
  17676. }, "body"));
  17677. return lines.concat(parts);
  17678. case "Noop": // Babel extension.
  17679. case "EmptyStatement":
  17680. return lines.fromString("");
  17681. case "ExpressionStatement":
  17682. return lines.concat([path.call(print, "expression"), ";"]);
  17683. case "ParenthesizedExpression": // Babel extension.
  17684. return lines.concat(["(", path.call(print, "expression"), ")"]);
  17685. case "BinaryExpression":
  17686. case "LogicalExpression":
  17687. case "AssignmentExpression":
  17688. return lines.fromString(" ").join([
  17689. path.call(print, "left"),
  17690. n.operator,
  17691. path.call(print, "right")
  17692. ]);
  17693. case "AssignmentPattern":
  17694. return lines.concat([
  17695. path.call(print, "left"),
  17696. " = ",
  17697. path.call(print, "right")
  17698. ]);
  17699. case "MemberExpression":
  17700. case "OptionalMemberExpression":
  17701. parts.push(path.call(print, "object"));
  17702. var property = path.call(print, "property");
  17703. var optional = n.type === "OptionalMemberExpression" && n.optional;
  17704. if (n.computed) {
  17705. parts.push(optional ? "?.[" : "[", property, "]");
  17706. }
  17707. else {
  17708. parts.push(optional ? "?." : ".", property);
  17709. }
  17710. return lines.concat(parts);
  17711. case "MetaProperty":
  17712. return lines.concat([
  17713. path.call(print, "meta"),
  17714. ".",
  17715. path.call(print, "property")
  17716. ]);
  17717. case "BindExpression":
  17718. if (n.object) {
  17719. parts.push(path.call(print, "object"));
  17720. }
  17721. parts.push("::", path.call(print, "callee"));
  17722. return lines.concat(parts);
  17723. case "Path":
  17724. return lines.fromString(".").join(n.body);
  17725. case "Identifier":
  17726. return lines.concat([
  17727. lines.fromString(n.name, options),
  17728. n.optional ? "?" : "",
  17729. path.call(print, "typeAnnotation")
  17730. ]);
  17731. case "SpreadElement":
  17732. case "SpreadElementPattern":
  17733. case "RestProperty": // Babel 6 for ObjectPattern
  17734. case "SpreadProperty":
  17735. case "SpreadPropertyPattern":
  17736. case "ObjectTypeSpreadProperty":
  17737. case "RestElement":
  17738. return lines.concat([
  17739. "...",
  17740. path.call(print, "argument"),
  17741. path.call(print, "typeAnnotation")
  17742. ]);
  17743. case "FunctionDeclaration":
  17744. case "FunctionExpression":
  17745. case "TSDeclareFunction":
  17746. if (n.declare) {
  17747. parts.push("declare ");
  17748. }
  17749. if (n.async) {
  17750. parts.push("async ");
  17751. }
  17752. parts.push("function");
  17753. if (n.generator)
  17754. parts.push("*");
  17755. if (n.id) {
  17756. parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
  17757. }
  17758. else {
  17759. if (n.typeParameters) {
  17760. parts.push(path.call(print, "typeParameters"));
  17761. }
  17762. }
  17763. parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "returnType"));
  17764. if (n.body) {
  17765. parts.push(" ", path.call(print, "body"));
  17766. }
  17767. return lines.concat(parts);
  17768. case "ArrowFunctionExpression":
  17769. if (n.async) {
  17770. parts.push("async ");
  17771. }
  17772. if (n.typeParameters) {
  17773. parts.push(path.call(print, "typeParameters"));
  17774. }
  17775. if (!options.arrowParensAlways &&
  17776. n.params.length === 1 &&
  17777. !n.rest &&
  17778. n.params[0].type === 'Identifier' &&
  17779. !n.params[0].typeAnnotation &&
  17780. !n.returnType) {
  17781. parts.push(path.call(print, "params", 0));
  17782. }
  17783. else {
  17784. parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "returnType"));
  17785. }
  17786. parts.push(" => ", path.call(print, "body"));
  17787. return lines.concat(parts);
  17788. case "MethodDefinition":
  17789. return printMethod(path, options, print);
  17790. case "YieldExpression":
  17791. parts.push("yield");
  17792. if (n.delegate)
  17793. parts.push("*");
  17794. if (n.argument)
  17795. parts.push(" ", path.call(print, "argument"));
  17796. return lines.concat(parts);
  17797. case "AwaitExpression":
  17798. parts.push("await");
  17799. if (n.all)
  17800. parts.push("*");
  17801. if (n.argument)
  17802. parts.push(" ", path.call(print, "argument"));
  17803. return lines.concat(parts);
  17804. case "ModuleDeclaration":
  17805. parts.push("module", path.call(print, "id"));
  17806. if (n.source) {
  17807. assert_1.default.ok(!n.body);
  17808. parts.push("from", path.call(print, "source"));
  17809. }
  17810. else {
  17811. parts.push(path.call(print, "body"));
  17812. }
  17813. return lines.fromString(" ").join(parts);
  17814. case "ImportSpecifier":
  17815. if (n.importKind && n.importKind !== "value") {
  17816. parts.push(n.importKind + " ");
  17817. }
  17818. if (n.imported) {
  17819. parts.push(path.call(print, "imported"));
  17820. if (n.local &&
  17821. n.local.name !== n.imported.name) {
  17822. parts.push(" as ", path.call(print, "local"));
  17823. }
  17824. }
  17825. else if (n.id) {
  17826. parts.push(path.call(print, "id"));
  17827. if (n.name) {
  17828. parts.push(" as ", path.call(print, "name"));
  17829. }
  17830. }
  17831. return lines.concat(parts);
  17832. case "ExportSpecifier":
  17833. if (n.local) {
  17834. parts.push(path.call(print, "local"));
  17835. if (n.exported &&
  17836. n.exported.name !== n.local.name) {
  17837. parts.push(" as ", path.call(print, "exported"));
  17838. }
  17839. }
  17840. else if (n.id) {
  17841. parts.push(path.call(print, "id"));
  17842. if (n.name) {
  17843. parts.push(" as ", path.call(print, "name"));
  17844. }
  17845. }
  17846. return lines.concat(parts);
  17847. case "ExportBatchSpecifier":
  17848. return lines.fromString("*");
  17849. case "ImportNamespaceSpecifier":
  17850. parts.push("* as ");
  17851. if (n.local) {
  17852. parts.push(path.call(print, "local"));
  17853. }
  17854. else if (n.id) {
  17855. parts.push(path.call(print, "id"));
  17856. }
  17857. return lines.concat(parts);
  17858. case "ImportDefaultSpecifier":
  17859. if (n.local) {
  17860. return path.call(print, "local");
  17861. }
  17862. return path.call(print, "id");
  17863. case "TSExportAssignment":
  17864. return lines.concat(["export = ", path.call(print, "expression")]);
  17865. case "ExportDeclaration":
  17866. case "ExportDefaultDeclaration":
  17867. case "ExportNamedDeclaration":
  17868. return printExportDeclaration(path, options, print);
  17869. case "ExportAllDeclaration":
  17870. parts.push("export *");
  17871. if (n.exported) {
  17872. parts.push(" as ", path.call(print, "exported"));
  17873. }
  17874. parts.push(" from ", path.call(print, "source"), ";");
  17875. return lines.concat(parts);
  17876. case "TSNamespaceExportDeclaration":
  17877. parts.push("export as namespace ", path.call(print, "id"));
  17878. return maybeAddSemicolon(lines.concat(parts));
  17879. case "ExportNamespaceSpecifier":
  17880. return lines.concat(["* as ", path.call(print, "exported")]);
  17881. case "ExportDefaultSpecifier":
  17882. return path.call(print, "exported");
  17883. case "Import":
  17884. return lines.fromString("import", options);
  17885. case "ImportDeclaration": {
  17886. parts.push("import ");
  17887. if (n.importKind && n.importKind !== "value") {
  17888. parts.push(n.importKind + " ");
  17889. }
  17890. if (n.specifiers &&
  17891. n.specifiers.length > 0) {
  17892. var unbracedSpecifiers_1 = [];
  17893. var bracedSpecifiers_1 = [];
  17894. path.each(function (specifierPath) {
  17895. var spec = specifierPath.getValue();
  17896. if (spec.type === "ImportSpecifier") {
  17897. bracedSpecifiers_1.push(print(specifierPath));
  17898. }
  17899. else if (spec.type === "ImportDefaultSpecifier" ||
  17900. spec.type === "ImportNamespaceSpecifier") {
  17901. unbracedSpecifiers_1.push(print(specifierPath));
  17902. }
  17903. }, "specifiers");
  17904. unbracedSpecifiers_1.forEach(function (lines, i) {
  17905. if (i > 0) {
  17906. parts.push(", ");
  17907. }
  17908. parts.push(lines);
  17909. });
  17910. if (bracedSpecifiers_1.length > 0) {
  17911. var lines_2 = lines.fromString(", ").join(bracedSpecifiers_1);
  17912. if (lines_2.getLineLength(1) > options.wrapColumn) {
  17913. lines_2 = lines.concat([
  17914. lines.fromString(",\n").join(bracedSpecifiers_1).indent(options.tabWidth),
  17915. ","
  17916. ]);
  17917. }
  17918. if (unbracedSpecifiers_1.length > 0) {
  17919. parts.push(", ");
  17920. }
  17921. if (lines_2.length > 1) {
  17922. parts.push("{\n", lines_2, "\n}");
  17923. }
  17924. else if (options.objectCurlySpacing) {
  17925. parts.push("{ ", lines_2, " }");
  17926. }
  17927. else {
  17928. parts.push("{", lines_2, "}");
  17929. }
  17930. }
  17931. parts.push(" from ");
  17932. }
  17933. parts.push(path.call(print, "source"), ";");
  17934. return lines.concat(parts);
  17935. }
  17936. case "BlockStatement":
  17937. var naked = path.call(function (bodyPath) {
  17938. return printStatementSequence(bodyPath, options, print);
  17939. }, "body");
  17940. if (naked.isEmpty()) {
  17941. if (!n.directives || n.directives.length === 0) {
  17942. return lines.fromString("{}");
  17943. }
  17944. }
  17945. parts.push("{\n");
  17946. // Babel 6
  17947. if (n.directives) {
  17948. path.each(function (childPath) {
  17949. parts.push(maybeAddSemicolon(print(childPath).indent(options.tabWidth)), n.directives.length > 1 || !naked.isEmpty() ? "\n" : "");
  17950. }, "directives");
  17951. }
  17952. parts.push(naked.indent(options.tabWidth));
  17953. parts.push("\n}");
  17954. return lines.concat(parts);
  17955. case "ReturnStatement":
  17956. parts.push("return");
  17957. if (n.argument) {
  17958. var argLines = path.call(print, "argument");
  17959. if (argLines.startsWithComment() ||
  17960. (argLines.length > 1 &&
  17961. namedTypes.JSXElement &&
  17962. namedTypes.JSXElement.check(n.argument))) {
  17963. parts.push(" (\n", argLines.indent(options.tabWidth), "\n)");
  17964. }
  17965. else {
  17966. parts.push(" ", argLines);
  17967. }
  17968. }
  17969. parts.push(";");
  17970. return lines.concat(parts);
  17971. case "CallExpression":
  17972. case "OptionalCallExpression":
  17973. parts.push(path.call(print, "callee"));
  17974. if (n.typeParameters) {
  17975. parts.push(path.call(print, "typeParameters"));
  17976. }
  17977. if (n.typeArguments) {
  17978. parts.push(path.call(print, "typeArguments"));
  17979. }
  17980. if (n.type === "OptionalCallExpression" &&
  17981. n.callee.type !== "OptionalMemberExpression") {
  17982. parts.push("?.");
  17983. }
  17984. parts.push(printArgumentsList(path, options, print));
  17985. return lines.concat(parts);
  17986. case "ObjectExpression":
  17987. case "ObjectPattern":
  17988. case "ObjectTypeAnnotation":
  17989. var allowBreak = false;
  17990. var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
  17991. var separator = options.flowObjectCommas ? "," : (isTypeAnnotation ? ";" : ",");
  17992. var fields = [];
  17993. if (isTypeAnnotation) {
  17994. fields.push("indexers", "callProperties");
  17995. if (n.internalSlots != null) {
  17996. fields.push("internalSlots");
  17997. }
  17998. }
  17999. fields.push("properties");
  18000. var len = 0;
  18001. fields.forEach(function (field) {
  18002. len += n[field].length;
  18003. });
  18004. var oneLine = (isTypeAnnotation && len === 1) || len === 0;
  18005. var leftBrace = n.exact ? "{|" : "{";
  18006. var rightBrace = n.exact ? "|}" : "}";
  18007. parts.push(oneLine ? leftBrace : leftBrace + "\n");
  18008. var leftBraceIndex = parts.length - 1;
  18009. var i = 0;
  18010. fields.forEach(function (field) {
  18011. path.each(function (childPath) {
  18012. var lines = print(childPath);
  18013. if (!oneLine) {
  18014. lines = lines.indent(options.tabWidth);
  18015. }
  18016. var multiLine = !isTypeAnnotation && lines.length > 1;
  18017. if (multiLine && allowBreak) {
  18018. // Similar to the logic for BlockStatement.
  18019. parts.push("\n");
  18020. }
  18021. parts.push(lines);
  18022. if (i < len - 1) {
  18023. // Add an extra line break if the previous object property
  18024. // had a multi-line value.
  18025. parts.push(separator + (multiLine ? "\n\n" : "\n"));
  18026. allowBreak = !multiLine;
  18027. }
  18028. else if (len !== 1 && isTypeAnnotation) {
  18029. parts.push(separator);
  18030. }
  18031. else if (!oneLine && util.isTrailingCommaEnabled(options, "objects")) {
  18032. parts.push(separator);
  18033. }
  18034. i++;
  18035. }, field);
  18036. });
  18037. if (n.inexact) {
  18038. var line = lines.fromString("...", options);
  18039. if (oneLine) {
  18040. if (len > 0) {
  18041. parts.push(separator, " ");
  18042. }
  18043. parts.push(line);
  18044. }
  18045. else {
  18046. // No trailing separator after ... to maintain parity with prettier.
  18047. parts.push("\n", line.indent(options.tabWidth));
  18048. }
  18049. }
  18050. parts.push(oneLine ? rightBrace : "\n" + rightBrace);
  18051. if (i !== 0 && oneLine && options.objectCurlySpacing) {
  18052. parts[leftBraceIndex] = leftBrace + " ";
  18053. parts[parts.length - 1] = " " + rightBrace;
  18054. }
  18055. if (n.typeAnnotation) {
  18056. parts.push(path.call(print, "typeAnnotation"));
  18057. }
  18058. return lines.concat(parts);
  18059. case "PropertyPattern":
  18060. return lines.concat([
  18061. path.call(print, "key"),
  18062. ": ",
  18063. path.call(print, "pattern")
  18064. ]);
  18065. case "ObjectProperty": // Babel 6
  18066. case "Property": // Non-standard AST node type.
  18067. if (n.method || n.kind === "get" || n.kind === "set") {
  18068. return printMethod(path, options, print);
  18069. }
  18070. if (n.shorthand && n.value.type === "AssignmentPattern") {
  18071. return path.call(print, "value");
  18072. }
  18073. var key = path.call(print, "key");
  18074. if (n.computed) {
  18075. parts.push("[", key, "]");
  18076. }
  18077. else {
  18078. parts.push(key);
  18079. }
  18080. if (!n.shorthand) {
  18081. parts.push(": ", path.call(print, "value"));
  18082. }
  18083. return lines.concat(parts);
  18084. case "ClassMethod": // Babel 6
  18085. case "ObjectMethod": // Babel 6
  18086. case "ClassPrivateMethod":
  18087. case "TSDeclareMethod":
  18088. return printMethod(path, options, print);
  18089. case "PrivateName":
  18090. return lines.concat(["#", path.call(print, "id")]);
  18091. case "Decorator":
  18092. return lines.concat(["@", path.call(print, "expression")]);
  18093. case "ArrayExpression":
  18094. case "ArrayPattern":
  18095. var elems = n.elements, len = elems.length;
  18096. var printed = path.map(print, "elements");
  18097. var joined = lines.fromString(", ").join(printed);
  18098. var oneLine = joined.getLineLength(1) <= options.wrapColumn;
  18099. if (oneLine) {
  18100. if (options.arrayBracketSpacing) {
  18101. parts.push("[ ");
  18102. }
  18103. else {
  18104. parts.push("[");
  18105. }
  18106. }
  18107. else {
  18108. parts.push("[\n");
  18109. }
  18110. path.each(function (elemPath) {
  18111. var i = elemPath.getName();
  18112. var elem = elemPath.getValue();
  18113. if (!elem) {
  18114. // If the array expression ends with a hole, that hole
  18115. // will be ignored by the interpreter, but if it ends with
  18116. // two (or more) holes, we need to write out two (or more)
  18117. // commas so that the resulting code is interpreted with
  18118. // both (all) of the holes.
  18119. parts.push(",");
  18120. }
  18121. else {
  18122. var lines = printed[i];
  18123. if (oneLine) {
  18124. if (i > 0)
  18125. parts.push(" ");
  18126. }
  18127. else {
  18128. lines = lines.indent(options.tabWidth);
  18129. }
  18130. parts.push(lines);
  18131. if (i < len - 1 || (!oneLine && util.isTrailingCommaEnabled(options, "arrays")))
  18132. parts.push(",");
  18133. if (!oneLine)
  18134. parts.push("\n");
  18135. }
  18136. }, "elements");
  18137. if (oneLine && options.arrayBracketSpacing) {
  18138. parts.push(" ]");
  18139. }
  18140. else {
  18141. parts.push("]");
  18142. }
  18143. if (n.typeAnnotation) {
  18144. parts.push(path.call(print, "typeAnnotation"));
  18145. }
  18146. return lines.concat(parts);
  18147. case "SequenceExpression":
  18148. return lines.fromString(", ").join(path.map(print, "expressions"));
  18149. case "ThisExpression":
  18150. return lines.fromString("this");
  18151. case "Super":
  18152. return lines.fromString("super");
  18153. case "NullLiteral": // Babel 6 Literal split
  18154. return lines.fromString("null");
  18155. case "RegExpLiteral": // Babel 6 Literal split
  18156. return lines.fromString(n.extra.raw);
  18157. case "BigIntLiteral": // Babel 7 Literal split
  18158. return lines.fromString(n.value + "n");
  18159. case "NumericLiteral": // Babel 6 Literal Split
  18160. // Keep original representation for numeric values not in base 10.
  18161. if (n.extra &&
  18162. typeof n.extra.raw === "string" &&
  18163. Number(n.extra.raw) === n.value) {
  18164. return lines.fromString(n.extra.raw, options);
  18165. }
  18166. return lines.fromString(n.value, options);
  18167. case "BooleanLiteral": // Babel 6 Literal split
  18168. case "StringLiteral": // Babel 6 Literal split
  18169. case "Literal":
  18170. // Numeric values may be in bases other than 10. Use their raw
  18171. // representation if equivalent.
  18172. if (typeof n.value === "number" &&
  18173. typeof n.raw === "string" &&
  18174. Number(n.raw) === n.value) {
  18175. return lines.fromString(n.raw, options);
  18176. }
  18177. if (typeof n.value !== "string") {
  18178. return lines.fromString(n.value, options);
  18179. }
  18180. return lines.fromString(nodeStr(n.value, options), options);
  18181. case "Directive": // Babel 6
  18182. return path.call(print, "value");
  18183. case "DirectiveLiteral": // Babel 6
  18184. return lines.fromString(nodeStr(n.value, options));
  18185. case "InterpreterDirective":
  18186. return lines.fromString("#!" + n.value + "\n", options);
  18187. case "ModuleSpecifier":
  18188. if (n.local) {
  18189. throw new Error("The ESTree ModuleSpecifier type should be abstract");
  18190. }
  18191. // The Esprima ModuleSpecifier type is just a string-valued
  18192. // Literal identifying the imported-from module.
  18193. return lines.fromString(nodeStr(n.value, options), options);
  18194. case "UnaryExpression":
  18195. parts.push(n.operator);
  18196. if (/[a-z]$/.test(n.operator))
  18197. parts.push(" ");
  18198. parts.push(path.call(print, "argument"));
  18199. return lines.concat(parts);
  18200. case "UpdateExpression":
  18201. parts.push(path.call(print, "argument"), n.operator);
  18202. if (n.prefix)
  18203. parts.reverse();
  18204. return lines.concat(parts);
  18205. case "ConditionalExpression":
  18206. return lines.concat([
  18207. path.call(print, "test"),
  18208. " ? ", path.call(print, "consequent"),
  18209. " : ", path.call(print, "alternate")
  18210. ]);
  18211. case "NewExpression":
  18212. parts.push("new ", path.call(print, "callee"));
  18213. if (n.typeParameters) {
  18214. parts.push(path.call(print, "typeParameters"));
  18215. }
  18216. if (n.typeArguments) {
  18217. parts.push(path.call(print, "typeArguments"));
  18218. }
  18219. var args = n.arguments;
  18220. if (args) {
  18221. parts.push(printArgumentsList(path, options, print));
  18222. }
  18223. return lines.concat(parts);
  18224. case "VariableDeclaration":
  18225. if (n.declare) {
  18226. parts.push("declare ");
  18227. }
  18228. parts.push(n.kind, " ");
  18229. var maxLen = 0;
  18230. var printed = path.map(function (childPath) {
  18231. var lines = print(childPath);
  18232. maxLen = Math.max(lines.length, maxLen);
  18233. return lines;
  18234. }, "declarations");
  18235. if (maxLen === 1) {
  18236. parts.push(lines.fromString(", ").join(printed));
  18237. }
  18238. else if (printed.length > 1) {
  18239. parts.push(lines.fromString(",\n").join(printed)
  18240. .indentTail(n.kind.length + 1));
  18241. }
  18242. else {
  18243. parts.push(printed[0]);
  18244. }
  18245. // We generally want to terminate all variable declarations with a
  18246. // semicolon, except when they are children of for loops.
  18247. var parentNode = path.getParentNode();
  18248. if (!namedTypes.ForStatement.check(parentNode) &&
  18249. !namedTypes.ForInStatement.check(parentNode) &&
  18250. !(namedTypes.ForOfStatement &&
  18251. namedTypes.ForOfStatement.check(parentNode)) &&
  18252. !(namedTypes.ForAwaitStatement &&
  18253. namedTypes.ForAwaitStatement.check(parentNode))) {
  18254. parts.push(";");
  18255. }
  18256. return lines.concat(parts);
  18257. case "VariableDeclarator":
  18258. return n.init ? lines.fromString(" = ").join([
  18259. path.call(print, "id"),
  18260. path.call(print, "init")
  18261. ]) : path.call(print, "id");
  18262. case "WithStatement":
  18263. return lines.concat([
  18264. "with (",
  18265. path.call(print, "object"),
  18266. ") ",
  18267. path.call(print, "body")
  18268. ]);
  18269. case "IfStatement":
  18270. var con = adjustClause(path.call(print, "consequent"), options);
  18271. parts.push("if (", path.call(print, "test"), ")", con);
  18272. if (n.alternate)
  18273. parts.push(endsWithBrace(con) ? " else" : "\nelse", adjustClause(path.call(print, "alternate"), options));
  18274. return lines.concat(parts);
  18275. case "ForStatement":
  18276. // TODO Get the for (;;) case right.
  18277. var init = path.call(print, "init"), sep = init.length > 1 ? ";\n" : "; ", forParen = "for (", indented = lines.fromString(sep).join([
  18278. init,
  18279. path.call(print, "test"),
  18280. path.call(print, "update")
  18281. ]).indentTail(forParen.length), head = lines.concat([forParen, indented, ")"]), clause = adjustClause(path.call(print, "body"), options);
  18282. parts.push(head);
  18283. if (head.length > 1) {
  18284. parts.push("\n");
  18285. clause = clause.trimLeft();
  18286. }
  18287. parts.push(clause);
  18288. return lines.concat(parts);
  18289. case "WhileStatement":
  18290. return lines.concat([
  18291. "while (",
  18292. path.call(print, "test"),
  18293. ")",
  18294. adjustClause(path.call(print, "body"), options)
  18295. ]);
  18296. case "ForInStatement":
  18297. // Note: esprima can't actually parse "for each (".
  18298. return lines.concat([
  18299. n.each ? "for each (" : "for (",
  18300. path.call(print, "left"),
  18301. " in ",
  18302. path.call(print, "right"),
  18303. ")",
  18304. adjustClause(path.call(print, "body"), options)
  18305. ]);
  18306. case "ForOfStatement":
  18307. case "ForAwaitStatement":
  18308. parts.push("for ");
  18309. if (n.await || n.type === "ForAwaitStatement") {
  18310. parts.push("await ");
  18311. }
  18312. parts.push("(", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options));
  18313. return lines.concat(parts);
  18314. case "DoWhileStatement":
  18315. var doBody = lines.concat([
  18316. "do",
  18317. adjustClause(path.call(print, "body"), options)
  18318. ]);
  18319. parts.push(doBody);
  18320. if (endsWithBrace(doBody))
  18321. parts.push(" while");
  18322. else
  18323. parts.push("\nwhile");
  18324. parts.push(" (", path.call(print, "test"), ");");
  18325. return lines.concat(parts);
  18326. case "DoExpression":
  18327. var statements = path.call(function (bodyPath) {
  18328. return printStatementSequence(bodyPath, options, print);
  18329. }, "body");
  18330. return lines.concat([
  18331. "do {\n",
  18332. statements.indent(options.tabWidth),
  18333. "\n}"
  18334. ]);
  18335. case "BreakStatement":
  18336. parts.push("break");
  18337. if (n.label)
  18338. parts.push(" ", path.call(print, "label"));
  18339. parts.push(";");
  18340. return lines.concat(parts);
  18341. case "ContinueStatement":
  18342. parts.push("continue");
  18343. if (n.label)
  18344. parts.push(" ", path.call(print, "label"));
  18345. parts.push(";");
  18346. return lines.concat(parts);
  18347. case "LabeledStatement":
  18348. return lines.concat([
  18349. path.call(print, "label"),
  18350. ":\n",
  18351. path.call(print, "body")
  18352. ]);
  18353. case "TryStatement":
  18354. parts.push("try ", path.call(print, "block"));
  18355. if (n.handler) {
  18356. parts.push(" ", path.call(print, "handler"));
  18357. }
  18358. else if (n.handlers) {
  18359. path.each(function (handlerPath) {
  18360. parts.push(" ", print(handlerPath));
  18361. }, "handlers");
  18362. }
  18363. if (n.finalizer) {
  18364. parts.push(" finally ", path.call(print, "finalizer"));
  18365. }
  18366. return lines.concat(parts);
  18367. case "CatchClause":
  18368. parts.push("catch ");
  18369. if (n.param) {
  18370. parts.push("(", path.call(print, "param"));
  18371. }
  18372. if (n.guard) {
  18373. // Note: esprima does not recognize conditional catch clauses.
  18374. parts.push(" if ", path.call(print, "guard"));
  18375. }
  18376. if (n.param) {
  18377. parts.push(") ");
  18378. }
  18379. parts.push(path.call(print, "body"));
  18380. return lines.concat(parts);
  18381. case "ThrowStatement":
  18382. return lines.concat(["throw ", path.call(print, "argument"), ";"]);
  18383. case "SwitchStatement":
  18384. return lines.concat([
  18385. "switch (",
  18386. path.call(print, "discriminant"),
  18387. ") {\n",
  18388. lines.fromString("\n").join(path.map(print, "cases")),
  18389. "\n}"
  18390. ]);
  18391. // Note: ignoring n.lexical because it has no printing consequences.
  18392. case "SwitchCase":
  18393. if (n.test)
  18394. parts.push("case ", path.call(print, "test"), ":");
  18395. else
  18396. parts.push("default:");
  18397. if (n.consequent.length > 0) {
  18398. parts.push("\n", path.call(function (consequentPath) {
  18399. return printStatementSequence(consequentPath, options, print);
  18400. }, "consequent").indent(options.tabWidth));
  18401. }
  18402. return lines.concat(parts);
  18403. case "DebuggerStatement":
  18404. return lines.fromString("debugger;");
  18405. // JSX extensions below.
  18406. case "JSXAttribute":
  18407. parts.push(path.call(print, "name"));
  18408. if (n.value)
  18409. parts.push("=", path.call(print, "value"));
  18410. return lines.concat(parts);
  18411. case "JSXIdentifier":
  18412. return lines.fromString(n.name, options);
  18413. case "JSXNamespacedName":
  18414. return lines.fromString(":").join([
  18415. path.call(print, "namespace"),
  18416. path.call(print, "name")
  18417. ]);
  18418. case "JSXMemberExpression":
  18419. return lines.fromString(".").join([
  18420. path.call(print, "object"),
  18421. path.call(print, "property")
  18422. ]);
  18423. case "JSXSpreadAttribute":
  18424. return lines.concat(["{...", path.call(print, "argument"), "}"]);
  18425. case "JSXSpreadChild":
  18426. return lines.concat(["{...", path.call(print, "expression"), "}"]);
  18427. case "JSXExpressionContainer":
  18428. return lines.concat(["{", path.call(print, "expression"), "}"]);
  18429. case "JSXElement":
  18430. case "JSXFragment":
  18431. var openingPropName = "opening" + (n.type === "JSXElement" ? "Element" : "Fragment");
  18432. var closingPropName = "closing" + (n.type === "JSXElement" ? "Element" : "Fragment");
  18433. var openingLines = path.call(print, openingPropName);
  18434. if (n[openingPropName].selfClosing) {
  18435. assert_1.default.ok(!n[closingPropName], "unexpected " + closingPropName + " element in self-closing " + n.type);
  18436. return openingLines;
  18437. }
  18438. var childLines = lines.concat(path.map(function (childPath) {
  18439. var child = childPath.getValue();
  18440. if (namedTypes.Literal.check(child) &&
  18441. typeof child.value === "string") {
  18442. if (/\S/.test(child.value)) {
  18443. return child.value.replace(/^\s+|\s+$/g, "");
  18444. }
  18445. else if (/\n/.test(child.value)) {
  18446. return "\n";
  18447. }
  18448. }
  18449. return print(childPath);
  18450. }, "children")).indentTail(options.tabWidth);
  18451. var closingLines = path.call(print, closingPropName);
  18452. return lines.concat([
  18453. openingLines,
  18454. childLines,
  18455. closingLines
  18456. ]);
  18457. case "JSXOpeningElement":
  18458. parts.push("<", path.call(print, "name"));
  18459. var attrParts = [];
  18460. path.each(function (attrPath) {
  18461. attrParts.push(" ", print(attrPath));
  18462. }, "attributes");
  18463. var attrLines = lines.concat(attrParts);
  18464. var needLineWrap = (attrLines.length > 1 ||
  18465. attrLines.getLineLength(1) > options.wrapColumn);
  18466. if (needLineWrap) {
  18467. attrParts.forEach(function (part, i) {
  18468. if (part === " ") {
  18469. assert_1.default.strictEqual(i % 2, 0);
  18470. attrParts[i] = "\n";
  18471. }
  18472. });
  18473. attrLines = lines.concat(attrParts).indentTail(options.tabWidth);
  18474. }
  18475. parts.push(attrLines, n.selfClosing ? " />" : ">");
  18476. return lines.concat(parts);
  18477. case "JSXClosingElement":
  18478. return lines.concat(["</", path.call(print, "name"), ">"]);
  18479. case "JSXOpeningFragment":
  18480. return lines.fromString("<>");
  18481. case "JSXClosingFragment":
  18482. return lines.fromString("</>");
  18483. case "JSXText":
  18484. return lines.fromString(n.value, options);
  18485. case "JSXEmptyExpression":
  18486. return lines.fromString("");
  18487. case "TypeAnnotatedIdentifier":
  18488. return lines.concat([
  18489. path.call(print, "annotation"),
  18490. " ",
  18491. path.call(print, "identifier")
  18492. ]);
  18493. case "ClassBody":
  18494. if (n.body.length === 0) {
  18495. return lines.fromString("{}");
  18496. }
  18497. return lines.concat([
  18498. "{\n",
  18499. path.call(function (bodyPath) {
  18500. return printStatementSequence(bodyPath, options, print);
  18501. }, "body").indent(options.tabWidth),
  18502. "\n}"
  18503. ]);
  18504. case "ClassPropertyDefinition":
  18505. parts.push("static ", path.call(print, "definition"));
  18506. if (!namedTypes.MethodDefinition.check(n.definition))
  18507. parts.push(";");
  18508. return lines.concat(parts);
  18509. case "ClassProperty":
  18510. var access = n.accessibility || n.access;
  18511. if (typeof access === "string") {
  18512. parts.push(access, " ");
  18513. }
  18514. if (n.static) {
  18515. parts.push("static ");
  18516. }
  18517. if (n.abstract) {
  18518. parts.push("abstract ");
  18519. }
  18520. if (n.readonly) {
  18521. parts.push("readonly ");
  18522. }
  18523. var key = path.call(print, "key");
  18524. if (n.computed) {
  18525. key = lines.concat(["[", key, "]"]);
  18526. }
  18527. if (n.variance) {
  18528. key = lines.concat([printVariance(path, print), key]);
  18529. }
  18530. parts.push(key);
  18531. if (n.optional) {
  18532. parts.push("?");
  18533. }
  18534. if (n.typeAnnotation) {
  18535. parts.push(path.call(print, "typeAnnotation"));
  18536. }
  18537. if (n.value) {
  18538. parts.push(" = ", path.call(print, "value"));
  18539. }
  18540. parts.push(";");
  18541. return lines.concat(parts);
  18542. case "ClassPrivateProperty":
  18543. if (n.static) {
  18544. parts.push("static ");
  18545. }
  18546. parts.push(path.call(print, "key"));
  18547. if (n.typeAnnotation) {
  18548. parts.push(path.call(print, "typeAnnotation"));
  18549. }
  18550. if (n.value) {
  18551. parts.push(" = ", path.call(print, "value"));
  18552. }
  18553. parts.push(";");
  18554. return lines.concat(parts);
  18555. case "ClassDeclaration":
  18556. case "ClassExpression":
  18557. if (n.declare) {
  18558. parts.push("declare ");
  18559. }
  18560. if (n.abstract) {
  18561. parts.push("abstract ");
  18562. }
  18563. parts.push("class");
  18564. if (n.id) {
  18565. parts.push(" ", path.call(print, "id"));
  18566. }
  18567. if (n.typeParameters) {
  18568. parts.push(path.call(print, "typeParameters"));
  18569. }
  18570. if (n.superClass) {
  18571. parts.push(" extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters"));
  18572. }
  18573. if (n["implements"] && n['implements'].length > 0) {
  18574. parts.push(" implements ", lines.fromString(", ").join(path.map(print, "implements")));
  18575. }
  18576. parts.push(" ", path.call(print, "body"));
  18577. return lines.concat(parts);
  18578. case "TemplateElement":
  18579. return lines.fromString(n.value.raw, options).lockIndentTail();
  18580. case "TemplateLiteral":
  18581. var expressions = path.map(print, "expressions");
  18582. parts.push("`");
  18583. path.each(function (childPath) {
  18584. var i = childPath.getName();
  18585. parts.push(print(childPath));
  18586. if (i < expressions.length) {
  18587. parts.push("${", expressions[i], "}");
  18588. }
  18589. }, "quasis");
  18590. parts.push("`");
  18591. return lines.concat(parts).lockIndentTail();
  18592. case "TaggedTemplateExpression":
  18593. return lines.concat([
  18594. path.call(print, "tag"),
  18595. path.call(print, "quasi")
  18596. ]);
  18597. // These types are unprintable because they serve as abstract
  18598. // supertypes for other (printable) types.
  18599. case "Node":
  18600. case "Printable":
  18601. case "SourceLocation":
  18602. case "Position":
  18603. case "Statement":
  18604. case "Function":
  18605. case "Pattern":
  18606. case "Expression":
  18607. case "Declaration":
  18608. case "Specifier":
  18609. case "NamedSpecifier":
  18610. case "Comment": // Supertype of Block and Line
  18611. case "Flow": // Supertype of all Flow AST node types
  18612. case "FlowType": // Supertype of all Flow types
  18613. case "FlowPredicate": // Supertype of InferredPredicate and DeclaredPredicate
  18614. case "MemberTypeAnnotation": // Flow
  18615. case "Type": // Flow
  18616. case "TSHasOptionalTypeParameterInstantiation":
  18617. case "TSHasOptionalTypeParameters":
  18618. case "TSHasOptionalTypeAnnotation":
  18619. throw new Error("unprintable type: " + JSON.stringify(n.type));
  18620. case "CommentBlock": // Babel block comment.
  18621. case "Block": // Esprima block comment.
  18622. return lines.concat(["/*", lines.fromString(n.value, options), "*/"]);
  18623. case "CommentLine": // Babel line comment.
  18624. case "Line": // Esprima line comment.
  18625. return lines.concat(["//", lines.fromString(n.value, options)]);
  18626. // Type Annotations for Facebook Flow, typically stripped out or
  18627. // transformed away before printing.
  18628. case "TypeAnnotation":
  18629. if (n.typeAnnotation) {
  18630. if (n.typeAnnotation.type !== "FunctionTypeAnnotation") {
  18631. parts.push(": ");
  18632. }
  18633. parts.push(path.call(print, "typeAnnotation"));
  18634. return lines.concat(parts);
  18635. }
  18636. return lines.fromString("");
  18637. case "ExistentialTypeParam":
  18638. case "ExistsTypeAnnotation":
  18639. return lines.fromString("*", options);
  18640. case "EmptyTypeAnnotation":
  18641. return lines.fromString("empty", options);
  18642. case "AnyTypeAnnotation":
  18643. return lines.fromString("any", options);
  18644. case "MixedTypeAnnotation":
  18645. return lines.fromString("mixed", options);
  18646. case "ArrayTypeAnnotation":
  18647. return lines.concat([
  18648. path.call(print, "elementType"),
  18649. "[]"
  18650. ]);
  18651. case "TupleTypeAnnotation":
  18652. var printed = path.map(print, "types");
  18653. var joined = lines.fromString(", ").join(printed);
  18654. var oneLine = joined.getLineLength(1) <= options.wrapColumn;
  18655. if (oneLine) {
  18656. if (options.arrayBracketSpacing) {
  18657. parts.push("[ ");
  18658. }
  18659. else {
  18660. parts.push("[");
  18661. }
  18662. }
  18663. else {
  18664. parts.push("[\n");
  18665. }
  18666. path.each(function (elemPath) {
  18667. var i = elemPath.getName();
  18668. var elem = elemPath.getValue();
  18669. if (!elem) {
  18670. // If the array expression ends with a hole, that hole
  18671. // will be ignored by the interpreter, but if it ends with
  18672. // two (or more) holes, we need to write out two (or more)
  18673. // commas so that the resulting code is interpreted with
  18674. // both (all) of the holes.
  18675. parts.push(",");
  18676. }
  18677. else {
  18678. var lines = printed[i];
  18679. if (oneLine) {
  18680. if (i > 0)
  18681. parts.push(" ");
  18682. }
  18683. else {
  18684. lines = lines.indent(options.tabWidth);
  18685. }
  18686. parts.push(lines);
  18687. if (i < n.types.length - 1 || (!oneLine && util.isTrailingCommaEnabled(options, "arrays")))
  18688. parts.push(",");
  18689. if (!oneLine)
  18690. parts.push("\n");
  18691. }
  18692. }, "types");
  18693. if (oneLine && options.arrayBracketSpacing) {
  18694. parts.push(" ]");
  18695. }
  18696. else {
  18697. parts.push("]");
  18698. }
  18699. return lines.concat(parts);
  18700. case "BooleanTypeAnnotation":
  18701. return lines.fromString("boolean", options);
  18702. case "BooleanLiteralTypeAnnotation":
  18703. assert_1.default.strictEqual(typeof n.value, "boolean");
  18704. return lines.fromString("" + n.value, options);
  18705. case "InterfaceTypeAnnotation":
  18706. parts.push("interface");
  18707. if (n.extends && n.extends.length > 0) {
  18708. parts.push(" extends ", lines.fromString(", ").join(path.map(print, "extends")));
  18709. }
  18710. parts.push(" ", path.call(print, "body"));
  18711. return lines.concat(parts);
  18712. case "DeclareClass":
  18713. return printFlowDeclaration(path, [
  18714. "class ",
  18715. path.call(print, "id"),
  18716. " ",
  18717. path.call(print, "body"),
  18718. ]);
  18719. case "DeclareFunction":
  18720. return printFlowDeclaration(path, [
  18721. "function ",
  18722. path.call(print, "id"),
  18723. ";"
  18724. ]);
  18725. case "DeclareModule":
  18726. return printFlowDeclaration(path, [
  18727. "module ",
  18728. path.call(print, "id"),
  18729. " ",
  18730. path.call(print, "body"),
  18731. ]);
  18732. case "DeclareModuleExports":
  18733. return printFlowDeclaration(path, [
  18734. "module.exports",
  18735. path.call(print, "typeAnnotation"),
  18736. ]);
  18737. case "DeclareVariable":
  18738. return printFlowDeclaration(path, [
  18739. "var ",
  18740. path.call(print, "id"),
  18741. ";"
  18742. ]);
  18743. case "DeclareExportDeclaration":
  18744. case "DeclareExportAllDeclaration":
  18745. return lines.concat([
  18746. "declare ",
  18747. printExportDeclaration(path, options, print)
  18748. ]);
  18749. case "InferredPredicate":
  18750. return lines.fromString("%checks", options);
  18751. case "DeclaredPredicate":
  18752. return lines.concat([
  18753. "%checks(",
  18754. path.call(print, "value"),
  18755. ")"
  18756. ]);
  18757. case "FunctionTypeAnnotation":
  18758. // FunctionTypeAnnotation is ambiguous:
  18759. // declare function(a: B): void; OR
  18760. // var A: (a: B) => void;
  18761. var parent = path.getParentNode(0);
  18762. var isArrowFunctionTypeAnnotation = !(namedTypes.ObjectTypeCallProperty.check(parent) ||
  18763. (namedTypes.ObjectTypeInternalSlot.check(parent) && parent.method) ||
  18764. namedTypes.DeclareFunction.check(path.getParentNode(2)));
  18765. var needsColon = isArrowFunctionTypeAnnotation &&
  18766. !namedTypes.FunctionTypeParam.check(parent);
  18767. if (needsColon) {
  18768. parts.push(": ");
  18769. }
  18770. parts.push("(", printFunctionParams(path, options, print), ")");
  18771. // The returnType is not wrapped in a TypeAnnotation, so the colon
  18772. // needs to be added separately.
  18773. if (n.returnType) {
  18774. parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"));
  18775. }
  18776. return lines.concat(parts);
  18777. case "FunctionTypeParam":
  18778. return lines.concat([
  18779. path.call(print, "name"),
  18780. n.optional ? '?' : '',
  18781. ": ",
  18782. path.call(print, "typeAnnotation"),
  18783. ]);
  18784. case "GenericTypeAnnotation":
  18785. return lines.concat([
  18786. path.call(print, "id"),
  18787. path.call(print, "typeParameters")
  18788. ]);
  18789. case "DeclareInterface":
  18790. parts.push("declare ");
  18791. // Fall through to InterfaceDeclaration...
  18792. case "InterfaceDeclaration":
  18793. case "TSInterfaceDeclaration":
  18794. if (n.declare) {
  18795. parts.push("declare ");
  18796. }
  18797. parts.push("interface ", path.call(print, "id"), path.call(print, "typeParameters"), " ");
  18798. if (n["extends"] && n["extends"].length > 0) {
  18799. parts.push("extends ", lines.fromString(", ").join(path.map(print, "extends")), " ");
  18800. }
  18801. if (n.body) {
  18802. parts.push(path.call(print, "body"));
  18803. }
  18804. return lines.concat(parts);
  18805. case "ClassImplements":
  18806. case "InterfaceExtends":
  18807. return lines.concat([
  18808. path.call(print, "id"),
  18809. path.call(print, "typeParameters")
  18810. ]);
  18811. case "IntersectionTypeAnnotation":
  18812. return lines.fromString(" & ").join(path.map(print, "types"));
  18813. case "NullableTypeAnnotation":
  18814. return lines.concat([
  18815. "?",
  18816. path.call(print, "typeAnnotation")
  18817. ]);
  18818. case "NullLiteralTypeAnnotation":
  18819. return lines.fromString("null", options);
  18820. case "ThisTypeAnnotation":
  18821. return lines.fromString("this", options);
  18822. case "NumberTypeAnnotation":
  18823. return lines.fromString("number", options);
  18824. case "ObjectTypeCallProperty":
  18825. return path.call(print, "value");
  18826. case "ObjectTypeIndexer":
  18827. return lines.concat([
  18828. printVariance(path, print),
  18829. "[",
  18830. path.call(print, "id"),
  18831. ": ",
  18832. path.call(print, "key"),
  18833. "]: ",
  18834. path.call(print, "value")
  18835. ]);
  18836. case "ObjectTypeProperty":
  18837. return lines.concat([
  18838. printVariance(path, print),
  18839. path.call(print, "key"),
  18840. n.optional ? "?" : "",
  18841. ": ",
  18842. path.call(print, "value")
  18843. ]);
  18844. case "ObjectTypeInternalSlot":
  18845. return lines.concat([
  18846. n.static ? "static " : "",
  18847. "[[",
  18848. path.call(print, "id"),
  18849. "]]",
  18850. n.optional ? "?" : "",
  18851. n.value.type !== "FunctionTypeAnnotation" ? ": " : "",
  18852. path.call(print, "value")
  18853. ]);
  18854. case "QualifiedTypeIdentifier":
  18855. return lines.concat([
  18856. path.call(print, "qualification"),
  18857. ".",
  18858. path.call(print, "id")
  18859. ]);
  18860. case "StringLiteralTypeAnnotation":
  18861. return lines.fromString(nodeStr(n.value, options), options);
  18862. case "NumberLiteralTypeAnnotation":
  18863. case "NumericLiteralTypeAnnotation":
  18864. assert_1.default.strictEqual(typeof n.value, "number");
  18865. return lines.fromString(JSON.stringify(n.value), options);
  18866. case "StringTypeAnnotation":
  18867. return lines.fromString("string", options);
  18868. case "DeclareTypeAlias":
  18869. parts.push("declare ");
  18870. // Fall through to TypeAlias...
  18871. case "TypeAlias":
  18872. return lines.concat([
  18873. "type ",
  18874. path.call(print, "id"),
  18875. path.call(print, "typeParameters"),
  18876. " = ",
  18877. path.call(print, "right"),
  18878. ";"
  18879. ]);
  18880. case "DeclareOpaqueType":
  18881. parts.push("declare ");
  18882. // Fall through to OpaqueType...
  18883. case "OpaqueType":
  18884. parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
  18885. if (n["supertype"]) {
  18886. parts.push(": ", path.call(print, "supertype"));
  18887. }
  18888. if (n["impltype"]) {
  18889. parts.push(" = ", path.call(print, "impltype"));
  18890. }
  18891. parts.push(";");
  18892. return lines.concat(parts);
  18893. case "TypeCastExpression":
  18894. return lines.concat([
  18895. "(",
  18896. path.call(print, "expression"),
  18897. path.call(print, "typeAnnotation"),
  18898. ")"
  18899. ]);
  18900. case "TypeParameterDeclaration":
  18901. case "TypeParameterInstantiation":
  18902. return lines.concat([
  18903. "<",
  18904. lines.fromString(", ").join(path.map(print, "params")),
  18905. ">"
  18906. ]);
  18907. case "Variance":
  18908. if (n.kind === "plus") {
  18909. return lines.fromString("+");
  18910. }
  18911. if (n.kind === "minus") {
  18912. return lines.fromString("-");
  18913. }
  18914. return lines.fromString("");
  18915. case "TypeParameter":
  18916. if (n.variance) {
  18917. parts.push(printVariance(path, print));
  18918. }
  18919. parts.push(path.call(print, 'name'));
  18920. if (n.bound) {
  18921. parts.push(path.call(print, 'bound'));
  18922. }
  18923. if (n['default']) {
  18924. parts.push('=', path.call(print, 'default'));
  18925. }
  18926. return lines.concat(parts);
  18927. case "TypeofTypeAnnotation":
  18928. return lines.concat([
  18929. lines.fromString("typeof ", options),
  18930. path.call(print, "argument")
  18931. ]);
  18932. case "UnionTypeAnnotation":
  18933. return lines.fromString(" | ").join(path.map(print, "types"));
  18934. case "VoidTypeAnnotation":
  18935. return lines.fromString("void", options);
  18936. case "NullTypeAnnotation":
  18937. return lines.fromString("null", options);
  18938. // Type Annotations for TypeScript (when using Babylon as parser)
  18939. case "TSType":
  18940. throw new Error("unprintable type: " + JSON.stringify(n.type));
  18941. case "TSNumberKeyword":
  18942. return lines.fromString("number", options);
  18943. case "TSBigIntKeyword":
  18944. return lines.fromString("bigint", options);
  18945. case "TSObjectKeyword":
  18946. return lines.fromString("object", options);
  18947. case "TSBooleanKeyword":
  18948. return lines.fromString("boolean", options);
  18949. case "TSStringKeyword":
  18950. return lines.fromString("string", options);
  18951. case "TSSymbolKeyword":
  18952. return lines.fromString("symbol", options);
  18953. case "TSAnyKeyword":
  18954. return lines.fromString("any", options);
  18955. case "TSVoidKeyword":
  18956. return lines.fromString("void", options);
  18957. case "TSThisType":
  18958. return lines.fromString("this", options);
  18959. case "TSNullKeyword":
  18960. return lines.fromString("null", options);
  18961. case "TSUndefinedKeyword":
  18962. return lines.fromString("undefined", options);
  18963. case "TSUnknownKeyword":
  18964. return lines.fromString("unknown", options);
  18965. case "TSNeverKeyword":
  18966. return lines.fromString("never", options);
  18967. case "TSArrayType":
  18968. return lines.concat([
  18969. path.call(print, "elementType"),
  18970. "[]"
  18971. ]);
  18972. case "TSLiteralType":
  18973. return path.call(print, "literal");
  18974. case "TSUnionType":
  18975. return lines.fromString(" | ").join(path.map(print, "types"));
  18976. case "TSIntersectionType":
  18977. return lines.fromString(" & ").join(path.map(print, "types"));
  18978. case "TSConditionalType":
  18979. parts.push(path.call(print, "checkType"), " extends ", path.call(print, "extendsType"), " ? ", path.call(print, "trueType"), " : ", path.call(print, "falseType"));
  18980. return lines.concat(parts);
  18981. case "TSInferType":
  18982. parts.push("infer ", path.call(print, "typeParameter"));
  18983. return lines.concat(parts);
  18984. case "TSParenthesizedType":
  18985. return lines.concat([
  18986. "(",
  18987. path.call(print, "typeAnnotation"),
  18988. ")"
  18989. ]);
  18990. case "TSFunctionType":
  18991. return lines.concat([
  18992. path.call(print, "typeParameters"),
  18993. "(",
  18994. printFunctionParams(path, options, print),
  18995. ")",
  18996. path.call(print, "typeAnnotation")
  18997. ]);
  18998. case "TSConstructorType":
  18999. return lines.concat([
  19000. "new ",
  19001. path.call(print, 'typeParameters'),
  19002. "(",
  19003. printFunctionParams(path, options, print),
  19004. ")",
  19005. path.call(print, "typeAnnotation")
  19006. ]);
  19007. case "TSMappedType": {
  19008. parts.push(n.readonly ? "readonly " : "", "[", path.call(print, "typeParameter"), "]", n.optional ? "?" : "");
  19009. if (n.typeAnnotation) {
  19010. parts.push(": ", path.call(print, "typeAnnotation"), ";");
  19011. }
  19012. return lines.concat([
  19013. "{\n",
  19014. lines.concat(parts).indent(options.tabWidth),
  19015. "\n}",
  19016. ]);
  19017. }
  19018. case "TSTupleType":
  19019. return lines.concat([
  19020. "[",
  19021. lines.fromString(", ").join(path.map(print, "elementTypes")),
  19022. "]"
  19023. ]);
  19024. case "TSRestType":
  19025. return lines.concat([
  19026. "...",
  19027. path.call(print, "typeAnnotation"),
  19028. "[]"
  19029. ]);
  19030. case "TSOptionalType":
  19031. return lines.concat([
  19032. path.call(print, "typeAnnotation"),
  19033. "?"
  19034. ]);
  19035. case "TSIndexedAccessType":
  19036. return lines.concat([
  19037. path.call(print, "objectType"),
  19038. "[",
  19039. path.call(print, "indexType"),
  19040. "]"
  19041. ]);
  19042. case "TSTypeOperator":
  19043. return lines.concat([
  19044. path.call(print, "operator"),
  19045. " ",
  19046. path.call(print, "typeAnnotation")
  19047. ]);
  19048. case "TSTypeLiteral": {
  19049. var memberLines_1 = lines.fromString(",\n").join(path.map(print, "members"));
  19050. if (memberLines_1.isEmpty()) {
  19051. return lines.fromString("{}", options);
  19052. }
  19053. parts.push("{\n", memberLines_1.indent(options.tabWidth), "\n}");
  19054. return lines.concat(parts);
  19055. }
  19056. case "TSEnumMember":
  19057. parts.push(path.call(print, "id"));
  19058. if (n.initializer) {
  19059. parts.push(" = ", path.call(print, "initializer"));
  19060. }
  19061. return lines.concat(parts);
  19062. case "TSTypeQuery":
  19063. return lines.concat([
  19064. "typeof ",
  19065. path.call(print, "exprName"),
  19066. ]);
  19067. case "TSParameterProperty":
  19068. if (n.accessibility) {
  19069. parts.push(n.accessibility, " ");
  19070. }
  19071. if (n.export) {
  19072. parts.push("export ");
  19073. }
  19074. if (n.static) {
  19075. parts.push("static ");
  19076. }
  19077. if (n.readonly) {
  19078. parts.push("readonly ");
  19079. }
  19080. parts.push(path.call(print, "parameter"));
  19081. return lines.concat(parts);
  19082. case "TSTypeReference":
  19083. return lines.concat([
  19084. path.call(print, "typeName"),
  19085. path.call(print, "typeParameters")
  19086. ]);
  19087. case "TSQualifiedName":
  19088. return lines.concat([
  19089. path.call(print, "left"),
  19090. ".",
  19091. path.call(print, "right")
  19092. ]);
  19093. case "TSAsExpression": {
  19094. var withParens = n.extra && n.extra.parenthesized === true;
  19095. if (withParens)
  19096. parts.push("(");
  19097. parts.push(path.call(print, "expression"), lines.fromString(" as "), path.call(print, "typeAnnotation"));
  19098. if (withParens)
  19099. parts.push(")");
  19100. return lines.concat(parts);
  19101. }
  19102. case "TSNonNullExpression":
  19103. return lines.concat([
  19104. path.call(print, "expression"),
  19105. "!"
  19106. ]);
  19107. case "TSTypeAnnotation": {
  19108. // similar to flow's FunctionTypeAnnotation, this can be
  19109. // ambiguous: it can be prefixed by => or :
  19110. // in a type predicate, it takes the for u is U
  19111. var parent = path.getParentNode(0);
  19112. var prefix = ": ";
  19113. if (namedTypes.TSFunctionType.check(parent) || namedTypes.TSConstructorType.check(parent)) {
  19114. prefix = " => ";
  19115. }
  19116. if (namedTypes.TSTypePredicate.check(parent)) {
  19117. prefix = " is ";
  19118. }
  19119. return lines.concat([
  19120. prefix,
  19121. path.call(print, "typeAnnotation")
  19122. ]);
  19123. }
  19124. case "TSIndexSignature":
  19125. return lines.concat([
  19126. n.readonly ? "readonly " : "",
  19127. "[",
  19128. path.map(print, "parameters"),
  19129. "]",
  19130. path.call(print, "typeAnnotation")
  19131. ]);
  19132. case "TSPropertySignature":
  19133. parts.push(printVariance(path, print), n.readonly ? "readonly " : "");
  19134. if (n.computed) {
  19135. parts.push("[", path.call(print, "key"), "]");
  19136. }
  19137. else {
  19138. parts.push(path.call(print, "key"));
  19139. }
  19140. parts.push(n.optional ? "?" : "", path.call(print, "typeAnnotation"));
  19141. return lines.concat(parts);
  19142. case "TSMethodSignature":
  19143. if (n.computed) {
  19144. parts.push("[", path.call(print, "key"), "]");
  19145. }
  19146. else {
  19147. parts.push(path.call(print, "key"));
  19148. }
  19149. if (n.optional) {
  19150. parts.push("?");
  19151. }
  19152. parts.push(path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ")", path.call(print, "typeAnnotation"));
  19153. return lines.concat(parts);
  19154. case "TSTypePredicate":
  19155. return lines.concat([
  19156. path.call(print, "parameterName"),
  19157. path.call(print, "typeAnnotation")
  19158. ]);
  19159. case "TSCallSignatureDeclaration":
  19160. return lines.concat([
  19161. path.call(print, "typeParameters"),
  19162. "(",
  19163. printFunctionParams(path, options, print),
  19164. ")",
  19165. path.call(print, "typeAnnotation")
  19166. ]);
  19167. case "TSConstructSignatureDeclaration":
  19168. if (n.typeParameters) {
  19169. parts.push("new", path.call(print, "typeParameters"));
  19170. }
  19171. else {
  19172. parts.push("new ");
  19173. }
  19174. parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "typeAnnotation"));
  19175. return lines.concat(parts);
  19176. case "TSTypeAliasDeclaration":
  19177. return lines.concat([
  19178. n.declare ? "declare " : "",
  19179. "type ",
  19180. path.call(print, "id"),
  19181. path.call(print, "typeParameters"),
  19182. " = ",
  19183. path.call(print, "typeAnnotation"),
  19184. ";"
  19185. ]);
  19186. case "TSTypeParameter":
  19187. parts.push(path.call(print, "name"));
  19188. // ambiguous because of TSMappedType
  19189. var parent = path.getParentNode(0);
  19190. var isInMappedType = namedTypes.TSMappedType.check(parent);
  19191. if (n.constraint) {
  19192. parts.push(isInMappedType ? " in " : " extends ", path.call(print, "constraint"));
  19193. }
  19194. if (n["default"]) {
  19195. parts.push(" = ", path.call(print, "default"));
  19196. }
  19197. return lines.concat(parts);
  19198. case "TSTypeAssertion":
  19199. var withParens = n.extra && n.extra.parenthesized === true;
  19200. if (withParens) {
  19201. parts.push("(");
  19202. }
  19203. parts.push("<", path.call(print, "typeAnnotation"), "> ", path.call(print, "expression"));
  19204. if (withParens) {
  19205. parts.push(")");
  19206. }
  19207. return lines.concat(parts);
  19208. case "TSTypeParameterDeclaration":
  19209. case "TSTypeParameterInstantiation":
  19210. return lines.concat([
  19211. "<",
  19212. lines.fromString(", ").join(path.map(print, "params")),
  19213. ">"
  19214. ]);
  19215. case "TSEnumDeclaration":
  19216. parts.push(n.declare ? "declare " : "", n.const ? "const " : "", "enum ", path.call(print, "id"));
  19217. var memberLines = lines.fromString(",\n").join(path.map(print, "members"));
  19218. if (memberLines.isEmpty()) {
  19219. parts.push(" {}");
  19220. }
  19221. else {
  19222. parts.push(" {\n", memberLines.indent(options.tabWidth), "\n}");
  19223. }
  19224. return lines.concat(parts);
  19225. case "TSExpressionWithTypeArguments":
  19226. return lines.concat([
  19227. path.call(print, "expression"),
  19228. path.call(print, "typeParameters")
  19229. ]);
  19230. case "TSInterfaceBody":
  19231. var lines$1 = lines.fromString(";\n").join(path.map(print, "body"));
  19232. if (lines$1.isEmpty()) {
  19233. return lines.fromString("{}", options);
  19234. }
  19235. return lines.concat([
  19236. "{\n",
  19237. lines$1.indent(options.tabWidth), ";",
  19238. "\n}",
  19239. ]);
  19240. case "TSImportType":
  19241. parts.push("import(", path.call(print, "argument"), ")");
  19242. if (n.qualifier) {
  19243. parts.push(".", path.call(print, "qualifier"));
  19244. }
  19245. if (n.typeParameters) {
  19246. parts.push(path.call(print, "typeParameters"));
  19247. }
  19248. return lines.concat(parts);
  19249. case "TSImportEqualsDeclaration":
  19250. if (n.isExport) {
  19251. parts.push("export ");
  19252. }
  19253. parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
  19254. return maybeAddSemicolon(lines.concat(parts));
  19255. case "TSExternalModuleReference":
  19256. return lines.concat(["require(", path.call(print, "expression"), ")"]);
  19257. case "TSModuleDeclaration": {
  19258. var parent_1 = path.getParentNode();
  19259. if (parent_1.type === "TSModuleDeclaration") {
  19260. parts.push(".");
  19261. }
  19262. else {
  19263. if (n.declare) {
  19264. parts.push("declare ");
  19265. }
  19266. if (!n.global) {
  19267. var isExternal = n.id.type === "StringLiteral" ||
  19268. (n.id.type === "Literal" &&
  19269. typeof n.id.value === "string");
  19270. if (isExternal) {
  19271. parts.push("module ");
  19272. }
  19273. else if (n.loc &&
  19274. n.loc.lines &&
  19275. n.id.loc) {
  19276. var prefix_1 = n.loc.lines.sliceString(n.loc.start, n.id.loc.start);
  19277. // These keywords are fundamentally ambiguous in the
  19278. // Babylon parser, and not reflected in the AST, so
  19279. // the best we can do is to match the original code,
  19280. // when possible.
  19281. if (prefix_1.indexOf("module") >= 0) {
  19282. parts.push("module ");
  19283. }
  19284. else {
  19285. parts.push("namespace ");
  19286. }
  19287. }
  19288. else {
  19289. parts.push("namespace ");
  19290. }
  19291. }
  19292. }
  19293. parts.push(path.call(print, "id"));
  19294. if (n.body && n.body.type === "TSModuleDeclaration") {
  19295. parts.push(path.call(print, "body"));
  19296. }
  19297. else if (n.body) {
  19298. var bodyLines = path.call(print, "body");
  19299. if (bodyLines.isEmpty()) {
  19300. parts.push(" {}");
  19301. }
  19302. else {
  19303. parts.push(" {\n", bodyLines.indent(options.tabWidth), "\n}");
  19304. }
  19305. }
  19306. return lines.concat(parts);
  19307. }
  19308. case "TSModuleBlock":
  19309. return path.call(function (bodyPath) {
  19310. return printStatementSequence(bodyPath, options, print);
  19311. }, "body");
  19312. // Unhandled types below. If encountered, nodes of these types should
  19313. // be either left alone or desugared into AST types that are fully
  19314. // supported by the pretty-printer.
  19315. case "ClassHeritage": // TODO
  19316. case "ComprehensionBlock": // TODO
  19317. case "ComprehensionExpression": // TODO
  19318. case "Glob": // TODO
  19319. case "GeneratorExpression": // TODO
  19320. case "LetStatement": // TODO
  19321. case "LetExpression": // TODO
  19322. case "GraphExpression": // TODO
  19323. case "GraphIndexExpression": // TODO
  19324. // XML types that nobody cares about or needs to print.
  19325. case "XMLDefaultDeclaration":
  19326. case "XMLAnyName":
  19327. case "XMLQualifiedIdentifier":
  19328. case "XMLFunctionQualifiedIdentifier":
  19329. case "XMLAttributeSelector":
  19330. case "XMLFilterExpression":
  19331. case "XML":
  19332. case "XMLElement":
  19333. case "XMLList":
  19334. case "XMLEscape":
  19335. case "XMLText":
  19336. case "XMLStartTag":
  19337. case "XMLEndTag":
  19338. case "XMLPointTag":
  19339. case "XMLName":
  19340. case "XMLAttribute":
  19341. case "XMLCdata":
  19342. case "XMLComment":
  19343. case "XMLProcessingInstruction":
  19344. default:
  19345. debugger;
  19346. throw new Error("unknown type: " + JSON.stringify(n.type));
  19347. }
  19348. }
  19349. function printDecorators(path, printPath) {
  19350. var parts = [];
  19351. var node = path.getValue();
  19352. if (node.decorators &&
  19353. node.decorators.length > 0 &&
  19354. // If the parent node is an export declaration, it will be
  19355. // responsible for printing node.decorators.
  19356. !util.getParentExportDeclaration(path)) {
  19357. path.each(function (decoratorPath) {
  19358. parts.push(printPath(decoratorPath), "\n");
  19359. }, "decorators");
  19360. }
  19361. else if (util.isExportDeclaration(node) &&
  19362. node.declaration &&
  19363. node.declaration.decorators) {
  19364. // Export declarations are responsible for printing any decorators
  19365. // that logically apply to node.declaration.
  19366. path.each(function (decoratorPath) {
  19367. parts.push(printPath(decoratorPath), "\n");
  19368. }, "declaration", "decorators");
  19369. }
  19370. return lines.concat(parts);
  19371. }
  19372. function printStatementSequence(path, options, print) {
  19373. var filtered = [];
  19374. var sawComment = false;
  19375. var sawStatement = false;
  19376. path.each(function (stmtPath) {
  19377. var stmt = stmtPath.getValue();
  19378. // Just in case the AST has been modified to contain falsy
  19379. // "statements," it's safer simply to skip them.
  19380. if (!stmt) {
  19381. return;
  19382. }
  19383. // Skip printing EmptyStatement nodes to avoid leaving stray
  19384. // semicolons lying around.
  19385. if (stmt.type === "EmptyStatement" &&
  19386. !(stmt.comments && stmt.comments.length > 0)) {
  19387. return;
  19388. }
  19389. if (namedTypes.Comment.check(stmt)) {
  19390. // The pretty printer allows a dangling Comment node to act as
  19391. // a Statement when the Comment can't be attached to any other
  19392. // non-Comment node in the tree.
  19393. sawComment = true;
  19394. }
  19395. else if (namedTypes.Statement.check(stmt)) {
  19396. sawStatement = true;
  19397. }
  19398. else {
  19399. // When the pretty printer encounters a string instead of an
  19400. // AST node, it just prints the string. This behavior can be
  19401. // useful for fine-grained formatting decisions like inserting
  19402. // blank lines.
  19403. isString.assert(stmt);
  19404. }
  19405. // We can't hang onto stmtPath outside of this function, because
  19406. // it's just a reference to a mutable FastPath object, so we have
  19407. // to go ahead and print it here.
  19408. filtered.push({
  19409. node: stmt,
  19410. printed: print(stmtPath)
  19411. });
  19412. });
  19413. if (sawComment) {
  19414. assert_1.default.strictEqual(sawStatement, false, "Comments may appear as statements in otherwise empty statement " +
  19415. "lists, but may not coexist with non-Comment nodes.");
  19416. }
  19417. var prevTrailingSpace = null;
  19418. var len = filtered.length;
  19419. var parts = [];
  19420. filtered.forEach(function (info, i) {
  19421. var printed = info.printed;
  19422. var stmt = info.node;
  19423. var multiLine = printed.length > 1;
  19424. var notFirst = i > 0;
  19425. var notLast = i < len - 1;
  19426. var leadingSpace;
  19427. var trailingSpace;
  19428. var lines = stmt && stmt.loc && stmt.loc.lines;
  19429. var trueLoc = lines && options.reuseWhitespace &&
  19430. util.getTrueLoc(stmt, lines);
  19431. if (notFirst) {
  19432. if (trueLoc) {
  19433. var beforeStart = lines.skipSpaces(trueLoc.start, true);
  19434. var beforeStartLine = beforeStart ? beforeStart.line : 1;
  19435. var leadingGap = trueLoc.start.line - beforeStartLine;
  19436. leadingSpace = Array(leadingGap + 1).join("\n");
  19437. }
  19438. else {
  19439. leadingSpace = multiLine ? "\n\n" : "\n";
  19440. }
  19441. }
  19442. else {
  19443. leadingSpace = "";
  19444. }
  19445. if (notLast) {
  19446. if (trueLoc) {
  19447. var afterEnd = lines.skipSpaces(trueLoc.end);
  19448. var afterEndLine = afterEnd ? afterEnd.line : lines.length;
  19449. var trailingGap = afterEndLine - trueLoc.end.line;
  19450. trailingSpace = Array(trailingGap + 1).join("\n");
  19451. }
  19452. else {
  19453. trailingSpace = multiLine ? "\n\n" : "\n";
  19454. }
  19455. }
  19456. else {
  19457. trailingSpace = "";
  19458. }
  19459. parts.push(maxSpace(prevTrailingSpace, leadingSpace), printed);
  19460. if (notLast) {
  19461. prevTrailingSpace = trailingSpace;
  19462. }
  19463. else if (trailingSpace) {
  19464. parts.push(trailingSpace);
  19465. }
  19466. });
  19467. return lines.concat(parts);
  19468. }
  19469. function maxSpace(s1, s2) {
  19470. if (!s1 && !s2) {
  19471. return lines.fromString("");
  19472. }
  19473. if (!s1) {
  19474. return lines.fromString(s2);
  19475. }
  19476. if (!s2) {
  19477. return lines.fromString(s1);
  19478. }
  19479. var spaceLines1 = lines.fromString(s1);
  19480. var spaceLines2 = lines.fromString(s2);
  19481. if (spaceLines2.length > spaceLines1.length) {
  19482. return spaceLines2;
  19483. }
  19484. return spaceLines1;
  19485. }
  19486. function printMethod(path, options, print) {
  19487. var node = path.getNode();
  19488. var kind = node.kind;
  19489. var parts = [];
  19490. var nodeValue = node.value;
  19491. if (!namedTypes.FunctionExpression.check(nodeValue)) {
  19492. nodeValue = node;
  19493. }
  19494. var access = node.accessibility || node.access;
  19495. if (typeof access === "string") {
  19496. parts.push(access, " ");
  19497. }
  19498. if (node.static) {
  19499. parts.push("static ");
  19500. }
  19501. if (node.abstract) {
  19502. parts.push("abstract ");
  19503. }
  19504. if (node.readonly) {
  19505. parts.push("readonly ");
  19506. }
  19507. if (nodeValue.async) {
  19508. parts.push("async ");
  19509. }
  19510. if (nodeValue.generator) {
  19511. parts.push("*");
  19512. }
  19513. if (kind === "get" || kind === "set") {
  19514. parts.push(kind, " ");
  19515. }
  19516. var key = path.call(print, "key");
  19517. if (node.computed) {
  19518. key = lines.concat(["[", key, "]"]);
  19519. }
  19520. parts.push(key);
  19521. if (node.optional) {
  19522. parts.push("?");
  19523. }
  19524. if (node === nodeValue) {
  19525. parts.push(path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ")", path.call(print, "returnType"));
  19526. if (node.body) {
  19527. parts.push(" ", path.call(print, "body"));
  19528. }
  19529. else {
  19530. parts.push(";");
  19531. }
  19532. }
  19533. else {
  19534. parts.push(path.call(print, "value", "typeParameters"), "(", path.call(function (valuePath) {
  19535. return printFunctionParams(valuePath, options, print);
  19536. }, "value"), ")", path.call(print, "value", "returnType"));
  19537. if (nodeValue.body) {
  19538. parts.push(" ", path.call(print, "value", "body"));
  19539. }
  19540. else {
  19541. parts.push(";");
  19542. }
  19543. }
  19544. return lines.concat(parts);
  19545. }
  19546. function printArgumentsList(path, options, print) {
  19547. var printed = path.map(print, "arguments");
  19548. var trailingComma = util.isTrailingCommaEnabled(options, "parameters");
  19549. var joined = lines.fromString(", ").join(printed);
  19550. if (joined.getLineLength(1) > options.wrapColumn) {
  19551. joined = lines.fromString(",\n").join(printed);
  19552. return lines.concat([
  19553. "(\n",
  19554. joined.indent(options.tabWidth),
  19555. trailingComma ? ",\n)" : "\n)"
  19556. ]);
  19557. }
  19558. return lines.concat(["(", joined, ")"]);
  19559. }
  19560. function printFunctionParams(path, options, print) {
  19561. var fun = path.getValue();
  19562. if (fun.params) {
  19563. var params = fun.params;
  19564. var printed = path.map(print, "params");
  19565. }
  19566. else if (fun.parameters) {
  19567. params = fun.parameters;
  19568. printed = path.map(print, "parameters");
  19569. }
  19570. if (fun.defaults) {
  19571. path.each(function (defExprPath) {
  19572. var i = defExprPath.getName();
  19573. var p = printed[i];
  19574. if (p && defExprPath.getValue()) {
  19575. printed[i] = lines.concat([p, " = ", print(defExprPath)]);
  19576. }
  19577. }, "defaults");
  19578. }
  19579. if (fun.rest) {
  19580. printed.push(lines.concat(["...", path.call(print, "rest")]));
  19581. }
  19582. var joined = lines.fromString(", ").join(printed);
  19583. if (joined.length > 1 ||
  19584. joined.getLineLength(1) > options.wrapColumn) {
  19585. joined = lines.fromString(",\n").join(printed);
  19586. if (util.isTrailingCommaEnabled(options, "parameters") &&
  19587. !fun.rest &&
  19588. params[params.length - 1].type !== 'RestElement') {
  19589. joined = lines.concat([joined, ",\n"]);
  19590. }
  19591. else {
  19592. joined = lines.concat([joined, "\n"]);
  19593. }
  19594. return lines.concat(["\n", joined.indent(options.tabWidth)]);
  19595. }
  19596. return joined;
  19597. }
  19598. function printExportDeclaration(path, options, print) {
  19599. var decl = path.getValue();
  19600. var parts = ["export "];
  19601. if (decl.exportKind && decl.exportKind !== "value") {
  19602. parts.push(decl.exportKind + " ");
  19603. }
  19604. var shouldPrintSpaces = options.objectCurlySpacing;
  19605. namedTypes.Declaration.assert(decl);
  19606. if (decl["default"] ||
  19607. decl.type === "ExportDefaultDeclaration") {
  19608. parts.push("default ");
  19609. }
  19610. if (decl.declaration) {
  19611. parts.push(path.call(print, "declaration"));
  19612. }
  19613. else if (decl.specifiers) {
  19614. if (decl.specifiers.length === 1 &&
  19615. decl.specifiers[0].type === "ExportBatchSpecifier") {
  19616. parts.push("*");
  19617. }
  19618. else if (decl.specifiers.length === 0) {
  19619. parts.push("{}");
  19620. }
  19621. else if (decl.specifiers[0].type === 'ExportDefaultSpecifier') {
  19622. var unbracedSpecifiers_2 = [];
  19623. var bracedSpecifiers_2 = [];
  19624. path.each(function (specifierPath) {
  19625. var spec = specifierPath.getValue();
  19626. if (spec.type === "ExportDefaultSpecifier") {
  19627. unbracedSpecifiers_2.push(print(specifierPath));
  19628. }
  19629. else {
  19630. bracedSpecifiers_2.push(print(specifierPath));
  19631. }
  19632. }, "specifiers");
  19633. unbracedSpecifiers_2.forEach(function (lines, i) {
  19634. if (i > 0) {
  19635. parts.push(", ");
  19636. }
  19637. parts.push(lines);
  19638. });
  19639. if (bracedSpecifiers_2.length > 0) {
  19640. var lines_3 = lines.fromString(", ").join(bracedSpecifiers_2);
  19641. if (lines_3.getLineLength(1) > options.wrapColumn) {
  19642. lines_3 = lines.concat([
  19643. lines.fromString(",\n").join(bracedSpecifiers_2).indent(options.tabWidth),
  19644. ","
  19645. ]);
  19646. }
  19647. if (unbracedSpecifiers_2.length > 0) {
  19648. parts.push(", ");
  19649. }
  19650. if (lines_3.length > 1) {
  19651. parts.push("{\n", lines_3, "\n}");
  19652. }
  19653. else if (options.objectCurlySpacing) {
  19654. parts.push("{ ", lines_3, " }");
  19655. }
  19656. else {
  19657. parts.push("{", lines_3, "}");
  19658. }
  19659. }
  19660. }
  19661. else {
  19662. parts.push(shouldPrintSpaces ? "{ " : "{", lines.fromString(", ").join(path.map(print, "specifiers")), shouldPrintSpaces ? " }" : "}");
  19663. }
  19664. if (decl.source) {
  19665. parts.push(" from ", path.call(print, "source"));
  19666. }
  19667. }
  19668. var lines$1 = lines.concat(parts);
  19669. if (lastNonSpaceCharacter(lines$1) !== ";" &&
  19670. !(decl.declaration &&
  19671. (decl.declaration.type === "FunctionDeclaration" ||
  19672. decl.declaration.type === "ClassDeclaration" ||
  19673. decl.declaration.type === "TSModuleDeclaration" ||
  19674. decl.declaration.type === "TSInterfaceDeclaration" ||
  19675. decl.declaration.type === "TSEnumDeclaration"))) {
  19676. lines$1 = lines.concat([lines$1, ";"]);
  19677. }
  19678. return lines$1;
  19679. }
  19680. function printFlowDeclaration(path, parts) {
  19681. var parentExportDecl = util.getParentExportDeclaration(path);
  19682. if (parentExportDecl) {
  19683. assert_1.default.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
  19684. }
  19685. else {
  19686. // If the parent node has type DeclareExportDeclaration, then it
  19687. // will be responsible for printing the "declare" token. Otherwise
  19688. // it needs to be printed with this non-exported declaration node.
  19689. parts.unshift("declare ");
  19690. }
  19691. return lines.concat(parts);
  19692. }
  19693. function printVariance(path, print) {
  19694. return path.call(function (variancePath) {
  19695. var value = variancePath.getValue();
  19696. if (value) {
  19697. if (value === "plus") {
  19698. return lines.fromString("+");
  19699. }
  19700. if (value === "minus") {
  19701. return lines.fromString("-");
  19702. }
  19703. return print(variancePath);
  19704. }
  19705. return lines.fromString("");
  19706. }, "variance");
  19707. }
  19708. function adjustClause(clause, options) {
  19709. if (clause.length > 1)
  19710. return lines.concat([" ", clause]);
  19711. return lines.concat([
  19712. "\n",
  19713. maybeAddSemicolon(clause).indent(options.tabWidth)
  19714. ]);
  19715. }
  19716. function lastNonSpaceCharacter(lines) {
  19717. var pos = lines.lastPos();
  19718. do {
  19719. var ch = lines.charAt(pos);
  19720. if (/\S/.test(ch))
  19721. return ch;
  19722. } while (lines.prevPos(pos));
  19723. }
  19724. function endsWithBrace(lines) {
  19725. return lastNonSpaceCharacter(lines) === "}";
  19726. }
  19727. function swapQuotes(str) {
  19728. return str.replace(/['"]/g, function (m) {
  19729. return m === '"' ? '\'' : '"';
  19730. });
  19731. }
  19732. function nodeStr(str, options) {
  19733. isString.assert(str);
  19734. switch (options.quote) {
  19735. case "auto":
  19736. var double = JSON.stringify(str);
  19737. var single = swapQuotes(JSON.stringify(swapQuotes(str)));
  19738. return double.length > single.length ? single : double;
  19739. case "single":
  19740. return swapQuotes(JSON.stringify(swapQuotes(str)));
  19741. case "double":
  19742. default:
  19743. return JSON.stringify(str);
  19744. }
  19745. }
  19746. function maybeAddSemicolon(lines$1) {
  19747. var eoc = lastNonSpaceCharacter(lines$1);
  19748. if (!eoc || "\n};".indexOf(eoc) < 0)
  19749. return lines.concat([lines$1, ";"]);
  19750. return lines$1;
  19751. }
  19752. });
  19753. unwrapExports(printer);
  19754. var printer_1 = printer.Printer;
  19755. var main$1 = createCommonjsModule(function (module, exports) {
  19756. var __importDefault = (this && this.__importDefault) || function (mod) {
  19757. return (mod && mod.__esModule) ? mod : { "default": mod };
  19758. };
  19759. var __importStar = (this && this.__importStar) || function (mod) {
  19760. if (mod && mod.__esModule) return mod;
  19761. var result = {};
  19762. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  19763. result["default"] = mod;
  19764. return result;
  19765. };
  19766. Object.defineProperty(exports, "__esModule", { value: true });
  19767. var fs_1 = __importDefault(fs);
  19768. var types = __importStar(main);
  19769. exports.types = types;
  19770. exports.parse = parser.parse;
  19771. /**
  19772. * Traverse and potentially modify an abstract syntax tree using a
  19773. * convenient visitor syntax:
  19774. *
  19775. * recast.visit(ast, {
  19776. * names: [],
  19777. * visitIdentifier: function(path) {
  19778. * var node = path.value;
  19779. * this.visitor.names.push(node.name);
  19780. * this.traverse(path);
  19781. * }
  19782. * });
  19783. */
  19784. var ast_types_1 = main;
  19785. exports.visit = ast_types_1.visit;
  19786. /**
  19787. * Reprint a modified syntax tree using as much of the original source
  19788. * code as possible.
  19789. */
  19790. function print(node, options) {
  19791. return new printer.Printer(options).print(node);
  19792. }
  19793. exports.print = print;
  19794. /**
  19795. * Print without attempting to reuse any original source code.
  19796. */
  19797. function prettyPrint(node, options) {
  19798. return new printer.Printer(options).printGenerically(node);
  19799. }
  19800. exports.prettyPrint = prettyPrint;
  19801. /**
  19802. * Convenient command-line interface (see e.g. example/add-braces).
  19803. */
  19804. function run(transformer, options) {
  19805. return runFile(process.argv[2], transformer, options);
  19806. }
  19807. exports.run = run;
  19808. function runFile(path, transformer, options) {
  19809. fs_1.default.readFile(path, "utf-8", function (err, code) {
  19810. if (err) {
  19811. console.error(err);
  19812. return;
  19813. }
  19814. runString(code, transformer, options);
  19815. });
  19816. }
  19817. function defaultWriteback(output) {
  19818. process.stdout.write(output);
  19819. }
  19820. function runString(code, transformer, options) {
  19821. var writeback = options && options.writeback || defaultWriteback;
  19822. transformer(parser.parse(code, options), function (node) {
  19823. writeback(print(node, options).code);
  19824. });
  19825. }
  19826. });
  19827. unwrapExports(main$1);
  19828. var main_1$1 = main$1.types;
  19829. var main_2$1 = main$1.parse;
  19830. var main_3$1 = main$1.visit;
  19831. var main_4$1 = main$1.print;
  19832. var main_5$1 = main$1.prettyPrint;
  19833. var main_6$1 = main$1.run;
  19834. const types$1 = main_1$1;
  19835. const builders = main_1$1.builders;
  19836. const namedTypes = main_1$1.namedTypes;
  19837. function nullNode() {
  19838. return builders.literal(null)
  19839. }
  19840. function simplePropertyNode(key, value) {
  19841. return builders.property('init', builders.literal(key), value, false)
  19842. }
  19843. /**
  19844. * Return a source map as JSON, it it has not the toJSON method it means it can
  19845. * be used right the way
  19846. * @param { SourceMapGenerator|Object } map - a sourcemap generator or simply an json object
  19847. * @returns { Object } the source map as JSON
  19848. */
  19849. function sourcemapAsJSON(map) {
  19850. if (map && map.toJSON) return map.toJSON()
  19851. return map
  19852. }
  19853. /**
  19854. * Quick type checking
  19855. * @param {*} element - anything
  19856. * @param {string} type - type definition
  19857. * @returns {boolean} true if the type corresponds
  19858. */
  19859. /**
  19860. * Detect node js environements
  19861. * @returns {boolean} true if the runtime is node
  19862. */
  19863. function isNode() {
  19864. return typeof process !== 'undefined'
  19865. }
  19866. /**
  19867. * Compose two sourcemaps
  19868. * @param { SourceMapGenerator } formerMap - original sourcemap
  19869. * @param { SourceMapGenerator } latterMap - target sourcemap
  19870. * @returns { Object } sourcemap json
  19871. */
  19872. function composeSourcemaps(formerMap, latterMap) {
  19873. if (
  19874. isNode() &&
  19875. formerMap && latterMap && latterMap.mappings
  19876. ) {
  19877. return util_5$1(sourcemapAsJSON(formerMap), sourcemapAsJSON(latterMap))
  19878. } else if (isNode() && formerMap) {
  19879. return sourcemapAsJSON(formerMap)
  19880. }
  19881. return {}
  19882. }
  19883. /* -*- Mode: js; js-indent-level: 2; -*- */
  19884. /*
  19885. * Copyright 2011 Mozilla Foundation and contributors
  19886. * Licensed under the New BSD license. See LICENSE or:
  19887. * http://opensource.org/licenses/BSD-3-Clause
  19888. */
  19889. const intToCharMap$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
  19890. /**
  19891. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  19892. */
  19893. var encode$2 = function(number) {
  19894. if (0 <= number && number < intToCharMap$1.length) {
  19895. return intToCharMap$1[number];
  19896. }
  19897. throw new TypeError("Must be between 0 and 63: " + number);
  19898. };
  19899. var base64$1 = {
  19900. encode: encode$2
  19901. };
  19902. /* -*- Mode: js; js-indent-level: 2; -*- */
  19903. /*
  19904. * Copyright 2011 Mozilla Foundation and contributors
  19905. * Licensed under the New BSD license. See LICENSE or:
  19906. * http://opensource.org/licenses/BSD-3-Clause
  19907. *
  19908. * Based on the Base 64 VLQ implementation in Closure Compiler:
  19909. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  19910. *
  19911. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  19912. * Redistribution and use in source and binary forms, with or without
  19913. * modification, are permitted provided that the following conditions are
  19914. * met:
  19915. *
  19916. * * Redistributions of source code must retain the above copyright
  19917. * notice, this list of conditions and the following disclaimer.
  19918. * * Redistributions in binary form must reproduce the above
  19919. * copyright notice, this list of conditions and the following
  19920. * disclaimer in the documentation and/or other materials provided
  19921. * with the distribution.
  19922. * * Neither the name of Google Inc. nor the names of its
  19923. * contributors may be used to endorse or promote products derived
  19924. * from this software without specific prior written permission.
  19925. *
  19926. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19927. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19928. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  19929. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19930. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19931. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  19932. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  19933. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  19934. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  19935. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  19936. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  19937. */
  19938. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  19939. // length quantities we use in the source map spec, the first bit is the sign,
  19940. // the next four bits are the actual value, and the 6th bit is the
  19941. // continuation bit. The continuation bit tells us whether there are more
  19942. // digits in this value following this digit.
  19943. //
  19944. // Continuation
  19945. // | Sign
  19946. // | |
  19947. // V V
  19948. // 101011
  19949. const VLQ_BASE_SHIFT$1 = 5;
  19950. // binary: 100000
  19951. const VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
  19952. // binary: 011111
  19953. const VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
  19954. // binary: 100000
  19955. const VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
  19956. /**
  19957. * Converts from a two-complement value to a value where the sign bit is
  19958. * placed in the least significant bit. For example, as decimals:
  19959. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  19960. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  19961. */
  19962. function toVLQSigned$1(aValue) {
  19963. return aValue < 0
  19964. ? ((-aValue) << 1) + 1
  19965. : (aValue << 1) + 0;
  19966. }
  19967. /**
  19968. * Returns the base 64 VLQ encoded value.
  19969. */
  19970. var encode$3 = function base64VLQ_encode(aValue) {
  19971. let encoded = "";
  19972. let digit;
  19973. let vlq = toVLQSigned$1(aValue);
  19974. do {
  19975. digit = vlq & VLQ_BASE_MASK$1;
  19976. vlq >>>= VLQ_BASE_SHIFT$1;
  19977. if (vlq > 0) {
  19978. // There are still more digits in this value, so we must make sure the
  19979. // continuation bit is marked.
  19980. digit |= VLQ_CONTINUATION_BIT$1;
  19981. }
  19982. encoded += base64$1.encode(digit);
  19983. } while (vlq > 0);
  19984. return encoded;
  19985. };
  19986. var base64Vlq$1 = {
  19987. encode: encode$3
  19988. };
  19989. var util$2 = createCommonjsModule(function (module, exports) {
  19990. /* -*- Mode: js; js-indent-level: 2; -*- */
  19991. /*
  19992. * Copyright 2011 Mozilla Foundation and contributors
  19993. * Licensed under the New BSD license. See LICENSE or:
  19994. * http://opensource.org/licenses/BSD-3-Clause
  19995. */
  19996. /**
  19997. * This is a helper function for getting values from parameter/options
  19998. * objects.
  19999. *
  20000. * @param args The object we are extracting values from
  20001. * @param name The name of the property we are getting.
  20002. * @param defaultValue An optional value to return if the property is missing
  20003. * from the object. If this is not specified and the property is missing, an
  20004. * error will be thrown.
  20005. */
  20006. function getArg(aArgs, aName, aDefaultValue) {
  20007. if (aName in aArgs) {
  20008. return aArgs[aName];
  20009. } else if (arguments.length === 3) {
  20010. return aDefaultValue;
  20011. }
  20012. throw new Error('"' + aName + '" is a required argument.');
  20013. }
  20014. exports.getArg = getArg;
  20015. const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  20016. const dataUrlRegexp = /^data:.+\,.+$/;
  20017. function urlParse(aUrl) {
  20018. const match = aUrl.match(urlRegexp);
  20019. if (!match) {
  20020. return null;
  20021. }
  20022. return {
  20023. scheme: match[1],
  20024. auth: match[2],
  20025. host: match[3],
  20026. port: match[4],
  20027. path: match[5]
  20028. };
  20029. }
  20030. exports.urlParse = urlParse;
  20031. function urlGenerate(aParsedUrl) {
  20032. let url = "";
  20033. if (aParsedUrl.scheme) {
  20034. url += aParsedUrl.scheme + ":";
  20035. }
  20036. url += "//";
  20037. if (aParsedUrl.auth) {
  20038. url += aParsedUrl.auth + "@";
  20039. }
  20040. if (aParsedUrl.host) {
  20041. url += aParsedUrl.host;
  20042. }
  20043. if (aParsedUrl.port) {
  20044. url += ":" + aParsedUrl.port;
  20045. }
  20046. if (aParsedUrl.path) {
  20047. url += aParsedUrl.path;
  20048. }
  20049. return url;
  20050. }
  20051. exports.urlGenerate = urlGenerate;
  20052. const MAX_CACHED_INPUTS = 32;
  20053. /**
  20054. * Takes some function `f(input) -> result` and returns a memoized version of
  20055. * `f`.
  20056. *
  20057. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  20058. * memoization is a dumb-simple, linear least-recently-used cache.
  20059. */
  20060. function lruMemoize(f) {
  20061. const cache = [];
  20062. return function(input) {
  20063. for (let i = 0; i < cache.length; i++) {
  20064. if (cache[i].input === input) {
  20065. const temp = cache[0];
  20066. cache[0] = cache[i];
  20067. cache[i] = temp;
  20068. return cache[0].result;
  20069. }
  20070. }
  20071. const result = f(input);
  20072. cache.unshift({
  20073. input,
  20074. result,
  20075. });
  20076. if (cache.length > MAX_CACHED_INPUTS) {
  20077. cache.pop();
  20078. }
  20079. return result;
  20080. };
  20081. }
  20082. /**
  20083. * Normalizes a path, or the path portion of a URL:
  20084. *
  20085. * - Replaces consecutive slashes with one slash.
  20086. * - Removes unnecessary '.' parts.
  20087. * - Removes unnecessary '<dir>/..' parts.
  20088. *
  20089. * Based on code in the Node.js 'path' core module.
  20090. *
  20091. * @param aPath The path or url to normalize.
  20092. */
  20093. const normalize = lruMemoize(function normalize(aPath) {
  20094. let path = aPath;
  20095. const url = urlParse(aPath);
  20096. if (url) {
  20097. if (!url.path) {
  20098. return aPath;
  20099. }
  20100. path = url.path;
  20101. }
  20102. const isAbsolute = exports.isAbsolute(path);
  20103. // Split the path into parts between `/` characters. This is much faster than
  20104. // using `.split(/\/+/g)`.
  20105. const parts = [];
  20106. let start = 0;
  20107. let i = 0;
  20108. while (true) {
  20109. start = i;
  20110. i = path.indexOf("/", start);
  20111. if (i === -1) {
  20112. parts.push(path.slice(start));
  20113. break;
  20114. } else {
  20115. parts.push(path.slice(start, i));
  20116. while (i < path.length && path[i] === "/") {
  20117. i++;
  20118. }
  20119. }
  20120. }
  20121. let up = 0;
  20122. for (i = parts.length - 1; i >= 0; i--) {
  20123. const part = parts[i];
  20124. if (part === ".") {
  20125. parts.splice(i, 1);
  20126. } else if (part === "..") {
  20127. up++;
  20128. } else if (up > 0) {
  20129. if (part === "") {
  20130. // The first part is blank if the path is absolute. Trying to go
  20131. // above the root is a no-op. Therefore we can remove all '..' parts
  20132. // directly after the root.
  20133. parts.splice(i + 1, up);
  20134. up = 0;
  20135. } else {
  20136. parts.splice(i, 2);
  20137. up--;
  20138. }
  20139. }
  20140. }
  20141. path = parts.join("/");
  20142. if (path === "") {
  20143. path = isAbsolute ? "/" : ".";
  20144. }
  20145. if (url) {
  20146. url.path = path;
  20147. return urlGenerate(url);
  20148. }
  20149. return path;
  20150. });
  20151. exports.normalize = normalize;
  20152. /**
  20153. * Joins two paths/URLs.
  20154. *
  20155. * @param aRoot The root path or URL.
  20156. * @param aPath The path or URL to be joined with the root.
  20157. *
  20158. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  20159. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  20160. * first.
  20161. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  20162. * is updated with the result and aRoot is returned. Otherwise the result
  20163. * is returned.
  20164. * - If aPath is absolute, the result is aPath.
  20165. * - Otherwise the two paths are joined with a slash.
  20166. * - Joining for example 'http://' and 'www.example.com' is also supported.
  20167. */
  20168. function join(aRoot, aPath) {
  20169. if (aRoot === "") {
  20170. aRoot = ".";
  20171. }
  20172. if (aPath === "") {
  20173. aPath = ".";
  20174. }
  20175. const aPathUrl = urlParse(aPath);
  20176. const aRootUrl = urlParse(aRoot);
  20177. if (aRootUrl) {
  20178. aRoot = aRootUrl.path || "/";
  20179. }
  20180. // `join(foo, '//www.example.org')`
  20181. if (aPathUrl && !aPathUrl.scheme) {
  20182. if (aRootUrl) {
  20183. aPathUrl.scheme = aRootUrl.scheme;
  20184. }
  20185. return urlGenerate(aPathUrl);
  20186. }
  20187. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  20188. return aPath;
  20189. }
  20190. // `join('http://', 'www.example.com')`
  20191. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  20192. aRootUrl.host = aPath;
  20193. return urlGenerate(aRootUrl);
  20194. }
  20195. const joined = aPath.charAt(0) === "/"
  20196. ? aPath
  20197. : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
  20198. if (aRootUrl) {
  20199. aRootUrl.path = joined;
  20200. return urlGenerate(aRootUrl);
  20201. }
  20202. return joined;
  20203. }
  20204. exports.join = join;
  20205. exports.isAbsolute = function(aPath) {
  20206. return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
  20207. };
  20208. /**
  20209. * Make a path relative to a URL or another path.
  20210. *
  20211. * @param aRoot The root path or URL.
  20212. * @param aPath The path or URL to be made relative to aRoot.
  20213. */
  20214. function relative(aRoot, aPath) {
  20215. if (aRoot === "") {
  20216. aRoot = ".";
  20217. }
  20218. aRoot = aRoot.replace(/\/$/, "");
  20219. // It is possible for the path to be above the root. In this case, simply
  20220. // checking whether the root is a prefix of the path won't work. Instead, we
  20221. // need to remove components from the root one by one, until either we find
  20222. // a prefix that fits, or we run out of components to remove.
  20223. let level = 0;
  20224. while (aPath.indexOf(aRoot + "/") !== 0) {
  20225. const index = aRoot.lastIndexOf("/");
  20226. if (index < 0) {
  20227. return aPath;
  20228. }
  20229. // If the only part of the root that is left is the scheme (i.e. http://,
  20230. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  20231. // have exhausted all components, so the path is not relative to the root.
  20232. aRoot = aRoot.slice(0, index);
  20233. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  20234. return aPath;
  20235. }
  20236. ++level;
  20237. }
  20238. // Make sure we add a "../" for each component we removed from the root.
  20239. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  20240. }
  20241. exports.relative = relative;
  20242. const supportsNullProto = (function() {
  20243. const obj = Object.create(null);
  20244. return !("__proto__" in obj);
  20245. }());
  20246. function identity(s) {
  20247. return s;
  20248. }
  20249. /**
  20250. * Because behavior goes wacky when you set `__proto__` on objects, we
  20251. * have to prefix all the strings in our set with an arbitrary character.
  20252. *
  20253. * See https://github.com/mozilla/source-map/pull/31 and
  20254. * https://github.com/mozilla/source-map/issues/30
  20255. *
  20256. * @param String aStr
  20257. */
  20258. function toSetString(aStr) {
  20259. if (isProtoString(aStr)) {
  20260. return "$" + aStr;
  20261. }
  20262. return aStr;
  20263. }
  20264. exports.toSetString = supportsNullProto ? identity : toSetString;
  20265. function fromSetString(aStr) {
  20266. if (isProtoString(aStr)) {
  20267. return aStr.slice(1);
  20268. }
  20269. return aStr;
  20270. }
  20271. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  20272. function isProtoString(s) {
  20273. if (!s) {
  20274. return false;
  20275. }
  20276. const length = s.length;
  20277. if (length < 9 /* "__proto__".length */) {
  20278. return false;
  20279. }
  20280. /* eslint-disable no-multi-spaces */
  20281. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  20282. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  20283. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  20284. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  20285. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  20286. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  20287. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  20288. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  20289. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  20290. return false;
  20291. }
  20292. /* eslint-enable no-multi-spaces */
  20293. for (let i = length - 10; i >= 0; i--) {
  20294. if (s.charCodeAt(i) !== 36 /* '$' */) {
  20295. return false;
  20296. }
  20297. }
  20298. return true;
  20299. }
  20300. /**
  20301. * Comparator between two mappings where the original positions are compared.
  20302. *
  20303. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  20304. * mappings with the same original source/line/column, but different generated
  20305. * line and column the same. Useful when searching for a mapping with a
  20306. * stubbed out mapping.
  20307. */
  20308. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  20309. let cmp = strcmp(mappingA.source, mappingB.source);
  20310. if (cmp !== 0) {
  20311. return cmp;
  20312. }
  20313. cmp = mappingA.originalLine - mappingB.originalLine;
  20314. if (cmp !== 0) {
  20315. return cmp;
  20316. }
  20317. cmp = mappingA.originalColumn - mappingB.originalColumn;
  20318. if (cmp !== 0 || onlyCompareOriginal) {
  20319. return cmp;
  20320. }
  20321. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  20322. if (cmp !== 0) {
  20323. return cmp;
  20324. }
  20325. cmp = mappingA.generatedLine - mappingB.generatedLine;
  20326. if (cmp !== 0) {
  20327. return cmp;
  20328. }
  20329. return strcmp(mappingA.name, mappingB.name);
  20330. }
  20331. exports.compareByOriginalPositions = compareByOriginalPositions;
  20332. /**
  20333. * Comparator between two mappings with deflated source and name indices where
  20334. * the generated positions are compared.
  20335. *
  20336. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  20337. * mappings with the same generated line and column, but different
  20338. * source/name/original line and column the same. Useful when searching for a
  20339. * mapping with a stubbed out mapping.
  20340. */
  20341. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  20342. let cmp = mappingA.generatedLine - mappingB.generatedLine;
  20343. if (cmp !== 0) {
  20344. return cmp;
  20345. }
  20346. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  20347. if (cmp !== 0 || onlyCompareGenerated) {
  20348. return cmp;
  20349. }
  20350. cmp = strcmp(mappingA.source, mappingB.source);
  20351. if (cmp !== 0) {
  20352. return cmp;
  20353. }
  20354. cmp = mappingA.originalLine - mappingB.originalLine;
  20355. if (cmp !== 0) {
  20356. return cmp;
  20357. }
  20358. cmp = mappingA.originalColumn - mappingB.originalColumn;
  20359. if (cmp !== 0) {
  20360. return cmp;
  20361. }
  20362. return strcmp(mappingA.name, mappingB.name);
  20363. }
  20364. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  20365. function strcmp(aStr1, aStr2) {
  20366. if (aStr1 === aStr2) {
  20367. return 0;
  20368. }
  20369. if (aStr1 === null) {
  20370. return 1; // aStr2 !== null
  20371. }
  20372. if (aStr2 === null) {
  20373. return -1; // aStr1 !== null
  20374. }
  20375. if (aStr1 > aStr2) {
  20376. return 1;
  20377. }
  20378. return -1;
  20379. }
  20380. /**
  20381. * Comparator between two mappings with inflated source and name strings where
  20382. * the generated positions are compared.
  20383. */
  20384. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  20385. let cmp = mappingA.generatedLine - mappingB.generatedLine;
  20386. if (cmp !== 0) {
  20387. return cmp;
  20388. }
  20389. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  20390. if (cmp !== 0) {
  20391. return cmp;
  20392. }
  20393. cmp = strcmp(mappingA.source, mappingB.source);
  20394. if (cmp !== 0) {
  20395. return cmp;
  20396. }
  20397. cmp = mappingA.originalLine - mappingB.originalLine;
  20398. if (cmp !== 0) {
  20399. return cmp;
  20400. }
  20401. cmp = mappingA.originalColumn - mappingB.originalColumn;
  20402. if (cmp !== 0) {
  20403. return cmp;
  20404. }
  20405. return strcmp(mappingA.name, mappingB.name);
  20406. }
  20407. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  20408. /**
  20409. * Strip any JSON XSSI avoidance prefix from the string (as documented
  20410. * in the source maps specification), and then parse the string as
  20411. * JSON.
  20412. */
  20413. function parseSourceMapInput(str) {
  20414. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
  20415. }
  20416. exports.parseSourceMapInput = parseSourceMapInput;
  20417. /**
  20418. * Compute the URL of a source given the the source root, the source's
  20419. * URL, and the source map's URL.
  20420. */
  20421. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  20422. sourceURL = sourceURL || "";
  20423. if (sourceRoot) {
  20424. // This follows what Chrome does.
  20425. if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
  20426. sourceRoot += "/";
  20427. }
  20428. // The spec says:
  20429. // Line 4: An optional source root, useful for relocating source
  20430. // files on a server or removing repeated values in the
  20431. // “sources” entry. This value is prepended to the individual
  20432. // entries in the “source” field.
  20433. sourceURL = sourceRoot + sourceURL;
  20434. }
  20435. // Historically, SourceMapConsumer did not take the sourceMapURL as
  20436. // a parameter. This mode is still somewhat supported, which is why
  20437. // this code block is conditional. However, it's preferable to pass
  20438. // the source map URL to SourceMapConsumer, so that this function
  20439. // can implement the source URL resolution algorithm as outlined in
  20440. // the spec. This block is basically the equivalent of:
  20441. // new URL(sourceURL, sourceMapURL).toString()
  20442. // ... except it avoids using URL, which wasn't available in the
  20443. // older releases of node still supported by this library.
  20444. //
  20445. // The spec says:
  20446. // If the sources are not absolute URLs after prepending of the
  20447. // “sourceRoot”, the sources are resolved relative to the
  20448. // SourceMap (like resolving script src in a html document).
  20449. if (sourceMapURL) {
  20450. const parsed = urlParse(sourceMapURL);
  20451. if (!parsed) {
  20452. throw new Error("sourceMapURL could not be parsed");
  20453. }
  20454. if (parsed.path) {
  20455. // Strip the last path component, but keep the "/".
  20456. const index = parsed.path.lastIndexOf("/");
  20457. if (index >= 0) {
  20458. parsed.path = parsed.path.substring(0, index + 1);
  20459. }
  20460. }
  20461. sourceURL = join(urlGenerate(parsed), sourceURL);
  20462. }
  20463. return normalize(sourceURL);
  20464. }
  20465. exports.computeSourceURL = computeSourceURL;
  20466. });
  20467. var util_1$2 = util$2.getArg;
  20468. var util_2$2 = util$2.urlParse;
  20469. var util_3$2 = util$2.urlGenerate;
  20470. var util_4$2 = util$2.normalize;
  20471. var util_5$2 = util$2.join;
  20472. var util_6$2 = util$2.isAbsolute;
  20473. var util_7$2 = util$2.relative;
  20474. var util_8$2 = util$2.toSetString;
  20475. var util_9$2 = util$2.fromSetString;
  20476. var util_10$2 = util$2.compareByOriginalPositions;
  20477. var util_11$1 = util$2.compareByGeneratedPositionsDeflated;
  20478. var util_12$1 = util$2.compareByGeneratedPositionsInflated;
  20479. var util_13$1 = util$2.parseSourceMapInput;
  20480. var util_14$1 = util$2.computeSourceURL;
  20481. /* -*- Mode: js; js-indent-level: 2; -*- */
  20482. /*
  20483. * Copyright 2011 Mozilla Foundation and contributors
  20484. * Licensed under the New BSD license. See LICENSE or:
  20485. * http://opensource.org/licenses/BSD-3-Clause
  20486. */
  20487. /**
  20488. * A data structure which is a combination of an array and a set. Adding a new
  20489. * member is O(1), testing for membership is O(1), and finding the index of an
  20490. * element is O(1). Removing elements from the set is not supported. Only
  20491. * strings are supported for membership.
  20492. */
  20493. class ArraySet$3 {
  20494. constructor() {
  20495. this._array = [];
  20496. this._set = new Map();
  20497. }
  20498. /**
  20499. * Static method for creating ArraySet instances from an existing array.
  20500. */
  20501. static fromArray(aArray, aAllowDuplicates) {
  20502. const set = new ArraySet$3();
  20503. for (let i = 0, len = aArray.length; i < len; i++) {
  20504. set.add(aArray[i], aAllowDuplicates);
  20505. }
  20506. return set;
  20507. }
  20508. /**
  20509. * Return how many unique items are in this ArraySet. If duplicates have been
  20510. * added, than those do not count towards the size.
  20511. *
  20512. * @returns Number
  20513. */
  20514. size() {
  20515. return this._set.size;
  20516. }
  20517. /**
  20518. * Add the given string to this set.
  20519. *
  20520. * @param String aStr
  20521. */
  20522. add(aStr, aAllowDuplicates) {
  20523. const isDuplicate = this.has(aStr);
  20524. const idx = this._array.length;
  20525. if (!isDuplicate || aAllowDuplicates) {
  20526. this._array.push(aStr);
  20527. }
  20528. if (!isDuplicate) {
  20529. this._set.set(aStr, idx);
  20530. }
  20531. }
  20532. /**
  20533. * Is the given string a member of this set?
  20534. *
  20535. * @param String aStr
  20536. */
  20537. has(aStr) {
  20538. return this._set.has(aStr);
  20539. }
  20540. /**
  20541. * What is the index of the given string in the array?
  20542. *
  20543. * @param String aStr
  20544. */
  20545. indexOf(aStr) {
  20546. const idx = this._set.get(aStr);
  20547. if (idx >= 0) {
  20548. return idx;
  20549. }
  20550. throw new Error('"' + aStr + '" is not in the set.');
  20551. }
  20552. /**
  20553. * What is the element at the given index?
  20554. *
  20555. * @param Number aIdx
  20556. */
  20557. at(aIdx) {
  20558. if (aIdx >= 0 && aIdx < this._array.length) {
  20559. return this._array[aIdx];
  20560. }
  20561. throw new Error("No element indexed by " + aIdx);
  20562. }
  20563. /**
  20564. * Returns the array representation of this set (which has the proper indices
  20565. * indicated by indexOf). Note that this is a copy of the internal array used
  20566. * for storing the members so that no one can mess with internal state.
  20567. */
  20568. toArray() {
  20569. return this._array.slice();
  20570. }
  20571. }
  20572. var ArraySet_1$1 = ArraySet$3;
  20573. var arraySet$1 = {
  20574. ArraySet: ArraySet_1$1
  20575. };
  20576. /* -*- Mode: js; js-indent-level: 2; -*- */
  20577. /*
  20578. * Copyright 2014 Mozilla Foundation and contributors
  20579. * Licensed under the New BSD license. See LICENSE or:
  20580. * http://opensource.org/licenses/BSD-3-Clause
  20581. */
  20582. /**
  20583. * Determine whether mappingB is after mappingA with respect to generated
  20584. * position.
  20585. */
  20586. function generatedPositionAfter$1(mappingA, mappingB) {
  20587. // Optimized for most common case
  20588. const lineA = mappingA.generatedLine;
  20589. const lineB = mappingB.generatedLine;
  20590. const columnA = mappingA.generatedColumn;
  20591. const columnB = mappingB.generatedColumn;
  20592. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  20593. util$2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  20594. }
  20595. /**
  20596. * A data structure to provide a sorted view of accumulated mappings in a
  20597. * performance conscious manner. It trades a negligible overhead in general
  20598. * case for a large speedup in case of mappings being added in order.
  20599. */
  20600. class MappingList$2 {
  20601. constructor() {
  20602. this._array = [];
  20603. this._sorted = true;
  20604. // Serves as infimum
  20605. this._last = {generatedLine: -1, generatedColumn: 0};
  20606. }
  20607. /**
  20608. * Iterate through internal items. This method takes the same arguments that
  20609. * `Array.prototype.forEach` takes.
  20610. *
  20611. * NOTE: The order of the mappings is NOT guaranteed.
  20612. */
  20613. unsortedForEach(aCallback, aThisArg) {
  20614. this._array.forEach(aCallback, aThisArg);
  20615. }
  20616. /**
  20617. * Add the given source mapping.
  20618. *
  20619. * @param Object aMapping
  20620. */
  20621. add(aMapping) {
  20622. if (generatedPositionAfter$1(this._last, aMapping)) {
  20623. this._last = aMapping;
  20624. this._array.push(aMapping);
  20625. } else {
  20626. this._sorted = false;
  20627. this._array.push(aMapping);
  20628. }
  20629. }
  20630. /**
  20631. * Returns the flat, sorted array of mappings. The mappings are sorted by
  20632. * generated position.
  20633. *
  20634. * WARNING: This method returns internal data without copying, for
  20635. * performance. The return value must NOT be mutated, and should be treated as
  20636. * an immutable borrow. If you want to take ownership, you must make your own
  20637. * copy.
  20638. */
  20639. toArray() {
  20640. if (!this._sorted) {
  20641. this._array.sort(util$2.compareByGeneratedPositionsInflated);
  20642. this._sorted = true;
  20643. }
  20644. return this._array;
  20645. }
  20646. }
  20647. var MappingList_1$1 = MappingList$2;
  20648. var mappingList$1 = {
  20649. MappingList: MappingList_1$1
  20650. };
  20651. /* -*- Mode: js; js-indent-level: 2; -*- */
  20652. /*
  20653. * Copyright 2011 Mozilla Foundation and contributors
  20654. * Licensed under the New BSD license. See LICENSE or:
  20655. * http://opensource.org/licenses/BSD-3-Clause
  20656. */
  20657. const ArraySet$4 = arraySet$1.ArraySet;
  20658. const MappingList$3 = mappingList$1.MappingList;
  20659. /**
  20660. * An instance of the SourceMapGenerator represents a source map which is
  20661. * being built incrementally. You may pass an object with the following
  20662. * properties:
  20663. *
  20664. * - file: The filename of the generated source.
  20665. * - sourceRoot: A root for all relative URLs in this source map.
  20666. */
  20667. class SourceMapGenerator$3 {
  20668. constructor(aArgs) {
  20669. if (!aArgs) {
  20670. aArgs = {};
  20671. }
  20672. this._file = util$2.getArg(aArgs, "file", null);
  20673. this._sourceRoot = util$2.getArg(aArgs, "sourceRoot", null);
  20674. this._skipValidation = util$2.getArg(aArgs, "skipValidation", false);
  20675. this._sources = new ArraySet$4();
  20676. this._names = new ArraySet$4();
  20677. this._mappings = new MappingList$3();
  20678. this._sourcesContents = null;
  20679. }
  20680. /**
  20681. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  20682. *
  20683. * @param aSourceMapConsumer The SourceMap.
  20684. */
  20685. static fromSourceMap(aSourceMapConsumer) {
  20686. const sourceRoot = aSourceMapConsumer.sourceRoot;
  20687. const generator = new SourceMapGenerator$3({
  20688. file: aSourceMapConsumer.file,
  20689. sourceRoot
  20690. });
  20691. aSourceMapConsumer.eachMapping(function(mapping) {
  20692. const newMapping = {
  20693. generated: {
  20694. line: mapping.generatedLine,
  20695. column: mapping.generatedColumn
  20696. }
  20697. };
  20698. if (mapping.source != null) {
  20699. newMapping.source = mapping.source;
  20700. if (sourceRoot != null) {
  20701. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  20702. }
  20703. newMapping.original = {
  20704. line: mapping.originalLine,
  20705. column: mapping.originalColumn
  20706. };
  20707. if (mapping.name != null) {
  20708. newMapping.name = mapping.name;
  20709. }
  20710. }
  20711. generator.addMapping(newMapping);
  20712. });
  20713. aSourceMapConsumer.sources.forEach(function(sourceFile) {
  20714. let sourceRelative = sourceFile;
  20715. if (sourceRoot !== null) {
  20716. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  20717. }
  20718. if (!generator._sources.has(sourceRelative)) {
  20719. generator._sources.add(sourceRelative);
  20720. }
  20721. const content = aSourceMapConsumer.sourceContentFor(sourceFile);
  20722. if (content != null) {
  20723. generator.setSourceContent(sourceFile, content);
  20724. }
  20725. });
  20726. return generator;
  20727. }
  20728. /**
  20729. * Add a single mapping from original source line and column to the generated
  20730. * source's line and column for this source map being created. The mapping
  20731. * object should have the following properties:
  20732. *
  20733. * - generated: An object with the generated line and column positions.
  20734. * - original: An object with the original line and column positions.
  20735. * - source: The original source file (relative to the sourceRoot).
  20736. * - name: An optional original token name for this mapping.
  20737. */
  20738. addMapping(aArgs) {
  20739. const generated = util$2.getArg(aArgs, "generated");
  20740. const original = util$2.getArg(aArgs, "original", null);
  20741. let source = util$2.getArg(aArgs, "source", null);
  20742. let name = util$2.getArg(aArgs, "name", null);
  20743. if (!this._skipValidation) {
  20744. this._validateMapping(generated, original, source, name);
  20745. }
  20746. if (source != null) {
  20747. source = String(source);
  20748. if (!this._sources.has(source)) {
  20749. this._sources.add(source);
  20750. }
  20751. }
  20752. if (name != null) {
  20753. name = String(name);
  20754. if (!this._names.has(name)) {
  20755. this._names.add(name);
  20756. }
  20757. }
  20758. this._mappings.add({
  20759. generatedLine: generated.line,
  20760. generatedColumn: generated.column,
  20761. originalLine: original != null && original.line,
  20762. originalColumn: original != null && original.column,
  20763. source,
  20764. name
  20765. });
  20766. }
  20767. /**
  20768. * Set the source content for a source file.
  20769. */
  20770. setSourceContent(aSourceFile, aSourceContent) {
  20771. let source = aSourceFile;
  20772. if (this._sourceRoot != null) {
  20773. source = util$2.relative(this._sourceRoot, source);
  20774. }
  20775. if (aSourceContent != null) {
  20776. // Add the source content to the _sourcesContents map.
  20777. // Create a new _sourcesContents map if the property is null.
  20778. if (!this._sourcesContents) {
  20779. this._sourcesContents = Object.create(null);
  20780. }
  20781. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  20782. } else if (this._sourcesContents) {
  20783. // Remove the source file from the _sourcesContents map.
  20784. // If the _sourcesContents map is empty, set the property to null.
  20785. delete this._sourcesContents[util$2.toSetString(source)];
  20786. if (Object.keys(this._sourcesContents).length === 0) {
  20787. this._sourcesContents = null;
  20788. }
  20789. }
  20790. }
  20791. /**
  20792. * Applies the mappings of a sub-source-map for a specific source file to the
  20793. * source map being generated. Each mapping to the supplied source file is
  20794. * rewritten using the supplied source map. Note: The resolution for the
  20795. * resulting mappings is the minimium of this map and the supplied map.
  20796. *
  20797. * @param aSourceMapConsumer The source map to be applied.
  20798. * @param aSourceFile Optional. The filename of the source file.
  20799. * If omitted, SourceMapConsumer's file property will be used.
  20800. * @param aSourceMapPath Optional. The dirname of the path to the source map
  20801. * to be applied. If relative, it is relative to the SourceMapConsumer.
  20802. * This parameter is needed when the two source maps aren't in the same
  20803. * directory, and the source map to be applied contains relative source
  20804. * paths. If so, those relative source paths need to be rewritten
  20805. * relative to the SourceMapGenerator.
  20806. */
  20807. applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  20808. let sourceFile = aSourceFile;
  20809. // If aSourceFile is omitted, we will use the file property of the SourceMap
  20810. if (aSourceFile == null) {
  20811. if (aSourceMapConsumer.file == null) {
  20812. throw new Error(
  20813. "SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " +
  20814. 'or the source map\'s "file" property. Both were omitted.'
  20815. );
  20816. }
  20817. sourceFile = aSourceMapConsumer.file;
  20818. }
  20819. const sourceRoot = this._sourceRoot;
  20820. // Make "sourceFile" relative if an absolute Url is passed.
  20821. if (sourceRoot != null) {
  20822. sourceFile = util$2.relative(sourceRoot, sourceFile);
  20823. }
  20824. // Applying the SourceMap can add and remove items from the sources and
  20825. // the names array.
  20826. const newSources = this._mappings.toArray().length > 0
  20827. ? new ArraySet$4()
  20828. : this._sources;
  20829. const newNames = new ArraySet$4();
  20830. // Find mappings for the "sourceFile"
  20831. this._mappings.unsortedForEach(function(mapping) {
  20832. if (mapping.source === sourceFile && mapping.originalLine != null) {
  20833. // Check if it can be mapped by the source map, then update the mapping.
  20834. const original = aSourceMapConsumer.originalPositionFor({
  20835. line: mapping.originalLine,
  20836. column: mapping.originalColumn
  20837. });
  20838. if (original.source != null) {
  20839. // Copy mapping
  20840. mapping.source = original.source;
  20841. if (aSourceMapPath != null) {
  20842. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  20843. }
  20844. if (sourceRoot != null) {
  20845. mapping.source = util$2.relative(sourceRoot, mapping.source);
  20846. }
  20847. mapping.originalLine = original.line;
  20848. mapping.originalColumn = original.column;
  20849. if (original.name != null) {
  20850. mapping.name = original.name;
  20851. }
  20852. }
  20853. }
  20854. const source = mapping.source;
  20855. if (source != null && !newSources.has(source)) {
  20856. newSources.add(source);
  20857. }
  20858. const name = mapping.name;
  20859. if (name != null && !newNames.has(name)) {
  20860. newNames.add(name);
  20861. }
  20862. }, this);
  20863. this._sources = newSources;
  20864. this._names = newNames;
  20865. // Copy sourcesContents of applied map.
  20866. aSourceMapConsumer.sources.forEach(function(srcFile) {
  20867. const content = aSourceMapConsumer.sourceContentFor(srcFile);
  20868. if (content != null) {
  20869. if (aSourceMapPath != null) {
  20870. srcFile = util$2.join(aSourceMapPath, srcFile);
  20871. }
  20872. if (sourceRoot != null) {
  20873. srcFile = util$2.relative(sourceRoot, srcFile);
  20874. }
  20875. this.setSourceContent(srcFile, content);
  20876. }
  20877. }, this);
  20878. }
  20879. /**
  20880. * A mapping can have one of the three levels of data:
  20881. *
  20882. * 1. Just the generated position.
  20883. * 2. The Generated position, original position, and original source.
  20884. * 3. Generated and original position, original source, as well as a name
  20885. * token.
  20886. *
  20887. * To maintain consistency, we validate that any new mapping being added falls
  20888. * in to one of these categories.
  20889. */
  20890. _validateMapping(aGenerated, aOriginal, aSource, aName) {
  20891. // When aOriginal is truthy but has empty values for .line and .column,
  20892. // it is most likely a programmer error. In this case we throw a very
  20893. // specific error message to try to guide them the right way.
  20894. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  20895. if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
  20896. throw new Error(
  20897. "original.line and original.column are not numbers -- you probably meant to omit " +
  20898. "the original mapping entirely and only map the generated position. If so, pass " +
  20899. "null for the original mapping instead of an object with empty or null values."
  20900. );
  20901. }
  20902. if (aGenerated && "line" in aGenerated && "column" in aGenerated
  20903. && aGenerated.line > 0 && aGenerated.column >= 0
  20904. && !aOriginal && !aSource && !aName) ; else if (aGenerated && "line" in aGenerated && "column" in aGenerated
  20905. && aOriginal && "line" in aOriginal && "column" in aOriginal
  20906. && aGenerated.line > 0 && aGenerated.column >= 0
  20907. && aOriginal.line > 0 && aOriginal.column >= 0
  20908. && aSource) ; else {
  20909. throw new Error("Invalid mapping: " + JSON.stringify({
  20910. generated: aGenerated,
  20911. source: aSource,
  20912. original: aOriginal,
  20913. name: aName
  20914. }));
  20915. }
  20916. }
  20917. /**
  20918. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  20919. * specified by the source map format.
  20920. */
  20921. _serializeMappings() {
  20922. let previousGeneratedColumn = 0;
  20923. let previousGeneratedLine = 1;
  20924. let previousOriginalColumn = 0;
  20925. let previousOriginalLine = 0;
  20926. let previousName = 0;
  20927. let previousSource = 0;
  20928. let result = "";
  20929. let next;
  20930. let mapping;
  20931. let nameIdx;
  20932. let sourceIdx;
  20933. const mappings = this._mappings.toArray();
  20934. for (let i = 0, len = mappings.length; i < len; i++) {
  20935. mapping = mappings[i];
  20936. next = "";
  20937. if (mapping.generatedLine !== previousGeneratedLine) {
  20938. previousGeneratedColumn = 0;
  20939. while (mapping.generatedLine !== previousGeneratedLine) {
  20940. next += ";";
  20941. previousGeneratedLine++;
  20942. }
  20943. } else if (i > 0) {
  20944. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  20945. continue;
  20946. }
  20947. next += ",";
  20948. }
  20949. next += base64Vlq$1.encode(mapping.generatedColumn
  20950. - previousGeneratedColumn);
  20951. previousGeneratedColumn = mapping.generatedColumn;
  20952. if (mapping.source != null) {
  20953. sourceIdx = this._sources.indexOf(mapping.source);
  20954. next += base64Vlq$1.encode(sourceIdx - previousSource);
  20955. previousSource = sourceIdx;
  20956. // lines are stored 0-based in SourceMap spec version 3
  20957. next += base64Vlq$1.encode(mapping.originalLine - 1
  20958. - previousOriginalLine);
  20959. previousOriginalLine = mapping.originalLine - 1;
  20960. next += base64Vlq$1.encode(mapping.originalColumn
  20961. - previousOriginalColumn);
  20962. previousOriginalColumn = mapping.originalColumn;
  20963. if (mapping.name != null) {
  20964. nameIdx = this._names.indexOf(mapping.name);
  20965. next += base64Vlq$1.encode(nameIdx - previousName);
  20966. previousName = nameIdx;
  20967. }
  20968. }
  20969. result += next;
  20970. }
  20971. return result;
  20972. }
  20973. _generateSourcesContent(aSources, aSourceRoot) {
  20974. return aSources.map(function(source) {
  20975. if (!this._sourcesContents) {
  20976. return null;
  20977. }
  20978. if (aSourceRoot != null) {
  20979. source = util$2.relative(aSourceRoot, source);
  20980. }
  20981. const key = util$2.toSetString(source);
  20982. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  20983. ? this._sourcesContents[key]
  20984. : null;
  20985. }, this);
  20986. }
  20987. /**
  20988. * Externalize the source map.
  20989. */
  20990. toJSON() {
  20991. const map = {
  20992. version: this._version,
  20993. sources: this._sources.toArray(),
  20994. names: this._names.toArray(),
  20995. mappings: this._serializeMappings()
  20996. };
  20997. if (this._file != null) {
  20998. map.file = this._file;
  20999. }
  21000. if (this._sourceRoot != null) {
  21001. map.sourceRoot = this._sourceRoot;
  21002. }
  21003. if (this._sourcesContents) {
  21004. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  21005. }
  21006. return map;
  21007. }
  21008. /**
  21009. * Render the source map being generated to a string.
  21010. */
  21011. toString() {
  21012. return JSON.stringify(this.toJSON());
  21013. }
  21014. }
  21015. SourceMapGenerator$3.prototype._version = 3;
  21016. var SourceMapGenerator_1$1 = SourceMapGenerator$3;
  21017. var sourceMapGenerator$1 = {
  21018. SourceMapGenerator: SourceMapGenerator_1$1
  21019. };
  21020. var binarySearch$1 = createCommonjsModule(function (module, exports) {
  21021. /* -*- Mode: js; js-indent-level: 2; -*- */
  21022. /*
  21023. * Copyright 2011 Mozilla Foundation and contributors
  21024. * Licensed under the New BSD license. See LICENSE or:
  21025. * http://opensource.org/licenses/BSD-3-Clause
  21026. */
  21027. exports.GREATEST_LOWER_BOUND = 1;
  21028. exports.LEAST_UPPER_BOUND = 2;
  21029. /**
  21030. * Recursive implementation of binary search.
  21031. *
  21032. * @param aLow Indices here and lower do not contain the needle.
  21033. * @param aHigh Indices here and higher do not contain the needle.
  21034. * @param aNeedle The element being searched for.
  21035. * @param aHaystack The non-empty array being searched.
  21036. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  21037. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  21038. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  21039. * closest element that is smaller than or greater than the one we are
  21040. * searching for, respectively, if the exact element cannot be found.
  21041. */
  21042. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  21043. // This function terminates when one of the following is true:
  21044. //
  21045. // 1. We find the exact element we are looking for.
  21046. //
  21047. // 2. We did not find the exact element, but we can return the index of
  21048. // the next-closest element.
  21049. //
  21050. // 3. We did not find the exact element, and there is no next-closest
  21051. // element than the one we are searching for, so we return -1.
  21052. const mid = Math.floor((aHigh - aLow) / 2) + aLow;
  21053. const cmp = aCompare(aNeedle, aHaystack[mid], true);
  21054. if (cmp === 0) {
  21055. // Found the element we are looking for.
  21056. return mid;
  21057. } else if (cmp > 0) {
  21058. // Our needle is greater than aHaystack[mid].
  21059. if (aHigh - mid > 1) {
  21060. // The element is in the upper half.
  21061. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  21062. }
  21063. // The exact needle element was not found in this haystack. Determine if
  21064. // we are in termination case (3) or (2) and return the appropriate thing.
  21065. if (aBias == exports.LEAST_UPPER_BOUND) {
  21066. return aHigh < aHaystack.length ? aHigh : -1;
  21067. }
  21068. return mid;
  21069. }
  21070. // Our needle is less than aHaystack[mid].
  21071. if (mid - aLow > 1) {
  21072. // The element is in the lower half.
  21073. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  21074. }
  21075. // we are in termination case (3) or (2) and return the appropriate thing.
  21076. if (aBias == exports.LEAST_UPPER_BOUND) {
  21077. return mid;
  21078. }
  21079. return aLow < 0 ? -1 : aLow;
  21080. }
  21081. /**
  21082. * This is an implementation of binary search which will always try and return
  21083. * the index of the closest element if there is no exact hit. This is because
  21084. * mappings between original and generated line/col pairs are single points,
  21085. * and there is an implicit region between each of them, so a miss just means
  21086. * that you aren't on the very start of a region.
  21087. *
  21088. * @param aNeedle The element you are looking for.
  21089. * @param aHaystack The array that is being searched.
  21090. * @param aCompare A function which takes the needle and an element in the
  21091. * array and returns -1, 0, or 1 depending on whether the needle is less
  21092. * than, equal to, or greater than the element, respectively.
  21093. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  21094. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  21095. * closest element that is smaller than or greater than the one we are
  21096. * searching for, respectively, if the exact element cannot be found.
  21097. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  21098. */
  21099. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  21100. if (aHaystack.length === 0) {
  21101. return -1;
  21102. }
  21103. let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  21104. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  21105. if (index < 0) {
  21106. return -1;
  21107. }
  21108. // We have found either the exact element, or the next-closest element than
  21109. // the one we are searching for. However, there may be more than one such
  21110. // element. Make sure we always return the smallest of these.
  21111. while (index - 1 >= 0) {
  21112. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  21113. break;
  21114. }
  21115. --index;
  21116. }
  21117. return index;
  21118. };
  21119. });
  21120. var binarySearch_1$1 = binarySearch$1.GREATEST_LOWER_BOUND;
  21121. var binarySearch_2$1 = binarySearch$1.LEAST_UPPER_BOUND;
  21122. var binarySearch_3$1 = binarySearch$1.search;
  21123. var readWasm = createCommonjsModule(function (module) {
  21124. if (typeof fetch === "function") {
  21125. // Web version of reading a wasm file into an array buffer.
  21126. let mappingsWasmUrl = null;
  21127. module.exports = function readWasm() {
  21128. if (typeof mappingsWasmUrl !== "string") {
  21129. throw new Error("You must provide the URL of lib/mappings.wasm by calling " +
  21130. "SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " +
  21131. "before using SourceMapConsumer");
  21132. }
  21133. return fetch(mappingsWasmUrl)
  21134. .then(response => response.arrayBuffer());
  21135. };
  21136. module.exports.initialize = url => mappingsWasmUrl = url;
  21137. } else {
  21138. // Node version of reading a wasm file into an array buffer.
  21139. const fs$1 = fs;
  21140. const path = path$1;
  21141. module.exports = function readWasm() {
  21142. return new Promise((resolve, reject) => {
  21143. const wasmPath = path.join(__dirname, "mappings.wasm");
  21144. fs$1.readFile(wasmPath, null, (error, data) => {
  21145. if (error) {
  21146. reject(error);
  21147. return;
  21148. }
  21149. resolve(data.buffer);
  21150. });
  21151. });
  21152. };
  21153. module.exports.initialize = _ => {
  21154. console.debug("SourceMapConsumer.initialize is a no-op when running in node.js");
  21155. };
  21156. }
  21157. });
  21158. var readWasm_1 = readWasm.initialize;
  21159. /**
  21160. * Provide the JIT with a nice shape / hidden class.
  21161. */
  21162. function Mapping$1() {
  21163. this.generatedLine = 0;
  21164. this.generatedColumn = 0;
  21165. this.lastGeneratedColumn = null;
  21166. this.source = null;
  21167. this.originalLine = null;
  21168. this.originalColumn = null;
  21169. this.name = null;
  21170. }
  21171. let cachedWasm = null;
  21172. var wasm = function wasm() {
  21173. if (cachedWasm) {
  21174. return cachedWasm;
  21175. }
  21176. const callbackStack = [];
  21177. cachedWasm = readWasm().then(buffer => {
  21178. return WebAssembly.instantiate(buffer, {
  21179. env: {
  21180. mapping_callback(
  21181. generatedLine,
  21182. generatedColumn,
  21183. hasLastGeneratedColumn,
  21184. lastGeneratedColumn,
  21185. hasOriginal,
  21186. source,
  21187. originalLine,
  21188. originalColumn,
  21189. hasName,
  21190. name
  21191. ) {
  21192. const mapping = new Mapping$1();
  21193. // JS uses 1-based line numbers, wasm uses 0-based.
  21194. mapping.generatedLine = generatedLine + 1;
  21195. mapping.generatedColumn = generatedColumn;
  21196. if (hasLastGeneratedColumn) {
  21197. // JS uses inclusive last generated column, wasm uses exclusive.
  21198. mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
  21199. }
  21200. if (hasOriginal) {
  21201. mapping.source = source;
  21202. // JS uses 1-based line numbers, wasm uses 0-based.
  21203. mapping.originalLine = originalLine + 1;
  21204. mapping.originalColumn = originalColumn;
  21205. if (hasName) {
  21206. mapping.name = name;
  21207. }
  21208. }
  21209. callbackStack[callbackStack.length - 1](mapping);
  21210. },
  21211. start_all_generated_locations_for() { console.time("all_generated_locations_for"); },
  21212. end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); },
  21213. start_compute_column_spans() { console.time("compute_column_spans"); },
  21214. end_compute_column_spans() { console.timeEnd("compute_column_spans"); },
  21215. start_generated_location_for() { console.time("generated_location_for"); },
  21216. end_generated_location_for() { console.timeEnd("generated_location_for"); },
  21217. start_original_location_for() { console.time("original_location_for"); },
  21218. end_original_location_for() { console.timeEnd("original_location_for"); },
  21219. start_parse_mappings() { console.time("parse_mappings"); },
  21220. end_parse_mappings() { console.timeEnd("parse_mappings"); },
  21221. start_sort_by_generated_location() { console.time("sort_by_generated_location"); },
  21222. end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); },
  21223. start_sort_by_original_location() { console.time("sort_by_original_location"); },
  21224. end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); },
  21225. }
  21226. });
  21227. }).then(Wasm => {
  21228. return {
  21229. exports: Wasm.instance.exports,
  21230. withMappingCallback: (mappingCallback, f) => {
  21231. callbackStack.push(mappingCallback);
  21232. try {
  21233. f();
  21234. } finally {
  21235. callbackStack.pop();
  21236. }
  21237. }
  21238. };
  21239. }).then(null, e => {
  21240. cachedWasm = null;
  21241. throw e;
  21242. });
  21243. return cachedWasm;
  21244. };
  21245. /* -*- Mode: js; js-indent-level: 2; -*- */
  21246. /*
  21247. * Copyright 2011 Mozilla Foundation and contributors
  21248. * Licensed under the New BSD license. See LICENSE or:
  21249. * http://opensource.org/licenses/BSD-3-Clause
  21250. */
  21251. const ArraySet$5 = arraySet$1.ArraySet;
  21252. // eslint-disable-line no-unused-vars
  21253. const INTERNAL = Symbol("smcInternal");
  21254. class SourceMapConsumer$2 {
  21255. constructor(aSourceMap, aSourceMapURL) {
  21256. // If the constructor was called by super(), just return Promise<this>.
  21257. // Yes, this is a hack to retain the pre-existing API of the base-class
  21258. // constructor also being an async factory function.
  21259. if (aSourceMap == INTERNAL) {
  21260. return Promise.resolve(this);
  21261. }
  21262. return _factory(aSourceMap, aSourceMapURL);
  21263. }
  21264. static initialize(opts) {
  21265. readWasm.initialize(opts["lib/mappings.wasm"]);
  21266. }
  21267. static fromSourceMap(aSourceMap, aSourceMapURL) {
  21268. return _factoryBSM(aSourceMap, aSourceMapURL);
  21269. }
  21270. /**
  21271. * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
  21272. * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
  21273. * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
  21274. * for `f` to complete, call `destroy` on the consumer, and return `f`'s return
  21275. * value.
  21276. *
  21277. * You must not use the consumer after `f` completes!
  21278. *
  21279. * By using `with`, you do not have to remember to manually call `destroy` on
  21280. * the consumer, since it will be called automatically once `f` completes.
  21281. *
  21282. * ```js
  21283. * const xSquared = await SourceMapConsumer.with(
  21284. * myRawSourceMap,
  21285. * null,
  21286. * async function (consumer) {
  21287. * // Use `consumer` inside here and don't worry about remembering
  21288. * // to call `destroy`.
  21289. *
  21290. * const x = await whatever(consumer);
  21291. * return x * x;
  21292. * }
  21293. * );
  21294. *
  21295. * // You may not use that `consumer` anymore out here; it has
  21296. * // been destroyed. But you can use `xSquared`.
  21297. * console.log(xSquared);
  21298. * ```
  21299. */
  21300. static with(rawSourceMap, sourceMapUrl, f) {
  21301. // Note: The `acorn` version that `webpack` currently depends on doesn't
  21302. // support `async` functions, and the nodes that we support don't all have
  21303. // `.finally`. Therefore, this is written a bit more convolutedly than it
  21304. // should really be.
  21305. let consumer = null;
  21306. const promise = new SourceMapConsumer$2(rawSourceMap, sourceMapUrl);
  21307. return promise
  21308. .then(c => {
  21309. consumer = c;
  21310. return f(c);
  21311. })
  21312. .then(x => {
  21313. if (consumer) {
  21314. consumer.destroy();
  21315. }
  21316. return x;
  21317. }, e => {
  21318. if (consumer) {
  21319. consumer.destroy();
  21320. }
  21321. throw e;
  21322. });
  21323. }
  21324. /**
  21325. * Parse the mappings in a string in to a data structure which we can easily
  21326. * query (the ordered arrays in the `this.__generatedMappings` and
  21327. * `this.__originalMappings` properties).
  21328. */
  21329. _parseMappings(aStr, aSourceRoot) {
  21330. throw new Error("Subclasses must implement _parseMappings");
  21331. }
  21332. /**
  21333. * Iterate over each mapping between an original source/line/column and a
  21334. * generated line/column in this source map.
  21335. *
  21336. * @param Function aCallback
  21337. * The function that is called with each mapping.
  21338. * @param Object aContext
  21339. * Optional. If specified, this object will be the value of `this` every
  21340. * time that `aCallback` is called.
  21341. * @param aOrder
  21342. * Either `SourceMapConsumer.GENERATED_ORDER` or
  21343. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  21344. * iterate over the mappings sorted by the generated file's line/column
  21345. * order or the original's source/line/column order, respectively. Defaults to
  21346. * `SourceMapConsumer.GENERATED_ORDER`.
  21347. */
  21348. eachMapping(aCallback, aContext, aOrder) {
  21349. throw new Error("Subclasses must implement eachMapping");
  21350. }
  21351. /**
  21352. * Returns all generated line and column information for the original source,
  21353. * line, and column provided. If no column is provided, returns all mappings
  21354. * corresponding to a either the line we are searching for or the next
  21355. * closest line that has any mappings. Otherwise, returns all mappings
  21356. * corresponding to the given line and either the column we are searching for
  21357. * or the next closest column that has any offsets.
  21358. *
  21359. * The only argument is an object with the following properties:
  21360. *
  21361. * - source: The filename of the original source.
  21362. * - line: The line number in the original source. The line number is 1-based.
  21363. * - column: Optional. the column number in the original source.
  21364. * The column number is 0-based.
  21365. *
  21366. * and an array of objects is returned, each with the following properties:
  21367. *
  21368. * - line: The line number in the generated source, or null. The
  21369. * line number is 1-based.
  21370. * - column: The column number in the generated source, or null.
  21371. * The column number is 0-based.
  21372. */
  21373. allGeneratedPositionsFor(aArgs) {
  21374. throw new Error("Subclasses must implement allGeneratedPositionsFor");
  21375. }
  21376. destroy() {
  21377. throw new Error("Subclasses must implement destroy");
  21378. }
  21379. }
  21380. /**
  21381. * The version of the source mapping spec that we are consuming.
  21382. */
  21383. SourceMapConsumer$2.prototype._version = 3;
  21384. SourceMapConsumer$2.GENERATED_ORDER = 1;
  21385. SourceMapConsumer$2.ORIGINAL_ORDER = 2;
  21386. SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1;
  21387. SourceMapConsumer$2.LEAST_UPPER_BOUND = 2;
  21388. /**
  21389. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  21390. * query for information about the original file positions by giving it a file
  21391. * position in the generated source.
  21392. *
  21393. * The first parameter is the raw source map (either as a JSON string, or
  21394. * already parsed to an object). According to the spec, source maps have the
  21395. * following attributes:
  21396. *
  21397. * - version: Which version of the source map spec this map is following.
  21398. * - sources: An array of URLs to the original source files.
  21399. * - names: An array of identifiers which can be referenced by individual mappings.
  21400. * - sourceRoot: Optional. The URL root from which all sources are relative.
  21401. * - sourcesContent: Optional. An array of contents of the original source files.
  21402. * - mappings: A string of base64 VLQs which contain the actual mappings.
  21403. * - file: Optional. The generated file this source map is associated with.
  21404. *
  21405. * Here is an example source map, taken from the source map spec[0]:
  21406. *
  21407. * {
  21408. * version : 3,
  21409. * file: "out.js",
  21410. * sourceRoot : "",
  21411. * sources: ["foo.js", "bar.js"],
  21412. * names: ["src", "maps", "are", "fun"],
  21413. * mappings: "AA,AB;;ABCDE;"
  21414. * }
  21415. *
  21416. * The second parameter, if given, is a string whose value is the URL
  21417. * at which the source map was found. This URL is used to compute the
  21418. * sources array.
  21419. *
  21420. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  21421. */
  21422. class BasicSourceMapConsumer$1 extends SourceMapConsumer$2 {
  21423. constructor(aSourceMap, aSourceMapURL) {
  21424. return super(INTERNAL).then(that => {
  21425. let sourceMap = aSourceMap;
  21426. if (typeof aSourceMap === "string") {
  21427. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  21428. }
  21429. const version = util$2.getArg(sourceMap, "version");
  21430. let sources = util$2.getArg(sourceMap, "sources");
  21431. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  21432. // requires the array) to play nice here.
  21433. const names = util$2.getArg(sourceMap, "names", []);
  21434. let sourceRoot = util$2.getArg(sourceMap, "sourceRoot", null);
  21435. const sourcesContent = util$2.getArg(sourceMap, "sourcesContent", null);
  21436. const mappings = util$2.getArg(sourceMap, "mappings");
  21437. const file = util$2.getArg(sourceMap, "file", null);
  21438. // Once again, Sass deviates from the spec and supplies the version as a
  21439. // string rather than a number, so we use loose equality checking here.
  21440. if (version != that._version) {
  21441. throw new Error("Unsupported version: " + version);
  21442. }
  21443. if (sourceRoot) {
  21444. sourceRoot = util$2.normalize(sourceRoot);
  21445. }
  21446. sources = sources
  21447. .map(String)
  21448. // Some source maps produce relative source paths like "./foo.js" instead of
  21449. // "foo.js". Normalize these first so that future comparisons will succeed.
  21450. // See bugzil.la/1090768.
  21451. .map(util$2.normalize)
  21452. // Always ensure that absolute sources are internally stored relative to
  21453. // the source root, if the source root is absolute. Not doing this would
  21454. // be particularly problematic when the source root is a prefix of the
  21455. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  21456. .map(function(source) {
  21457. return sourceRoot && util$2.isAbsolute(sourceRoot) && util$2.isAbsolute(source)
  21458. ? util$2.relative(sourceRoot, source)
  21459. : source;
  21460. });
  21461. // Pass `true` below to allow duplicate names and sources. While source maps
  21462. // are intended to be compressed and deduplicated, the TypeScript compiler
  21463. // sometimes generates source maps with duplicates in them. See Github issue
  21464. // #72 and bugzil.la/889492.
  21465. that._names = ArraySet$5.fromArray(names.map(String), true);
  21466. that._sources = ArraySet$5.fromArray(sources, true);
  21467. that._absoluteSources = that._sources.toArray().map(function(s) {
  21468. return util$2.computeSourceURL(sourceRoot, s, aSourceMapURL);
  21469. });
  21470. that.sourceRoot = sourceRoot;
  21471. that.sourcesContent = sourcesContent;
  21472. that._mappings = mappings;
  21473. that._sourceMapURL = aSourceMapURL;
  21474. that.file = file;
  21475. that._computedColumnSpans = false;
  21476. that._mappingsPtr = 0;
  21477. that._wasm = null;
  21478. return wasm().then(w => {
  21479. that._wasm = w;
  21480. return that;
  21481. });
  21482. });
  21483. }
  21484. /**
  21485. * Utility function to find the index of a source. Returns -1 if not
  21486. * found.
  21487. */
  21488. _findSourceIndex(aSource) {
  21489. let relativeSource = aSource;
  21490. if (this.sourceRoot != null) {
  21491. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  21492. }
  21493. if (this._sources.has(relativeSource)) {
  21494. return this._sources.indexOf(relativeSource);
  21495. }
  21496. // Maybe aSource is an absolute URL as returned by |sources|. In
  21497. // this case we can't simply undo the transform.
  21498. for (let i = 0; i < this._absoluteSources.length; ++i) {
  21499. if (this._absoluteSources[i] == aSource) {
  21500. return i;
  21501. }
  21502. }
  21503. return -1;
  21504. }
  21505. /**
  21506. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  21507. *
  21508. * @param SourceMapGenerator aSourceMap
  21509. * The source map that will be consumed.
  21510. * @param String aSourceMapURL
  21511. * The URL at which the source map can be found (optional)
  21512. * @returns BasicSourceMapConsumer
  21513. */
  21514. static fromSourceMap(aSourceMap, aSourceMapURL) {
  21515. return new BasicSourceMapConsumer$1(aSourceMap.toString());
  21516. }
  21517. get sources() {
  21518. return this._absoluteSources.slice();
  21519. }
  21520. _getMappingsPtr() {
  21521. if (this._mappingsPtr === 0) {
  21522. this._parseMappings(this._mappings, this.sourceRoot);
  21523. }
  21524. return this._mappingsPtr;
  21525. }
  21526. /**
  21527. * Parse the mappings in a string in to a data structure which we can easily
  21528. * query (the ordered arrays in the `this.__generatedMappings` and
  21529. * `this.__originalMappings` properties).
  21530. */
  21531. _parseMappings(aStr, aSourceRoot) {
  21532. const size = aStr.length;
  21533. const mappingsBufPtr = this._wasm.exports.allocate_mappings(size);
  21534. const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size);
  21535. for (let i = 0; i < size; i++) {
  21536. mappingsBuf[i] = aStr.charCodeAt(i);
  21537. }
  21538. const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr);
  21539. if (!mappingsPtr) {
  21540. const error = this._wasm.exports.get_last_error();
  21541. let msg = `Error parsing mappings (code ${error}): `;
  21542. // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`.
  21543. switch (error) {
  21544. case 1:
  21545. msg += "the mappings contained a negative line, column, source index, or name index";
  21546. break;
  21547. case 2:
  21548. msg += "the mappings contained a number larger than 2**32";
  21549. break;
  21550. case 3:
  21551. msg += "reached EOF while in the middle of parsing a VLQ";
  21552. break;
  21553. case 4:
  21554. msg += "invalid base 64 character while parsing a VLQ";
  21555. break;
  21556. default:
  21557. msg += "unknown error code";
  21558. break;
  21559. }
  21560. throw new Error(msg);
  21561. }
  21562. this._mappingsPtr = mappingsPtr;
  21563. }
  21564. eachMapping(aCallback, aContext, aOrder) {
  21565. const context = aContext || null;
  21566. const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  21567. const sourceRoot = this.sourceRoot;
  21568. this._wasm.withMappingCallback(
  21569. mapping => {
  21570. if (mapping.source !== null) {
  21571. mapping.source = this._sources.at(mapping.source);
  21572. mapping.source = util$2.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL);
  21573. if (mapping.name !== null) {
  21574. mapping.name = this._names.at(mapping.name);
  21575. }
  21576. }
  21577. aCallback.call(context, mapping);
  21578. },
  21579. () => {
  21580. switch (order) {
  21581. case SourceMapConsumer$2.GENERATED_ORDER:
  21582. this._wasm.exports.by_generated_location(this._getMappingsPtr());
  21583. break;
  21584. case SourceMapConsumer$2.ORIGINAL_ORDER:
  21585. this._wasm.exports.by_original_location(this._getMappingsPtr());
  21586. break;
  21587. default:
  21588. throw new Error("Unknown order of iteration.");
  21589. }
  21590. }
  21591. );
  21592. }
  21593. allGeneratedPositionsFor(aArgs) {
  21594. let source = util$2.getArg(aArgs, "source");
  21595. const originalLine = util$2.getArg(aArgs, "line");
  21596. const originalColumn = aArgs.column || 0;
  21597. source = this._findSourceIndex(source);
  21598. if (source < 0) {
  21599. return [];
  21600. }
  21601. if (originalLine < 1) {
  21602. throw new Error("Line numbers must be >= 1");
  21603. }
  21604. if (originalColumn < 0) {
  21605. throw new Error("Column numbers must be >= 0");
  21606. }
  21607. const mappings = [];
  21608. this._wasm.withMappingCallback(
  21609. m => {
  21610. let lastColumn = m.lastGeneratedColumn;
  21611. if (this._computedColumnSpans && lastColumn === null) {
  21612. lastColumn = Infinity;
  21613. }
  21614. mappings.push({
  21615. line: m.generatedLine,
  21616. column: m.generatedColumn,
  21617. lastColumn,
  21618. });
  21619. }, () => {
  21620. this._wasm.exports.all_generated_locations_for(
  21621. this._getMappingsPtr(),
  21622. source,
  21623. originalLine - 1,
  21624. "column" in aArgs,
  21625. originalColumn
  21626. );
  21627. }
  21628. );
  21629. return mappings;
  21630. }
  21631. destroy() {
  21632. if (this._mappingsPtr !== 0) {
  21633. this._wasm.exports.free_mappings(this._mappingsPtr);
  21634. this._mappingsPtr = 0;
  21635. }
  21636. }
  21637. /**
  21638. * Compute the last column for each generated mapping. The last column is
  21639. * inclusive.
  21640. */
  21641. computeColumnSpans() {
  21642. if (this._computedColumnSpans) {
  21643. return;
  21644. }
  21645. this._wasm.exports.compute_column_spans(this._getMappingsPtr());
  21646. this._computedColumnSpans = true;
  21647. }
  21648. /**
  21649. * Returns the original source, line, and column information for the generated
  21650. * source's line and column positions provided. The only argument is an object
  21651. * with the following properties:
  21652. *
  21653. * - line: The line number in the generated source. The line number
  21654. * is 1-based.
  21655. * - column: The column number in the generated source. The column
  21656. * number is 0-based.
  21657. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  21658. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  21659. * closest element that is smaller than or greater than the one we are
  21660. * searching for, respectively, if the exact element cannot be found.
  21661. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  21662. *
  21663. * and an object is returned with the following properties:
  21664. *
  21665. * - source: The original source file, or null.
  21666. * - line: The line number in the original source, or null. The
  21667. * line number is 1-based.
  21668. * - column: The column number in the original source, or null. The
  21669. * column number is 0-based.
  21670. * - name: The original identifier, or null.
  21671. */
  21672. originalPositionFor(aArgs) {
  21673. const needle = {
  21674. generatedLine: util$2.getArg(aArgs, "line"),
  21675. generatedColumn: util$2.getArg(aArgs, "column")
  21676. };
  21677. if (needle.generatedLine < 1) {
  21678. throw new Error("Line numbers must be >= 1");
  21679. }
  21680. if (needle.generatedColumn < 0) {
  21681. throw new Error("Column numbers must be >= 0");
  21682. }
  21683. let bias = util$2.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND);
  21684. if (bias == null) {
  21685. bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND;
  21686. }
  21687. let mapping;
  21688. this._wasm.withMappingCallback(m => mapping = m, () => {
  21689. this._wasm.exports.original_location_for(
  21690. this._getMappingsPtr(),
  21691. needle.generatedLine - 1,
  21692. needle.generatedColumn,
  21693. bias
  21694. );
  21695. });
  21696. if (mapping) {
  21697. if (mapping.generatedLine === needle.generatedLine) {
  21698. let source = util$2.getArg(mapping, "source", null);
  21699. if (source !== null) {
  21700. source = this._sources.at(source);
  21701. source = util$2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  21702. }
  21703. let name = util$2.getArg(mapping, "name", null);
  21704. if (name !== null) {
  21705. name = this._names.at(name);
  21706. }
  21707. return {
  21708. source,
  21709. line: util$2.getArg(mapping, "originalLine", null),
  21710. column: util$2.getArg(mapping, "originalColumn", null),
  21711. name
  21712. };
  21713. }
  21714. }
  21715. return {
  21716. source: null,
  21717. line: null,
  21718. column: null,
  21719. name: null
  21720. };
  21721. }
  21722. /**
  21723. * Return true if we have the source content for every source in the source
  21724. * map, false otherwise.
  21725. */
  21726. hasContentsOfAllSources() {
  21727. if (!this.sourcesContent) {
  21728. return false;
  21729. }
  21730. return this.sourcesContent.length >= this._sources.size() &&
  21731. !this.sourcesContent.some(function(sc) { return sc == null; });
  21732. }
  21733. /**
  21734. * Returns the original source content. The only argument is the url of the
  21735. * original source file. Returns null if no original source content is
  21736. * available.
  21737. */
  21738. sourceContentFor(aSource, nullOnMissing) {
  21739. if (!this.sourcesContent) {
  21740. return null;
  21741. }
  21742. const index = this._findSourceIndex(aSource);
  21743. if (index >= 0) {
  21744. return this.sourcesContent[index];
  21745. }
  21746. let relativeSource = aSource;
  21747. if (this.sourceRoot != null) {
  21748. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  21749. }
  21750. let url;
  21751. if (this.sourceRoot != null
  21752. && (url = util$2.urlParse(this.sourceRoot))) {
  21753. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  21754. // many users. We can help them out when they expect file:// URIs to
  21755. // behave like it would if they were running a local HTTP server. See
  21756. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  21757. const fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  21758. if (url.scheme == "file"
  21759. && this._sources.has(fileUriAbsPath)) {
  21760. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
  21761. }
  21762. if ((!url.path || url.path == "/")
  21763. && this._sources.has("/" + relativeSource)) {
  21764. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  21765. }
  21766. }
  21767. // This function is used recursively from
  21768. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  21769. // don't want to throw if we can't find the source - we just want to
  21770. // return null, so we provide a flag to exit gracefully.
  21771. if (nullOnMissing) {
  21772. return null;
  21773. }
  21774. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  21775. }
  21776. /**
  21777. * Returns the generated line and column information for the original source,
  21778. * line, and column positions provided. The only argument is an object with
  21779. * the following properties:
  21780. *
  21781. * - source: The filename of the original source.
  21782. * - line: The line number in the original source. The line number
  21783. * is 1-based.
  21784. * - column: The column number in the original source. The column
  21785. * number is 0-based.
  21786. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  21787. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  21788. * closest element that is smaller than or greater than the one we are
  21789. * searching for, respectively, if the exact element cannot be found.
  21790. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  21791. *
  21792. * and an object is returned with the following properties:
  21793. *
  21794. * - line: The line number in the generated source, or null. The
  21795. * line number is 1-based.
  21796. * - column: The column number in the generated source, or null.
  21797. * The column number is 0-based.
  21798. */
  21799. generatedPositionFor(aArgs) {
  21800. let source = util$2.getArg(aArgs, "source");
  21801. source = this._findSourceIndex(source);
  21802. if (source < 0) {
  21803. return {
  21804. line: null,
  21805. column: null,
  21806. lastColumn: null
  21807. };
  21808. }
  21809. const needle = {
  21810. source,
  21811. originalLine: util$2.getArg(aArgs, "line"),
  21812. originalColumn: util$2.getArg(aArgs, "column")
  21813. };
  21814. if (needle.originalLine < 1) {
  21815. throw new Error("Line numbers must be >= 1");
  21816. }
  21817. if (needle.originalColumn < 0) {
  21818. throw new Error("Column numbers must be >= 0");
  21819. }
  21820. let bias = util$2.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND);
  21821. if (bias == null) {
  21822. bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND;
  21823. }
  21824. let mapping;
  21825. this._wasm.withMappingCallback(m => mapping = m, () => {
  21826. this._wasm.exports.generated_location_for(
  21827. this._getMappingsPtr(),
  21828. needle.source,
  21829. needle.originalLine - 1,
  21830. needle.originalColumn,
  21831. bias
  21832. );
  21833. });
  21834. if (mapping) {
  21835. if (mapping.source === needle.source) {
  21836. let lastColumn = mapping.lastGeneratedColumn;
  21837. if (this._computedColumnSpans && lastColumn === null) {
  21838. lastColumn = Infinity;
  21839. }
  21840. return {
  21841. line: util$2.getArg(mapping, "generatedLine", null),
  21842. column: util$2.getArg(mapping, "generatedColumn", null),
  21843. lastColumn,
  21844. };
  21845. }
  21846. }
  21847. return {
  21848. line: null,
  21849. column: null,
  21850. lastColumn: null
  21851. };
  21852. }
  21853. }
  21854. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2;
  21855. /**
  21856. * An IndexedSourceMapConsumer instance represents a parsed source map which
  21857. * we can query for information. It differs from BasicSourceMapConsumer in
  21858. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  21859. * input.
  21860. *
  21861. * The first parameter is a raw source map (either as a JSON string, or already
  21862. * parsed to an object). According to the spec for indexed source maps, they
  21863. * have the following attributes:
  21864. *
  21865. * - version: Which version of the source map spec this map is following.
  21866. * - file: Optional. The generated file this source map is associated with.
  21867. * - sections: A list of section definitions.
  21868. *
  21869. * Each value under the "sections" field has two fields:
  21870. * - offset: The offset into the original specified at which this section
  21871. * begins to apply, defined as an object with a "line" and "column"
  21872. * field.
  21873. * - map: A source map definition. This source map could also be indexed,
  21874. * but doesn't have to be.
  21875. *
  21876. * Instead of the "map" field, it's also possible to have a "url" field
  21877. * specifying a URL to retrieve a source map from, but that's currently
  21878. * unsupported.
  21879. *
  21880. * Here's an example source map, taken from the source map spec[0], but
  21881. * modified to omit a section which uses the "url" field.
  21882. *
  21883. * {
  21884. * version : 3,
  21885. * file: "app.js",
  21886. * sections: [{
  21887. * offset: {line:100, column:10},
  21888. * map: {
  21889. * version : 3,
  21890. * file: "section.js",
  21891. * sources: ["foo.js", "bar.js"],
  21892. * names: ["src", "maps", "are", "fun"],
  21893. * mappings: "AAAA,E;;ABCDE;"
  21894. * }
  21895. * }],
  21896. * }
  21897. *
  21898. * The second parameter, if given, is a string whose value is the URL
  21899. * at which the source map was found. This URL is used to compute the
  21900. * sources array.
  21901. *
  21902. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  21903. */
  21904. class IndexedSourceMapConsumer$1 extends SourceMapConsumer$2 {
  21905. constructor(aSourceMap, aSourceMapURL) {
  21906. return super(INTERNAL).then(that => {
  21907. let sourceMap = aSourceMap;
  21908. if (typeof aSourceMap === "string") {
  21909. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  21910. }
  21911. const version = util$2.getArg(sourceMap, "version");
  21912. const sections = util$2.getArg(sourceMap, "sections");
  21913. if (version != that._version) {
  21914. throw new Error("Unsupported version: " + version);
  21915. }
  21916. that._sources = new ArraySet$5();
  21917. that._names = new ArraySet$5();
  21918. that.__generatedMappings = null;
  21919. that.__originalMappings = null;
  21920. that.__generatedMappingsUnsorted = null;
  21921. that.__originalMappingsUnsorted = null;
  21922. let lastOffset = {
  21923. line: -1,
  21924. column: 0
  21925. };
  21926. return Promise.all(sections.map(s => {
  21927. if (s.url) {
  21928. // The url field will require support for asynchronicity.
  21929. // See https://github.com/mozilla/source-map/issues/16
  21930. throw new Error("Support for url field in sections not implemented.");
  21931. }
  21932. const offset = util$2.getArg(s, "offset");
  21933. const offsetLine = util$2.getArg(offset, "line");
  21934. const offsetColumn = util$2.getArg(offset, "column");
  21935. if (offsetLine < lastOffset.line ||
  21936. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  21937. throw new Error("Section offsets must be ordered and non-overlapping.");
  21938. }
  21939. lastOffset = offset;
  21940. const cons = new SourceMapConsumer$2(util$2.getArg(s, "map"), aSourceMapURL);
  21941. return cons.then(consumer => {
  21942. return {
  21943. generatedOffset: {
  21944. // The offset fields are 0-based, but we use 1-based indices when
  21945. // encoding/decoding from VLQ.
  21946. generatedLine: offsetLine + 1,
  21947. generatedColumn: offsetColumn + 1
  21948. },
  21949. consumer
  21950. };
  21951. });
  21952. })).then(s => {
  21953. that._sections = s;
  21954. return that;
  21955. });
  21956. });
  21957. }
  21958. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  21959. // parsed mapping coordinates from the source map's "mappings" attribute. They
  21960. // are lazily instantiated, accessed via the `_generatedMappings` and
  21961. // `_originalMappings` getters respectively, and we only parse the mappings
  21962. // and create these arrays once queried for a source location. We jump through
  21963. // these hoops because there can be many thousands of mappings, and parsing
  21964. // them is expensive, so we only want to do it if we must.
  21965. //
  21966. // Each object in the arrays is of the form:
  21967. //
  21968. // {
  21969. // generatedLine: The line number in the generated code,
  21970. // generatedColumn: The column number in the generated code,
  21971. // source: The path to the original source file that generated this
  21972. // chunk of code,
  21973. // originalLine: The line number in the original source that
  21974. // corresponds to this chunk of generated code,
  21975. // originalColumn: The column number in the original source that
  21976. // corresponds to this chunk of generated code,
  21977. // name: The name of the original symbol which generated this chunk of
  21978. // code.
  21979. // }
  21980. //
  21981. // All properties except for `generatedLine` and `generatedColumn` can be
  21982. // `null`.
  21983. //
  21984. // `_generatedMappings` is ordered by the generated positions.
  21985. //
  21986. // `_originalMappings` is ordered by the original positions.
  21987. get _generatedMappings() {
  21988. if (!this.__generatedMappings) {
  21989. this._sortGeneratedMappings();
  21990. }
  21991. return this.__generatedMappings;
  21992. }
  21993. get _originalMappings() {
  21994. if (!this.__originalMappings) {
  21995. this._sortOriginalMappings();
  21996. }
  21997. return this.__originalMappings;
  21998. }
  21999. get _generatedMappingsUnsorted() {
  22000. if (!this.__generatedMappingsUnsorted) {
  22001. this._parseMappings(this._mappings, this.sourceRoot);
  22002. }
  22003. return this.__generatedMappingsUnsorted;
  22004. }
  22005. get _originalMappingsUnsorted() {
  22006. if (!this.__originalMappingsUnsorted) {
  22007. this._parseMappings(this._mappings, this.sourceRoot);
  22008. }
  22009. return this.__originalMappingsUnsorted;
  22010. }
  22011. _sortGeneratedMappings() {
  22012. const mappings = this._generatedMappingsUnsorted;
  22013. mappings.sort(util$2.compareByGeneratedPositionsDeflated);
  22014. this.__generatedMappings = mappings;
  22015. }
  22016. _sortOriginalMappings() {
  22017. const mappings = this._originalMappingsUnsorted;
  22018. mappings.sort(util$2.compareByOriginalPositions);
  22019. this.__originalMappings = mappings;
  22020. }
  22021. /**
  22022. * The list of original sources.
  22023. */
  22024. get sources() {
  22025. const sources = [];
  22026. for (let i = 0; i < this._sections.length; i++) {
  22027. for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {
  22028. sources.push(this._sections[i].consumer.sources[j]);
  22029. }
  22030. }
  22031. return sources;
  22032. }
  22033. /**
  22034. * Returns the original source, line, and column information for the generated
  22035. * source's line and column positions provided. The only argument is an object
  22036. * with the following properties:
  22037. *
  22038. * - line: The line number in the generated source. The line number
  22039. * is 1-based.
  22040. * - column: The column number in the generated source. The column
  22041. * number is 0-based.
  22042. *
  22043. * and an object is returned with the following properties:
  22044. *
  22045. * - source: The original source file, or null.
  22046. * - line: The line number in the original source, or null. The
  22047. * line number is 1-based.
  22048. * - column: The column number in the original source, or null. The
  22049. * column number is 0-based.
  22050. * - name: The original identifier, or null.
  22051. */
  22052. originalPositionFor(aArgs) {
  22053. const needle = {
  22054. generatedLine: util$2.getArg(aArgs, "line"),
  22055. generatedColumn: util$2.getArg(aArgs, "column")
  22056. };
  22057. // Find the section containing the generated position we're trying to map
  22058. // to an original position.
  22059. const sectionIndex = binarySearch$1.search(needle, this._sections,
  22060. function(aNeedle, section) {
  22061. const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine;
  22062. if (cmp) {
  22063. return cmp;
  22064. }
  22065. return (aNeedle.generatedColumn -
  22066. section.generatedOffset.generatedColumn);
  22067. });
  22068. const section = this._sections[sectionIndex];
  22069. if (!section) {
  22070. return {
  22071. source: null,
  22072. line: null,
  22073. column: null,
  22074. name: null
  22075. };
  22076. }
  22077. return section.consumer.originalPositionFor({
  22078. line: needle.generatedLine -
  22079. (section.generatedOffset.generatedLine - 1),
  22080. column: needle.generatedColumn -
  22081. (section.generatedOffset.generatedLine === needle.generatedLine
  22082. ? section.generatedOffset.generatedColumn - 1
  22083. : 0),
  22084. bias: aArgs.bias
  22085. });
  22086. }
  22087. /**
  22088. * Return true if we have the source content for every source in the source
  22089. * map, false otherwise.
  22090. */
  22091. hasContentsOfAllSources() {
  22092. return this._sections.every(function(s) {
  22093. return s.consumer.hasContentsOfAllSources();
  22094. });
  22095. }
  22096. /**
  22097. * Returns the original source content. The only argument is the url of the
  22098. * original source file. Returns null if no original source content is
  22099. * available.
  22100. */
  22101. sourceContentFor(aSource, nullOnMissing) {
  22102. for (let i = 0; i < this._sections.length; i++) {
  22103. const section = this._sections[i];
  22104. const content = section.consumer.sourceContentFor(aSource, true);
  22105. if (content) {
  22106. return content;
  22107. }
  22108. }
  22109. if (nullOnMissing) {
  22110. return null;
  22111. }
  22112. throw new Error('"' + aSource + '" is not in the SourceMap.');
  22113. }
  22114. /**
  22115. * Returns the generated line and column information for the original source,
  22116. * line, and column positions provided. The only argument is an object with
  22117. * the following properties:
  22118. *
  22119. * - source: The filename of the original source.
  22120. * - line: The line number in the original source. The line number
  22121. * is 1-based.
  22122. * - column: The column number in the original source. The column
  22123. * number is 0-based.
  22124. *
  22125. * and an object is returned with the following properties:
  22126. *
  22127. * - line: The line number in the generated source, or null. The
  22128. * line number is 1-based.
  22129. * - column: The column number in the generated source, or null.
  22130. * The column number is 0-based.
  22131. */
  22132. generatedPositionFor(aArgs) {
  22133. for (let i = 0; i < this._sections.length; i++) {
  22134. const section = this._sections[i];
  22135. // Only consider this section if the requested source is in the list of
  22136. // sources of the consumer.
  22137. if (section.consumer._findSourceIndex(util$2.getArg(aArgs, "source")) === -1) {
  22138. continue;
  22139. }
  22140. const generatedPosition = section.consumer.generatedPositionFor(aArgs);
  22141. if (generatedPosition) {
  22142. const ret = {
  22143. line: generatedPosition.line +
  22144. (section.generatedOffset.generatedLine - 1),
  22145. column: generatedPosition.column +
  22146. (section.generatedOffset.generatedLine === generatedPosition.line
  22147. ? section.generatedOffset.generatedColumn - 1
  22148. : 0)
  22149. };
  22150. return ret;
  22151. }
  22152. }
  22153. return {
  22154. line: null,
  22155. column: null
  22156. };
  22157. }
  22158. /**
  22159. * Parse the mappings in a string in to a data structure which we can easily
  22160. * query (the ordered arrays in the `this.__generatedMappings` and
  22161. * `this.__originalMappings` properties).
  22162. */
  22163. _parseMappings(aStr, aSourceRoot) {
  22164. const generatedMappings = this.__generatedMappingsUnsorted = [];
  22165. const originalMappings = this.__originalMappingsUnsorted = [];
  22166. for (let i = 0; i < this._sections.length; i++) {
  22167. const section = this._sections[i];
  22168. const sectionMappings = [];
  22169. section.consumer.eachMapping(m => sectionMappings.push(m));
  22170. for (let j = 0; j < sectionMappings.length; j++) {
  22171. const mapping = sectionMappings[j];
  22172. // TODO: test if null is correct here. The original code used
  22173. // `source`, which would actually have gotten used as null because
  22174. // var's get hoisted.
  22175. // See: https://github.com/mozilla/source-map/issues/333
  22176. let source = util$2.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL);
  22177. this._sources.add(source);
  22178. source = this._sources.indexOf(source);
  22179. let name = null;
  22180. if (mapping.name) {
  22181. this._names.add(mapping.name);
  22182. name = this._names.indexOf(mapping.name);
  22183. }
  22184. // The mappings coming from the consumer for the section have
  22185. // generated positions relative to the start of the section, so we
  22186. // need to offset them to be relative to the start of the concatenated
  22187. // generated file.
  22188. const adjustedMapping = {
  22189. source,
  22190. generatedLine: mapping.generatedLine +
  22191. (section.generatedOffset.generatedLine - 1),
  22192. generatedColumn: mapping.generatedColumn +
  22193. (section.generatedOffset.generatedLine === mapping.generatedLine
  22194. ? section.generatedOffset.generatedColumn - 1
  22195. : 0),
  22196. originalLine: mapping.originalLine,
  22197. originalColumn: mapping.originalColumn,
  22198. name
  22199. };
  22200. generatedMappings.push(adjustedMapping);
  22201. if (typeof adjustedMapping.originalLine === "number") {
  22202. originalMappings.push(adjustedMapping);
  22203. }
  22204. }
  22205. }
  22206. }
  22207. eachMapping(aCallback, aContext, aOrder) {
  22208. const context = aContext || null;
  22209. const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  22210. let mappings;
  22211. switch (order) {
  22212. case SourceMapConsumer$2.GENERATED_ORDER:
  22213. mappings = this._generatedMappings;
  22214. break;
  22215. case SourceMapConsumer$2.ORIGINAL_ORDER:
  22216. mappings = this._originalMappings;
  22217. break;
  22218. default:
  22219. throw new Error("Unknown order of iteration.");
  22220. }
  22221. const sourceRoot = this.sourceRoot;
  22222. mappings.map(function(mapping) {
  22223. let source = null;
  22224. if (mapping.source !== null) {
  22225. source = this._sources.at(mapping.source);
  22226. source = util$2.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  22227. }
  22228. return {
  22229. source,
  22230. generatedLine: mapping.generatedLine,
  22231. generatedColumn: mapping.generatedColumn,
  22232. originalLine: mapping.originalLine,
  22233. originalColumn: mapping.originalColumn,
  22234. name: mapping.name === null ? null : this._names.at(mapping.name)
  22235. };
  22236. }, this).forEach(aCallback, context);
  22237. }
  22238. /**
  22239. * Find the mapping that best matches the hypothetical "needle" mapping that
  22240. * we are searching for in the given "haystack" of mappings.
  22241. */
  22242. _findMapping(aNeedle, aMappings, aLineName,
  22243. aColumnName, aComparator, aBias) {
  22244. // To return the position we are searching for, we must first find the
  22245. // mapping for the given position and then return the opposite position it
  22246. // points to. Because the mappings are sorted, we can use binary search to
  22247. // find the best mapping.
  22248. if (aNeedle[aLineName] <= 0) {
  22249. throw new TypeError("Line must be greater than or equal to 1, got "
  22250. + aNeedle[aLineName]);
  22251. }
  22252. if (aNeedle[aColumnName] < 0) {
  22253. throw new TypeError("Column must be greater than or equal to 0, got "
  22254. + aNeedle[aColumnName]);
  22255. }
  22256. return binarySearch$1.search(aNeedle, aMappings, aComparator, aBias);
  22257. }
  22258. allGeneratedPositionsFor(aArgs) {
  22259. const line = util$2.getArg(aArgs, "line");
  22260. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  22261. // returns the index of the closest mapping less than the needle. By
  22262. // setting needle.originalColumn to 0, we thus find the last mapping for
  22263. // the given line, provided such a mapping exists.
  22264. const needle = {
  22265. source: util$2.getArg(aArgs, "source"),
  22266. originalLine: line,
  22267. originalColumn: util$2.getArg(aArgs, "column", 0)
  22268. };
  22269. needle.source = this._findSourceIndex(needle.source);
  22270. if (needle.source < 0) {
  22271. return [];
  22272. }
  22273. if (needle.originalLine < 1) {
  22274. throw new Error("Line numbers must be >= 1");
  22275. }
  22276. if (needle.originalColumn < 0) {
  22277. throw new Error("Column numbers must be >= 0");
  22278. }
  22279. const mappings = [];
  22280. let index = this._findMapping(needle,
  22281. this._originalMappings,
  22282. "originalLine",
  22283. "originalColumn",
  22284. util$2.compareByOriginalPositions,
  22285. binarySearch$1.LEAST_UPPER_BOUND);
  22286. if (index >= 0) {
  22287. let mapping = this._originalMappings[index];
  22288. if (aArgs.column === undefined) {
  22289. const originalLine = mapping.originalLine;
  22290. // Iterate until either we run out of mappings, or we run into
  22291. // a mapping for a different line than the one we found. Since
  22292. // mappings are sorted, this is guaranteed to find all mappings for
  22293. // the line we found.
  22294. while (mapping && mapping.originalLine === originalLine) {
  22295. let lastColumn = mapping.lastGeneratedColumn;
  22296. if (this._computedColumnSpans && lastColumn === null) {
  22297. lastColumn = Infinity;
  22298. }
  22299. mappings.push({
  22300. line: util$2.getArg(mapping, "generatedLine", null),
  22301. column: util$2.getArg(mapping, "generatedColumn", null),
  22302. lastColumn,
  22303. });
  22304. mapping = this._originalMappings[++index];
  22305. }
  22306. } else {
  22307. const originalColumn = mapping.originalColumn;
  22308. // Iterate until either we run out of mappings, or we run into
  22309. // a mapping for a different line than the one we were searching for.
  22310. // Since mappings are sorted, this is guaranteed to find all mappings for
  22311. // the line we are searching for.
  22312. while (mapping &&
  22313. mapping.originalLine === line &&
  22314. mapping.originalColumn == originalColumn) {
  22315. let lastColumn = mapping.lastGeneratedColumn;
  22316. if (this._computedColumnSpans && lastColumn === null) {
  22317. lastColumn = Infinity;
  22318. }
  22319. mappings.push({
  22320. line: util$2.getArg(mapping, "generatedLine", null),
  22321. column: util$2.getArg(mapping, "generatedColumn", null),
  22322. lastColumn,
  22323. });
  22324. mapping = this._originalMappings[++index];
  22325. }
  22326. }
  22327. }
  22328. return mappings;
  22329. }
  22330. destroy() {
  22331. for (let i = 0; i < this._sections.length; i++) {
  22332. this._sections[i].consumer.destroy();
  22333. }
  22334. }
  22335. }
  22336. /*
  22337. * Cheat to get around inter-twingled classes. `factory()` can be at the end
  22338. * where it has access to non-hoisted classes, but it gets hoisted itself.
  22339. */
  22340. function _factory(aSourceMap, aSourceMapURL) {
  22341. let sourceMap = aSourceMap;
  22342. if (typeof aSourceMap === "string") {
  22343. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  22344. }
  22345. const consumer = sourceMap.sections != null
  22346. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  22347. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  22348. return Promise.resolve(consumer);
  22349. }
  22350. function _factoryBSM(aSourceMap, aSourceMapURL) {
  22351. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  22352. }
  22353. /*
  22354. * Copyright 2009-2011 Mozilla Foundation and contributors
  22355. * Licensed under the New BSD license. See LICENSE.txt or:
  22356. * http://opensource.org/licenses/BSD-3-Clause
  22357. */
  22358. var SourceMapGenerator$4 = sourceMapGenerator$1.SourceMapGenerator;
  22359. /**
  22360. * Create a new sourcemap generator
  22361. * @param { Object } options - sourcemap options
  22362. * @returns { SourceMapGenerator } SourceMapGenerator instance
  22363. */
  22364. function createSourcemap(options) {
  22365. return new SourceMapGenerator$4(options)
  22366. }
  22367. const Output = Object.freeze({
  22368. code: '',
  22369. ast: [],
  22370. meta: {},
  22371. map: null
  22372. });
  22373. /**
  22374. * Create the right output data result of a parsing
  22375. * @param { Object } data - output data
  22376. * @param { string } data.code - code generated
  22377. * @param { AST } data.ast - ast representing the code
  22378. * @param { SourceMapGenerator } data.map - source map generated along with the code
  22379. * @param { Object } meta - compilation meta infomration
  22380. * @returns { Output } output container object
  22381. */
  22382. function createOutput(data, meta) {
  22383. const output = {
  22384. ...Output,
  22385. ...data,
  22386. meta
  22387. };
  22388. if (!output.map && meta && meta.options && meta.options.file)
  22389. return {
  22390. ...output,
  22391. map: createSourcemap({ file: meta.options.file })
  22392. }
  22393. return output
  22394. }
  22395. /**
  22396. * Transform the source code received via a compiler function
  22397. * @param { Function } compiler - function needed to generate the output code
  22398. * @param { Object } meta - compilation meta information
  22399. * @param { string } source - source code
  22400. * @returns { Output } output - the result of the compiler
  22401. */
  22402. function transform(compiler, meta, source) {
  22403. const result = (compiler ? compiler(source, meta) : { code: source });
  22404. return createOutput(result, meta)
  22405. }
  22406. /**
  22407. * Throw an error with a descriptive message
  22408. * @param { string } message - error message
  22409. * @returns { undefined } hoppla.. at this point the program should stop working
  22410. */
  22411. function panic(message) {
  22412. throw new Error(message)
  22413. }
  22414. const postprocessors = new Set();
  22415. /**
  22416. * Register a postprocessor that will be used after the parsing and compilation of the riot tags
  22417. * @param { Function } postprocessor - transformer that will receive the output code ans sourcemap
  22418. * @returns { Set } the postprocessors collection
  22419. */
  22420. function register(postprocessor) {
  22421. if (postprocessors.has(postprocessor)) {
  22422. panic(`This postprocessor "${postprocessor.name || postprocessor.toString()}" was already registered`);
  22423. }
  22424. postprocessors.add(postprocessor);
  22425. return postprocessors
  22426. }
  22427. /**
  22428. * Exec all the postprocessors in sequence combining the sourcemaps generated
  22429. * @param { Output } compilerOutput - output generated by the compiler
  22430. * @param { Object } meta - compiling meta information
  22431. * @returns { Output } object containing output code and source map
  22432. */
  22433. function execute(compilerOutput, meta) {
  22434. return Array.from(postprocessors).reduce(function(acc, postprocessor) {
  22435. const { code, map } = acc;
  22436. const output = postprocessor(code, meta);
  22437. return {
  22438. code: output.code,
  22439. map: composeSourcemaps(map, output.map)
  22440. }
  22441. }, createOutput(compilerOutput, meta))
  22442. }
  22443. /**
  22444. * Parsers that can be registered by users to preparse components fragments
  22445. * @type { Object }
  22446. */
  22447. const preprocessors = Object.freeze({
  22448. javascript: new Map(),
  22449. css: new Map(),
  22450. template: new Map().set('default', code => ({ code }))
  22451. });
  22452. // throw a processor type error
  22453. function preprocessorTypeError(type) {
  22454. panic(`No preprocessor of type "${type}" was found, please make sure to use one of these: 'javascript', 'css' or 'template'`);
  22455. }
  22456. // throw an error if the preprocessor was not registered
  22457. function preprocessorNameNotFoundError(name) {
  22458. panic(`No preprocessor named "${name}" was found, are you sure you have registered it?'`);
  22459. }
  22460. /**
  22461. * Register a custom preprocessor
  22462. * @param { string } type - preprocessor type either 'js', 'css' or 'template'
  22463. * @param { string } name - unique preprocessor id
  22464. * @param { Function } preprocessor - preprocessor function
  22465. * @returns { Map } - the preprocessors map
  22466. */
  22467. function register$1(type, name, preprocessor) {
  22468. if (!type) panic('Please define the type of preprocessor you want to register \'javascript\', \'css\' or \'template\'');
  22469. if (!name) panic('Please define a name for your preprocessor');
  22470. if (!preprocessor) panic('Please provide a preprocessor function');
  22471. if (!preprocessors[type]) preprocessorTypeError(type);
  22472. if (preprocessors[type].has(name)) panic(`The preprocessor ${name} was already registered before`);
  22473. preprocessors[type].set(name, preprocessor);
  22474. return preprocessors
  22475. }
  22476. /**
  22477. * Exec the compilation of a preprocessor
  22478. * @param { string } type - preprocessor type either 'js', 'css' or 'template'
  22479. * @param { string } name - unique preprocessor id
  22480. * @param { Object } meta - preprocessor meta information
  22481. * @param { string } source - source code
  22482. * @returns { Output } object containing a sourcemap and a code string
  22483. */
  22484. function execute$1(type, name, meta, source) {
  22485. if (!preprocessors[type]) preprocessorTypeError(type);
  22486. if (!preprocessors[type].has(name)) preprocessorNameNotFoundError(name);
  22487. return transform(preprocessors[type].get(name), meta, source)
  22488. }
  22489. /**
  22490. * Similar to compose but performs from left-to-right function composition.<br/>
  22491. * {@link https://30secondsofcode.org/function#composeright see also}
  22492. * @param {...[function]} fns) - list of unary function
  22493. * @returns {*} result of the computation
  22494. */
  22495. /**
  22496. * Performs right-to-left function composition.<br/>
  22497. * Use Array.prototype.reduce() to perform right-to-left function composition.<br/>
  22498. * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/>
  22499. * {@link https://30secondsofcode.org/function#compose original source code}
  22500. * @param {...[function]} fns) - list of unary function
  22501. * @returns {*} result of the computation
  22502. */
  22503. function compose(...fns) {
  22504. return fns.reduce((f, g) => (...args) => f(g(...args)))
  22505. }
  22506. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  22507. var object = {};
  22508. var hasOwnProperty$1 = object.hasOwnProperty;
  22509. var merge = function merge(options, defaults) {
  22510. if (!options) {
  22511. return defaults;
  22512. }
  22513. var result = {};
  22514. for (var key in defaults) {
  22515. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  22516. // only recognized option names are used.
  22517. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  22518. }
  22519. return result;
  22520. };
  22521. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  22522. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  22523. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  22524. // https://mathiasbynens.be/notes/css-escapes#css
  22525. var cssesc = function cssesc(string, options) {
  22526. options = merge(options, cssesc.options);
  22527. if (options.quotes != 'single' && options.quotes != 'double') {
  22528. options.quotes = 'single';
  22529. }
  22530. var quote = options.quotes == 'double' ? '"' : '\'';
  22531. var isIdentifier = options.isIdentifier;
  22532. var firstChar = string.charAt(0);
  22533. var output = '';
  22534. var counter = 0;
  22535. var length = string.length;
  22536. while (counter < length) {
  22537. var character = string.charAt(counter++);
  22538. var codePoint = character.charCodeAt();
  22539. var value = void 0;
  22540. // If it’s not a printable ASCII character…
  22541. if (codePoint < 0x20 || codePoint > 0x7E) {
  22542. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  22543. // It’s a high surrogate, and there is a next character.
  22544. var extra = string.charCodeAt(counter++);
  22545. if ((extra & 0xFC00) == 0xDC00) {
  22546. // next character is low surrogate
  22547. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  22548. } else {
  22549. // It’s an unmatched surrogate; only append this code unit, in case
  22550. // the next code unit is the high surrogate of a surrogate pair.
  22551. counter--;
  22552. }
  22553. }
  22554. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  22555. } else {
  22556. if (options.escapeEverything) {
  22557. if (regexAnySingleEscape.test(character)) {
  22558. value = '\\' + character;
  22559. } else {
  22560. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  22561. }
  22562. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  22563. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  22564. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  22565. value = '\\' + character;
  22566. } else {
  22567. value = character;
  22568. }
  22569. }
  22570. output += value;
  22571. }
  22572. if (isIdentifier) {
  22573. if (/^-[-\d]/.test(output)) {
  22574. output = '\\-' + output.slice(1);
  22575. } else if (/\d/.test(firstChar)) {
  22576. output = '\\3' + firstChar + ' ' + output.slice(1);
  22577. }
  22578. }
  22579. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  22580. // since they’re redundant. Note that this is only possible if the escape
  22581. // sequence isn’t preceded by an odd number of backslashes.
  22582. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  22583. if ($1 && $1.length % 2) {
  22584. // It’s not safe to remove the space, so don’t.
  22585. return $0;
  22586. }
  22587. // Strip the space.
  22588. return ($1 || '') + $2;
  22589. });
  22590. if (!isIdentifier && options.wrap) {
  22591. return quote + output + quote;
  22592. }
  22593. return output;
  22594. };
  22595. // Expose default options (so they can be overridden globally).
  22596. cssesc.options = {
  22597. 'escapeEverything': false,
  22598. 'isIdentifier': false,
  22599. 'quotes': 'single',
  22600. 'wrap': false
  22601. };
  22602. cssesc.version = '3.0.0';
  22603. var cssesc_1 = cssesc;
  22604. const ATTRIBUTE_TYPE_NAME = 'type';
  22605. /**
  22606. * Get the type attribute from a node generated by the riot parser
  22607. * @param { Object} sourceNode - riot parser node
  22608. * @returns { string|null } a valid type to identify the preprocessor to use or nothing
  22609. */
  22610. function getPreprocessorTypeByAttribute(sourceNode) {
  22611. const typeAttribute = sourceNode.attributes ?
  22612. sourceNode.attributes.find(attribute => attribute.name === ATTRIBUTE_TYPE_NAME) :
  22613. null;
  22614. return typeAttribute ? normalize(typeAttribute.value) : null
  22615. }
  22616. /**
  22617. * Remove the noise in case a user has defined the preprocessor type='text/scss'
  22618. * @param { string } value - input string
  22619. * @returns { string } normalized string
  22620. */
  22621. function normalize(value) {
  22622. return value.replace('text/', '')
  22623. }
  22624. /**
  22625. * Preprocess a riot parser node
  22626. * @param { string } preprocessorType - either css, js
  22627. * @param { string } preprocessorName - preprocessor id
  22628. * @param { Object } meta - compilation meta information
  22629. * @param { RiotParser.nodeTypes } node - css node detected by the parser
  22630. * @returns { Output } code and sourcemap generated by the preprocessor
  22631. */
  22632. function preprocess(preprocessorType, preprocessorName, meta, node) {
  22633. const code = node.text;
  22634. return (preprocessorName ?
  22635. execute$1(preprocessorType, preprocessorName, meta, code) :
  22636. { code }
  22637. )
  22638. }
  22639. /**
  22640. * Matches valid, multiline JavaScript comments in almost all its forms.
  22641. * @const {RegExp}
  22642. * @static
  22643. */
  22644. const R_MLCOMMS = /\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//g;
  22645. /**
  22646. * Source for creating regexes matching valid quoted, single-line JavaScript strings.
  22647. * It recognizes escape characters, including nested quotes and line continuation.
  22648. * @const {string}
  22649. */
  22650. const S_LINESTR = /"[^"\n\\]*(?:\\[\S\s][^"\n\\]*)*"|'[^'\n\\]*(?:\\[\S\s][^'\n\\]*)*'/.source;
  22651. /**
  22652. * Matches CSS selectors, excluding those beginning with '@' and quoted strings.
  22653. * @const {RegExp}
  22654. */
  22655. const CSS_SELECTOR = RegExp(`([{}]|^)[; ]*((?:[^@ ;{}][^{}]*)?[^@ ;{}:] ?)(?={)|${S_LINESTR}`, 'g');
  22656. /**
  22657. * Parses styles enclosed in a "scoped" tag
  22658. * The "css" string is received without comments or surrounding spaces.
  22659. *
  22660. * @param {string} tag - Tag name of the root element
  22661. * @param {string} css - The CSS code
  22662. * @returns {string} CSS with the styles scoped to the root element
  22663. */
  22664. function scopedCSS(tag, css) {
  22665. const host = ':host';
  22666. const selectorsBlacklist = ['from', 'to'];
  22667. return css.replace(CSS_SELECTOR, function(m, p1, p2) {
  22668. // skip quoted strings
  22669. if (!p2) return m
  22670. // we have a selector list, parse each individually
  22671. p2 = p2.replace(/[^,]+/g, function(sel) {
  22672. const s = sel.trim();
  22673. // skip selectors already using the tag name
  22674. if (s.indexOf(tag) === 0) {
  22675. return sel
  22676. }
  22677. // skips the keywords and percents of css animations
  22678. if (!s || selectorsBlacklist.indexOf(s) > -1 || s.slice(-1) === '%') {
  22679. return sel
  22680. }
  22681. // replace the `:host` pseudo-selector, where it is, with the root tag name;
  22682. // if `:host` was not included, add the tag name as prefix, and mirror all
  22683. // `[data-is]`
  22684. if (s.indexOf(host) < 0) {
  22685. return `${tag} ${s},[is="${tag}"] ${s}`
  22686. } else {
  22687. return `${s.replace(host, tag)},${
  22688. s.replace(host, `[is="${tag}"]`)}`
  22689. }
  22690. });
  22691. // add the danling bracket char and return the processed selector list
  22692. return p1 ? `${p1} ${p2}` : p2
  22693. })
  22694. }
  22695. /**
  22696. * Remove comments, compact and trim whitespace
  22697. * @param { string } code - compiled css code
  22698. * @returns { string } css code normalized
  22699. */
  22700. function compactCss(code) {
  22701. return code.replace(R_MLCOMMS, '').replace(/\s+/g, ' ').trim()
  22702. }
  22703. const escapeBackslashes = s => s.replace(/\\/g, '\\\\');
  22704. const escapeIdentifier = identifier => escapeBackslashes(cssesc_1(identifier, {
  22705. isIdentifier: true
  22706. }));
  22707. /**
  22708. * Generate the component css
  22709. * @param { Object } sourceNode - node generated by the riot compiler
  22710. * @param { string } source - original component source code
  22711. * @param { Object } meta - compilation meta information
  22712. * @param { AST } ast - current AST output
  22713. * @returns { AST } the AST generated
  22714. */
  22715. function css(sourceNode, source, meta, ast) {
  22716. const preprocessorName = getPreprocessorTypeByAttribute(sourceNode);
  22717. const { options } = meta;
  22718. const preprocessorOutput = preprocess('css', preprocessorName, meta, sourceNode.text);
  22719. const normalizedCssCode = compactCss(preprocessorOutput.code);
  22720. const escapedCssIdentifier = escapeIdentifier(meta.tagName);
  22721. const cssCode = (options.scopedCss ?
  22722. scopedCSS(escapedCssIdentifier, escapeBackslashes(normalizedCssCode)) :
  22723. escapeBackslashes(normalizedCssCode)
  22724. ).trim();
  22725. types$1.visit(ast, {
  22726. visitProperty(path) {
  22727. if (path.value.key.value === TAG_CSS_PROPERTY) {
  22728. path.value.value = builders.templateLiteral(
  22729. [builders.templateElement({ raw: cssCode, cooked: '' }, false)],
  22730. []
  22731. );
  22732. return false
  22733. }
  22734. this.traverse(path);
  22735. }
  22736. });
  22737. return ast
  22738. }
  22739. /**
  22740. * Function to curry any javascript method
  22741. * @param {Function} fn - the target function we want to curry
  22742. * @param {...[args]} acc - initial arguments
  22743. * @returns {Function|*} it will return a function until the target function
  22744. * will receive all of its arguments
  22745. */
  22746. function curry(fn, ...acc) {
  22747. return (...args) => {
  22748. args = [...acc, ...args];
  22749. return args.length < fn.length ?
  22750. curry(fn, ...args) :
  22751. fn(...args)
  22752. }
  22753. }
  22754. /**
  22755. * Generate the javascript from an ast source
  22756. * @param {AST} ast - ast object
  22757. * @param {Object} options - printer options
  22758. * @returns {Object} code + map
  22759. */
  22760. function generateJavascript(ast, options) {
  22761. return main_4$1(ast, {
  22762. ...options,
  22763. tabWidth: 2,
  22764. quote: 'single'
  22765. })
  22766. }
  22767. /**
  22768. * True if the sourcemap has no mappings, it is empty
  22769. * @param {Object} map - sourcemap json
  22770. * @returns {boolean} true if empty
  22771. */
  22772. function isEmptySourcemap(map) {
  22773. return !map || !map.mappings || !map.mappings.length
  22774. }
  22775. const LINES_RE = /\r\n?|\n/g;
  22776. /**
  22777. * Split a string into a rows array generated from its EOL matches
  22778. * @param { string } string [description]
  22779. * @returns { Array } array containing all the string rows
  22780. */
  22781. function splitStringByEOL(string) {
  22782. return string.split(LINES_RE)
  22783. }
  22784. /**
  22785. * Get the line and the column of a source text based on its position in the string
  22786. * @param { string } string - target string
  22787. * @param { number } position - target position
  22788. * @returns { Object } object containing the source text line and column
  22789. */
  22790. function getLineAndColumnByPosition(string, position) {
  22791. const lines = splitStringByEOL(string.slice(0, position));
  22792. return {
  22793. line: lines.length,
  22794. column: lines[lines.length - 1].length
  22795. }
  22796. }
  22797. /**
  22798. * Add the offset to the code that must be parsed in order to generate properly the sourcemaps
  22799. * @param {string} input - input string
  22800. * @param {string} source - original source code
  22801. * @param {RiotParser.Node} node - node that we are going to transform
  22802. * @return {string} the input string with the offset properly set
  22803. */
  22804. function addLineOffset(input, source, node) {
  22805. const {column, line} = getLineAndColumnByPosition(source, node.start);
  22806. return `${'\n'.repeat(line - 1)}${' '.repeat(column + 1)}${input}`
  22807. }
  22808. // Reserved word lists for various dialects of the language
  22809. var reservedWords = {
  22810. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  22811. 5: "class enum extends super const export import",
  22812. 6: "enum",
  22813. strict: "implements interface let package private protected public static yield",
  22814. strictBind: "eval arguments"
  22815. };
  22816. // And the keywords
  22817. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  22818. var keywords = {
  22819. 5: ecma5AndLessKeywords,
  22820. "5module": ecma5AndLessKeywords + " export import",
  22821. 6: ecma5AndLessKeywords + " const class extends export import super"
  22822. };
  22823. var keywordRelationalOperator = /^in(stanceof)?$/;
  22824. // ## Character categories
  22825. // Big ugly regular expressions that match characters in the
  22826. // whitespace, identifier, and identifier-start categories. These
  22827. // are only applied when a character is found to actually have a
  22828. // code point above 128.
  22829. // Generated by `bin/generate-identifier-regex.js`.
  22830. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab67\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38
  22831. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  22832. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  22833. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  22834. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  22835. // These are a run-length and offset encoded representation of the
  22836. // >0xffff code points that are a valid part of identifiers. The
  22837. // offset starts at 0x10000, and each pair of numbers represents an
  22838. // offset to the next range, and then a size of the range. They were
  22839. // generated by bin/generate-identifier-regex.js
  22840. // eslint-disable-next-line comma-spacing
  22841. var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,754,9486,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541];
  22842. // eslint-disable-next-line comma-spacing
  22843. var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,232,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,792487,239];
  22844. // This has a complexity linear to the value of the code. The
  22845. // assumption is that looking up astral identifier characters is
  22846. // rare.
  22847. function isInAstralSet(code, set) {
  22848. var pos = 0x10000;
  22849. for (var i = 0; i < set.length; i += 2) {
  22850. pos += set[i];
  22851. if (pos > code) { return false }
  22852. pos += set[i + 1];
  22853. if (pos >= code) { return true }
  22854. }
  22855. }
  22856. // Test whether a given character code starts an identifier.
  22857. function isIdentifierStart(code, astral) {
  22858. if (code < 65) { return code === 36 }
  22859. if (code < 91) { return true }
  22860. if (code < 97) { return code === 95 }
  22861. if (code < 123) { return true }
  22862. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  22863. if (astral === false) { return false }
  22864. return isInAstralSet(code, astralIdentifierStartCodes)
  22865. }
  22866. // Test whether a given character is part of an identifier.
  22867. function isIdentifierChar(code, astral) {
  22868. if (code < 48) { return code === 36 }
  22869. if (code < 58) { return true }
  22870. if (code < 65) { return false }
  22871. if (code < 91) { return true }
  22872. if (code < 97) { return code === 95 }
  22873. if (code < 123) { return true }
  22874. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  22875. if (astral === false) { return false }
  22876. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  22877. }
  22878. // ## Token types
  22879. // The assignment of fine-grained, information-carrying type objects
  22880. // allows the tokenizer to store the information it has about a
  22881. // token in a way that is very cheap for the parser to look up.
  22882. // All token type variables start with an underscore, to make them
  22883. // easy to recognize.
  22884. // The `beforeExpr` property is used to disambiguate between regular
  22885. // expressions and divisions. It is set on all token types that can
  22886. // be followed by an expression (thus, a slash after them would be a
  22887. // regular expression).
  22888. //
  22889. // The `startsExpr` property is used to check if the token ends a
  22890. // `yield` expression. It is set on all token types that either can
  22891. // directly start an expression (like a quotation mark) or can
  22892. // continue an expression (like the body of a string).
  22893. //
  22894. // `isLoop` marks a keyword as starting a loop, which is important
  22895. // to know when parsing a label, in order to allow or disallow
  22896. // continue jumps to that label.
  22897. var TokenType = function TokenType(label, conf) {
  22898. if ( conf === void 0 ) conf = {};
  22899. this.label = label;
  22900. this.keyword = conf.keyword;
  22901. this.beforeExpr = !!conf.beforeExpr;
  22902. this.startsExpr = !!conf.startsExpr;
  22903. this.isLoop = !!conf.isLoop;
  22904. this.isAssign = !!conf.isAssign;
  22905. this.prefix = !!conf.prefix;
  22906. this.postfix = !!conf.postfix;
  22907. this.binop = conf.binop || null;
  22908. this.updateContext = null;
  22909. };
  22910. function binop(name, prec) {
  22911. return new TokenType(name, {beforeExpr: true, binop: prec})
  22912. }
  22913. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  22914. // Map keyword names to token types.
  22915. var keywords$1 = {};
  22916. // Succinct definitions of keyword token types
  22917. function kw(name, options) {
  22918. if ( options === void 0 ) options = {};
  22919. options.keyword = name;
  22920. return keywords$1[name] = new TokenType(name, options)
  22921. }
  22922. var types$2 = {
  22923. num: new TokenType("num", startsExpr),
  22924. regexp: new TokenType("regexp", startsExpr),
  22925. string: new TokenType("string", startsExpr),
  22926. name: new TokenType("name", startsExpr),
  22927. eof: new TokenType("eof"),
  22928. // Punctuation token types.
  22929. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  22930. bracketR: new TokenType("]"),
  22931. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  22932. braceR: new TokenType("}"),
  22933. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  22934. parenR: new TokenType(")"),
  22935. comma: new TokenType(",", beforeExpr),
  22936. semi: new TokenType(";", beforeExpr),
  22937. colon: new TokenType(":", beforeExpr),
  22938. dot: new TokenType("."),
  22939. question: new TokenType("?", beforeExpr),
  22940. arrow: new TokenType("=>", beforeExpr),
  22941. template: new TokenType("template"),
  22942. invalidTemplate: new TokenType("invalidTemplate"),
  22943. ellipsis: new TokenType("...", beforeExpr),
  22944. backQuote: new TokenType("`", startsExpr),
  22945. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  22946. // Operators. These carry several kinds of properties to help the
  22947. // parser use them properly (the presence of these properties is
  22948. // what categorizes them as operators).
  22949. //
  22950. // `binop`, when present, specifies that this operator is a binary
  22951. // operator, and will refer to its precedence.
  22952. //
  22953. // `prefix` and `postfix` mark the operator as a prefix or postfix
  22954. // unary operator.
  22955. //
  22956. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  22957. // binary operators with a very low precedence, that should result
  22958. // in AssignmentExpression nodes.
  22959. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  22960. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  22961. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  22962. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  22963. logicalOR: binop("||", 1),
  22964. logicalAND: binop("&&", 2),
  22965. bitwiseOR: binop("|", 3),
  22966. bitwiseXOR: binop("^", 4),
  22967. bitwiseAND: binop("&", 5),
  22968. equality: binop("==/!=/===/!==", 6),
  22969. relational: binop("</>/<=/>=", 7),
  22970. bitShift: binop("<</>>/>>>", 8),
  22971. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  22972. modulo: binop("%", 10),
  22973. star: binop("*", 10),
  22974. slash: binop("/", 10),
  22975. starstar: new TokenType("**", {beforeExpr: true}),
  22976. // Keyword token types.
  22977. _break: kw("break"),
  22978. _case: kw("case", beforeExpr),
  22979. _catch: kw("catch"),
  22980. _continue: kw("continue"),
  22981. _debugger: kw("debugger"),
  22982. _default: kw("default", beforeExpr),
  22983. _do: kw("do", {isLoop: true, beforeExpr: true}),
  22984. _else: kw("else", beforeExpr),
  22985. _finally: kw("finally"),
  22986. _for: kw("for", {isLoop: true}),
  22987. _function: kw("function", startsExpr),
  22988. _if: kw("if"),
  22989. _return: kw("return", beforeExpr),
  22990. _switch: kw("switch"),
  22991. _throw: kw("throw", beforeExpr),
  22992. _try: kw("try"),
  22993. _var: kw("var"),
  22994. _const: kw("const"),
  22995. _while: kw("while", {isLoop: true}),
  22996. _with: kw("with"),
  22997. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  22998. _this: kw("this", startsExpr),
  22999. _super: kw("super", startsExpr),
  23000. _class: kw("class", startsExpr),
  23001. _extends: kw("extends", beforeExpr),
  23002. _export: kw("export"),
  23003. _import: kw("import", startsExpr),
  23004. _null: kw("null", startsExpr),
  23005. _true: kw("true", startsExpr),
  23006. _false: kw("false", startsExpr),
  23007. _in: kw("in", {beforeExpr: true, binop: 7}),
  23008. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  23009. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  23010. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  23011. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  23012. };
  23013. // Matches a whole line break (where CRLF is considered a single
  23014. // line break). Used to count lines.
  23015. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  23016. var lineBreakG = new RegExp(lineBreak.source, "g");
  23017. function isNewLine(code, ecma2019String) {
  23018. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  23019. }
  23020. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  23021. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  23022. var ref = Object.prototype;
  23023. var hasOwnProperty$2 = ref.hasOwnProperty;
  23024. var toString = ref.toString;
  23025. // Checks if an object has a property.
  23026. function has$1(obj, propName) {
  23027. return hasOwnProperty$2.call(obj, propName)
  23028. }
  23029. var isArray$1 = Array.isArray || (function (obj) { return (
  23030. toString.call(obj) === "[object Array]"
  23031. ); });
  23032. function wordsRegexp(words) {
  23033. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  23034. }
  23035. // These are used when `options.locations` is on, for the
  23036. // `startLoc` and `endLoc` properties.
  23037. var Position = function Position(line, col) {
  23038. this.line = line;
  23039. this.column = col;
  23040. };
  23041. Position.prototype.offset = function offset (n) {
  23042. return new Position(this.line, this.column + n)
  23043. };
  23044. var SourceLocation = function SourceLocation(p, start, end) {
  23045. this.start = start;
  23046. this.end = end;
  23047. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  23048. };
  23049. // The `getLineInfo` function is mostly useful when the
  23050. // `locations` option is off (for performance reasons) and you
  23051. // want to find the line/column position for a given character
  23052. // offset. `input` should be the code string that the offset refers
  23053. // into.
  23054. function getLineInfo(input, offset) {
  23055. for (var line = 1, cur = 0;;) {
  23056. lineBreakG.lastIndex = cur;
  23057. var match = lineBreakG.exec(input);
  23058. if (match && match.index < offset) {
  23059. ++line;
  23060. cur = match.index + match[0].length;
  23061. } else {
  23062. return new Position(line, offset - cur)
  23063. }
  23064. }
  23065. }
  23066. // A second optional argument can be given to further configure
  23067. // the parser process. These options are recognized:
  23068. var defaultOptions = {
  23069. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  23070. // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
  23071. // (2019). This influences support for strict mode, the set of
  23072. // reserved words, and support for new syntax features. The default
  23073. // is 10.
  23074. ecmaVersion: 10,
  23075. // `sourceType` indicates the mode the code should be parsed in.
  23076. // Can be either `"script"` or `"module"`. This influences global
  23077. // strict mode and parsing of `import` and `export` declarations.
  23078. sourceType: "script",
  23079. // `onInsertedSemicolon` can be a callback that will be called
  23080. // when a semicolon is automatically inserted. It will be passed
  23081. // the position of the comma as an offset, and if `locations` is
  23082. // enabled, it is given the location as a `{line, column}` object
  23083. // as second argument.
  23084. onInsertedSemicolon: null,
  23085. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  23086. // trailing commas.
  23087. onTrailingComma: null,
  23088. // By default, reserved words are only enforced if ecmaVersion >= 5.
  23089. // Set `allowReserved` to a boolean value to explicitly turn this on
  23090. // an off. When this option has the value "never", reserved words
  23091. // and keywords can also not be used as property names.
  23092. allowReserved: null,
  23093. // When enabled, a return at the top level is not considered an
  23094. // error.
  23095. allowReturnOutsideFunction: false,
  23096. // When enabled, import/export statements are not constrained to
  23097. // appearing at the top of the program.
  23098. allowImportExportEverywhere: false,
  23099. // When enabled, await identifiers are allowed to appear at the top-level scope,
  23100. // but they are still not allowed in non-async functions.
  23101. allowAwaitOutsideFunction: false,
  23102. // When enabled, hashbang directive in the beginning of file
  23103. // is allowed and treated as a line comment.
  23104. allowHashBang: false,
  23105. // When `locations` is on, `loc` properties holding objects with
  23106. // `start` and `end` properties in `{line, column}` form (with
  23107. // line being 1-based and column 0-based) will be attached to the
  23108. // nodes.
  23109. locations: false,
  23110. // A function can be passed as `onToken` option, which will
  23111. // cause Acorn to call that function with object in the same
  23112. // format as tokens returned from `tokenizer().getToken()`. Note
  23113. // that you are not allowed to call the parser from the
  23114. // callback—that will corrupt its internal state.
  23115. onToken: null,
  23116. // A function can be passed as `onComment` option, which will
  23117. // cause Acorn to call that function with `(block, text, start,
  23118. // end)` parameters whenever a comment is skipped. `block` is a
  23119. // boolean indicating whether this is a block (`/* */`) comment,
  23120. // `text` is the content of the comment, and `start` and `end` are
  23121. // character offsets that denote the start and end of the comment.
  23122. // When the `locations` option is on, two more parameters are
  23123. // passed, the full `{line, column}` locations of the start and
  23124. // end of the comments. Note that you are not allowed to call the
  23125. // parser from the callback—that will corrupt its internal state.
  23126. onComment: null,
  23127. // Nodes have their start and end characters offsets recorded in
  23128. // `start` and `end` properties (directly on the node, rather than
  23129. // the `loc` object, which holds line/column data. To also add a
  23130. // [semi-standardized][range] `range` property holding a `[start,
  23131. // end]` array with the same numbers, set the `ranges` option to
  23132. // `true`.
  23133. //
  23134. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  23135. ranges: false,
  23136. // It is possible to parse multiple files into a single AST by
  23137. // passing the tree produced by parsing the first file as
  23138. // `program` option in subsequent parses. This will add the
  23139. // toplevel forms of the parsed file to the `Program` (top) node
  23140. // of an existing parse tree.
  23141. program: null,
  23142. // When `locations` is on, you can pass this to record the source
  23143. // file in every node's `loc` object.
  23144. sourceFile: null,
  23145. // This value, if given, is stored in every node, whether
  23146. // `locations` is on or off.
  23147. directSourceFile: null,
  23148. // When enabled, parenthesized expressions are represented by
  23149. // (non-standard) ParenthesizedExpression nodes
  23150. preserveParens: false
  23151. };
  23152. // Interpret and default an options object
  23153. function getOptions(opts) {
  23154. var options = {};
  23155. for (var opt in defaultOptions)
  23156. { options[opt] = opts && has$1(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  23157. if (options.ecmaVersion >= 2015)
  23158. { options.ecmaVersion -= 2009; }
  23159. if (options.allowReserved == null)
  23160. { options.allowReserved = options.ecmaVersion < 5; }
  23161. if (isArray$1(options.onToken)) {
  23162. var tokens = options.onToken;
  23163. options.onToken = function (token) { return tokens.push(token); };
  23164. }
  23165. if (isArray$1(options.onComment))
  23166. { options.onComment = pushComment(options, options.onComment); }
  23167. return options
  23168. }
  23169. function pushComment(options, array) {
  23170. return function(block, text, start, end, startLoc, endLoc) {
  23171. var comment = {
  23172. type: block ? "Block" : "Line",
  23173. value: text,
  23174. start: start,
  23175. end: end
  23176. };
  23177. if (options.locations)
  23178. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  23179. if (options.ranges)
  23180. { comment.range = [start, end]; }
  23181. array.push(comment);
  23182. }
  23183. }
  23184. // Each scope gets a bitset that may contain these flags
  23185. var
  23186. SCOPE_TOP = 1,
  23187. SCOPE_FUNCTION = 2,
  23188. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  23189. SCOPE_ASYNC = 4,
  23190. SCOPE_GENERATOR = 8,
  23191. SCOPE_ARROW = 16,
  23192. SCOPE_SIMPLE_CATCH = 32,
  23193. SCOPE_SUPER = 64,
  23194. SCOPE_DIRECT_SUPER = 128;
  23195. function functionFlags(async, generator) {
  23196. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  23197. }
  23198. // Used in checkLVal and declareName to determine the type of a binding
  23199. var
  23200. BIND_NONE = 0, // Not a binding
  23201. BIND_VAR = 1, // Var-style binding
  23202. BIND_LEXICAL = 2, // Let- or const-style binding
  23203. BIND_FUNCTION = 3, // Function declaration
  23204. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  23205. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  23206. var Parser = function Parser(options, input, startPos) {
  23207. this.options = options = getOptions(options);
  23208. this.sourceFile = options.sourceFile;
  23209. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  23210. var reserved = "";
  23211. if (options.allowReserved !== true) {
  23212. for (var v = options.ecmaVersion;; v--)
  23213. { if (reserved = reservedWords[v]) { break } }
  23214. if (options.sourceType === "module") { reserved += " await"; }
  23215. }
  23216. this.reservedWords = wordsRegexp(reserved);
  23217. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  23218. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  23219. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  23220. this.input = String(input);
  23221. // Used to signal to callers of `readWord1` whether the word
  23222. // contained any escape sequences. This is needed because words with
  23223. // escape sequences must not be interpreted as keywords.
  23224. this.containsEsc = false;
  23225. // Set up token state
  23226. // The current position of the tokenizer in the input.
  23227. if (startPos) {
  23228. this.pos = startPos;
  23229. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  23230. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  23231. } else {
  23232. this.pos = this.lineStart = 0;
  23233. this.curLine = 1;
  23234. }
  23235. // Properties of the current token:
  23236. // Its type
  23237. this.type = types$2.eof;
  23238. // For tokens that include more information than their type, the value
  23239. this.value = null;
  23240. // Its start and end offset
  23241. this.start = this.end = this.pos;
  23242. // And, if locations are used, the {line, column} object
  23243. // corresponding to those offsets
  23244. this.startLoc = this.endLoc = this.curPosition();
  23245. // Position information for the previous token
  23246. this.lastTokEndLoc = this.lastTokStartLoc = null;
  23247. this.lastTokStart = this.lastTokEnd = this.pos;
  23248. // The context stack is used to superficially track syntactic
  23249. // context to predict whether a regular expression is allowed in a
  23250. // given position.
  23251. this.context = this.initialContext();
  23252. this.exprAllowed = true;
  23253. // Figure out if it's a module code.
  23254. this.inModule = options.sourceType === "module";
  23255. this.strict = this.inModule || this.strictDirective(this.pos);
  23256. // Used to signify the start of a potential arrow function
  23257. this.potentialArrowAt = -1;
  23258. // Positions to delayed-check that yield/await does not exist in default parameters.
  23259. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  23260. // Labels in scope.
  23261. this.labels = [];
  23262. // Thus-far undefined exports.
  23263. this.undefinedExports = {};
  23264. // If enabled, skip leading hashbang line.
  23265. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  23266. { this.skipLineComment(2); }
  23267. // Scope tracking for duplicate variable names (see scope.js)
  23268. this.scopeStack = [];
  23269. this.enterScope(SCOPE_TOP);
  23270. // For RegExp validation
  23271. this.regexpState = null;
  23272. };
  23273. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
  23274. Parser.prototype.parse = function parse () {
  23275. var node = this.options.program || this.startNode();
  23276. this.nextToken();
  23277. return this.parseTopLevel(node)
  23278. };
  23279. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  23280. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
  23281. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
  23282. prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
  23283. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  23284. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  23285. // Switch to a getter for 7.0.0.
  23286. Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
  23287. Parser.extend = function extend () {
  23288. var plugins = [], len = arguments.length;
  23289. while ( len-- ) plugins[ len ] = arguments[ len ];
  23290. var cls = this;
  23291. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  23292. return cls
  23293. };
  23294. Parser.parse = function parse (input, options) {
  23295. return new this(options, input).parse()
  23296. };
  23297. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  23298. var parser = new this(options, input, pos);
  23299. parser.nextToken();
  23300. return parser.parseExpression()
  23301. };
  23302. Parser.tokenizer = function tokenizer (input, options) {
  23303. return new this(options, input)
  23304. };
  23305. Object.defineProperties( Parser.prototype, prototypeAccessors );
  23306. var pp = Parser.prototype;
  23307. // ## Parser utilities
  23308. var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
  23309. pp.strictDirective = function(start) {
  23310. for (;;) {
  23311. // Try to find string literal.
  23312. skipWhiteSpace.lastIndex = start;
  23313. start += skipWhiteSpace.exec(this.input)[0].length;
  23314. var match = literal.exec(this.input.slice(start));
  23315. if (!match) { return false }
  23316. if ((match[1] || match[2]) === "use strict") { return true }
  23317. start += match[0].length;
  23318. // Skip semicolon, if any.
  23319. skipWhiteSpace.lastIndex = start;
  23320. start += skipWhiteSpace.exec(this.input)[0].length;
  23321. if (this.input[start] === ";")
  23322. { start++; }
  23323. }
  23324. };
  23325. // Predicate that tests whether the next token is of the given
  23326. // type, and if yes, consumes it as a side effect.
  23327. pp.eat = function(type) {
  23328. if (this.type === type) {
  23329. this.next();
  23330. return true
  23331. } else {
  23332. return false
  23333. }
  23334. };
  23335. // Tests whether parsed token is a contextual keyword.
  23336. pp.isContextual = function(name) {
  23337. return this.type === types$2.name && this.value === name && !this.containsEsc
  23338. };
  23339. // Consumes contextual keyword if possible.
  23340. pp.eatContextual = function(name) {
  23341. if (!this.isContextual(name)) { return false }
  23342. this.next();
  23343. return true
  23344. };
  23345. // Asserts that following token is given contextual keyword.
  23346. pp.expectContextual = function(name) {
  23347. if (!this.eatContextual(name)) { this.unexpected(); }
  23348. };
  23349. // Test whether a semicolon can be inserted at the current position.
  23350. pp.canInsertSemicolon = function() {
  23351. return this.type === types$2.eof ||
  23352. this.type === types$2.braceR ||
  23353. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  23354. };
  23355. pp.insertSemicolon = function() {
  23356. if (this.canInsertSemicolon()) {
  23357. if (this.options.onInsertedSemicolon)
  23358. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  23359. return true
  23360. }
  23361. };
  23362. // Consume a semicolon, or, failing that, see if we are allowed to
  23363. // pretend that there is a semicolon at this position.
  23364. pp.semicolon = function() {
  23365. if (!this.eat(types$2.semi) && !this.insertSemicolon()) { this.unexpected(); }
  23366. };
  23367. pp.afterTrailingComma = function(tokType, notNext) {
  23368. if (this.type === tokType) {
  23369. if (this.options.onTrailingComma)
  23370. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  23371. if (!notNext)
  23372. { this.next(); }
  23373. return true
  23374. }
  23375. };
  23376. // Expect a token of a given type. If found, consume it, otherwise,
  23377. // raise an unexpected token error.
  23378. pp.expect = function(type) {
  23379. this.eat(type) || this.unexpected();
  23380. };
  23381. // Raise an unexpected token error.
  23382. pp.unexpected = function(pos) {
  23383. this.raise(pos != null ? pos : this.start, "Unexpected token");
  23384. };
  23385. function DestructuringErrors() {
  23386. this.shorthandAssign =
  23387. this.trailingComma =
  23388. this.parenthesizedAssign =
  23389. this.parenthesizedBind =
  23390. this.doubleProto =
  23391. -1;
  23392. }
  23393. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  23394. if (!refDestructuringErrors) { return }
  23395. if (refDestructuringErrors.trailingComma > -1)
  23396. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  23397. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  23398. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  23399. };
  23400. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  23401. if (!refDestructuringErrors) { return false }
  23402. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  23403. var doubleProto = refDestructuringErrors.doubleProto;
  23404. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  23405. if (shorthandAssign >= 0)
  23406. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  23407. if (doubleProto >= 0)
  23408. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  23409. };
  23410. pp.checkYieldAwaitInDefaultParams = function() {
  23411. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  23412. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  23413. if (this.awaitPos)
  23414. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  23415. };
  23416. pp.isSimpleAssignTarget = function(expr) {
  23417. if (expr.type === "ParenthesizedExpression")
  23418. { return this.isSimpleAssignTarget(expr.expression) }
  23419. return expr.type === "Identifier" || expr.type === "MemberExpression"
  23420. };
  23421. var pp$1 = Parser.prototype;
  23422. // ### Statement parsing
  23423. // Parse a program. Initializes the parser, reads any number of
  23424. // statements, and wraps them in a Program node. Optionally takes a
  23425. // `program` argument. If present, the statements will be appended
  23426. // to its body instead of creating a new node.
  23427. pp$1.parseTopLevel = function(node) {
  23428. var exports = {};
  23429. if (!node.body) { node.body = []; }
  23430. while (this.type !== types$2.eof) {
  23431. var stmt = this.parseStatement(null, true, exports);
  23432. node.body.push(stmt);
  23433. }
  23434. if (this.inModule)
  23435. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  23436. {
  23437. var name = list[i];
  23438. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  23439. } }
  23440. this.adaptDirectivePrologue(node.body);
  23441. this.next();
  23442. node.sourceType = this.options.sourceType;
  23443. return this.finishNode(node, "Program")
  23444. };
  23445. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  23446. pp$1.isLet = function(context) {
  23447. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  23448. skipWhiteSpace.lastIndex = this.pos;
  23449. var skip = skipWhiteSpace.exec(this.input);
  23450. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  23451. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  23452. // Statement) is allowed here. If context is not empty then only a Statement
  23453. // is allowed. However, `let [` is an explicit negative lookahead for
  23454. // ExpressionStatement, so special-case it first.
  23455. if (nextCh === 91) { return true } // '['
  23456. if (context) { return false }
  23457. if (nextCh === 123) { return true } // '{'
  23458. if (isIdentifierStart(nextCh, true)) {
  23459. var pos = next + 1;
  23460. while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
  23461. var ident = this.input.slice(next, pos);
  23462. if (!keywordRelationalOperator.test(ident)) { return true }
  23463. }
  23464. return false
  23465. };
  23466. // check 'async [no LineTerminator here] function'
  23467. // - 'async /*foo*/ function' is OK.
  23468. // - 'async /*\n*/ function' is invalid.
  23469. pp$1.isAsyncFunction = function() {
  23470. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  23471. { return false }
  23472. skipWhiteSpace.lastIndex = this.pos;
  23473. var skip = skipWhiteSpace.exec(this.input);
  23474. var next = this.pos + skip[0].length;
  23475. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  23476. this.input.slice(next, next + 8) === "function" &&
  23477. (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
  23478. };
  23479. // Parse a single statement.
  23480. //
  23481. // If expecting a statement and finding a slash operator, parse a
  23482. // regular expression literal. This is to handle cases like
  23483. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  23484. // does not help.
  23485. pp$1.parseStatement = function(context, topLevel, exports) {
  23486. var starttype = this.type, node = this.startNode(), kind;
  23487. if (this.isLet(context)) {
  23488. starttype = types$2._var;
  23489. kind = "let";
  23490. }
  23491. // Most types of statements are recognized by the keyword they
  23492. // start with. Many are trivial to parse, some require a bit of
  23493. // complexity.
  23494. switch (starttype) {
  23495. case types$2._break: case types$2._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  23496. case types$2._debugger: return this.parseDebuggerStatement(node)
  23497. case types$2._do: return this.parseDoStatement(node)
  23498. case types$2._for: return this.parseForStatement(node)
  23499. case types$2._function:
  23500. // Function as sole body of either an if statement or a labeled statement
  23501. // works, but not when it is part of a labeled statement that is the sole
  23502. // body of an if statement.
  23503. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  23504. return this.parseFunctionStatement(node, false, !context)
  23505. case types$2._class:
  23506. if (context) { this.unexpected(); }
  23507. return this.parseClass(node, true)
  23508. case types$2._if: return this.parseIfStatement(node)
  23509. case types$2._return: return this.parseReturnStatement(node)
  23510. case types$2._switch: return this.parseSwitchStatement(node)
  23511. case types$2._throw: return this.parseThrowStatement(node)
  23512. case types$2._try: return this.parseTryStatement(node)
  23513. case types$2._const: case types$2._var:
  23514. kind = kind || this.value;
  23515. if (context && kind !== "var") { this.unexpected(); }
  23516. return this.parseVarStatement(node, kind)
  23517. case types$2._while: return this.parseWhileStatement(node)
  23518. case types$2._with: return this.parseWithStatement(node)
  23519. case types$2.braceL: return this.parseBlock(true, node)
  23520. case types$2.semi: return this.parseEmptyStatement(node)
  23521. case types$2._export:
  23522. case types$2._import:
  23523. if (this.options.ecmaVersion > 10 && starttype === types$2._import) {
  23524. skipWhiteSpace.lastIndex = this.pos;
  23525. var skip = skipWhiteSpace.exec(this.input);
  23526. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  23527. if (nextCh === 40) // '('
  23528. { return this.parseExpressionStatement(node, this.parseExpression()) }
  23529. }
  23530. if (!this.options.allowImportExportEverywhere) {
  23531. if (!topLevel)
  23532. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  23533. if (!this.inModule)
  23534. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  23535. }
  23536. return starttype === types$2._import ? this.parseImport(node) : this.parseExport(node, exports)
  23537. // If the statement does not start with a statement keyword or a
  23538. // brace, it's an ExpressionStatement or LabeledStatement. We
  23539. // simply start parsing an expression, and afterwards, if the
  23540. // next token is a colon and the expression was a simple
  23541. // Identifier node, we switch to interpreting it as a label.
  23542. default:
  23543. if (this.isAsyncFunction()) {
  23544. if (context) { this.unexpected(); }
  23545. this.next();
  23546. return this.parseFunctionStatement(node, true, !context)
  23547. }
  23548. var maybeName = this.value, expr = this.parseExpression();
  23549. if (starttype === types$2.name && expr.type === "Identifier" && this.eat(types$2.colon))
  23550. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  23551. else { return this.parseExpressionStatement(node, expr) }
  23552. }
  23553. };
  23554. pp$1.parseBreakContinueStatement = function(node, keyword) {
  23555. var isBreak = keyword === "break";
  23556. this.next();
  23557. if (this.eat(types$2.semi) || this.insertSemicolon()) { node.label = null; }
  23558. else if (this.type !== types$2.name) { this.unexpected(); }
  23559. else {
  23560. node.label = this.parseIdent();
  23561. this.semicolon();
  23562. }
  23563. // Verify that there is an actual destination to break or
  23564. // continue to.
  23565. var i = 0;
  23566. for (; i < this.labels.length; ++i) {
  23567. var lab = this.labels[i];
  23568. if (node.label == null || lab.name === node.label.name) {
  23569. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  23570. if (node.label && isBreak) { break }
  23571. }
  23572. }
  23573. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  23574. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  23575. };
  23576. pp$1.parseDebuggerStatement = function(node) {
  23577. this.next();
  23578. this.semicolon();
  23579. return this.finishNode(node, "DebuggerStatement")
  23580. };
  23581. pp$1.parseDoStatement = function(node) {
  23582. this.next();
  23583. this.labels.push(loopLabel);
  23584. node.body = this.parseStatement("do");
  23585. this.labels.pop();
  23586. this.expect(types$2._while);
  23587. node.test = this.parseParenExpression();
  23588. if (this.options.ecmaVersion >= 6)
  23589. { this.eat(types$2.semi); }
  23590. else
  23591. { this.semicolon(); }
  23592. return this.finishNode(node, "DoWhileStatement")
  23593. };
  23594. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  23595. // loop is non-trivial. Basically, we have to parse the init `var`
  23596. // statement or expression, disallowing the `in` operator (see
  23597. // the second parameter to `parseExpression`), and then check
  23598. // whether the next token is `in` or `of`. When there is no init
  23599. // part (semicolon immediately after the opening parenthesis), it
  23600. // is a regular `for` loop.
  23601. pp$1.parseForStatement = function(node) {
  23602. this.next();
  23603. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  23604. this.labels.push(loopLabel);
  23605. this.enterScope(0);
  23606. this.expect(types$2.parenL);
  23607. if (this.type === types$2.semi) {
  23608. if (awaitAt > -1) { this.unexpected(awaitAt); }
  23609. return this.parseFor(node, null)
  23610. }
  23611. var isLet = this.isLet();
  23612. if (this.type === types$2._var || this.type === types$2._const || isLet) {
  23613. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  23614. this.next();
  23615. this.parseVar(init$1, true, kind);
  23616. this.finishNode(init$1, "VariableDeclaration");
  23617. if ((this.type === types$2._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  23618. if (this.options.ecmaVersion >= 9) {
  23619. if (this.type === types$2._in) {
  23620. if (awaitAt > -1) { this.unexpected(awaitAt); }
  23621. } else { node.await = awaitAt > -1; }
  23622. }
  23623. return this.parseForIn(node, init$1)
  23624. }
  23625. if (awaitAt > -1) { this.unexpected(awaitAt); }
  23626. return this.parseFor(node, init$1)
  23627. }
  23628. var refDestructuringErrors = new DestructuringErrors;
  23629. var init = this.parseExpression(true, refDestructuringErrors);
  23630. if (this.type === types$2._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  23631. if (this.options.ecmaVersion >= 9) {
  23632. if (this.type === types$2._in) {
  23633. if (awaitAt > -1) { this.unexpected(awaitAt); }
  23634. } else { node.await = awaitAt > -1; }
  23635. }
  23636. this.toAssignable(init, false, refDestructuringErrors);
  23637. this.checkLVal(init);
  23638. return this.parseForIn(node, init)
  23639. } else {
  23640. this.checkExpressionErrors(refDestructuringErrors, true);
  23641. }
  23642. if (awaitAt > -1) { this.unexpected(awaitAt); }
  23643. return this.parseFor(node, init)
  23644. };
  23645. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  23646. this.next();
  23647. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  23648. };
  23649. pp$1.parseIfStatement = function(node) {
  23650. this.next();
  23651. node.test = this.parseParenExpression();
  23652. // allow function declarations in branches, but only in non-strict mode
  23653. node.consequent = this.parseStatement("if");
  23654. node.alternate = this.eat(types$2._else) ? this.parseStatement("if") : null;
  23655. return this.finishNode(node, "IfStatement")
  23656. };
  23657. pp$1.parseReturnStatement = function(node) {
  23658. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  23659. { this.raise(this.start, "'return' outside of function"); }
  23660. this.next();
  23661. // In `return` (and `break`/`continue`), the keywords with
  23662. // optional arguments, we eagerly look for a semicolon or the
  23663. // possibility to insert one.
  23664. if (this.eat(types$2.semi) || this.insertSemicolon()) { node.argument = null; }
  23665. else { node.argument = this.parseExpression(); this.semicolon(); }
  23666. return this.finishNode(node, "ReturnStatement")
  23667. };
  23668. pp$1.parseSwitchStatement = function(node) {
  23669. this.next();
  23670. node.discriminant = this.parseParenExpression();
  23671. node.cases = [];
  23672. this.expect(types$2.braceL);
  23673. this.labels.push(switchLabel);
  23674. this.enterScope(0);
  23675. // Statements under must be grouped (by label) in SwitchCase
  23676. // nodes. `cur` is used to keep the node that we are currently
  23677. // adding statements to.
  23678. var cur;
  23679. for (var sawDefault = false; this.type !== types$2.braceR;) {
  23680. if (this.type === types$2._case || this.type === types$2._default) {
  23681. var isCase = this.type === types$2._case;
  23682. if (cur) { this.finishNode(cur, "SwitchCase"); }
  23683. node.cases.push(cur = this.startNode());
  23684. cur.consequent = [];
  23685. this.next();
  23686. if (isCase) {
  23687. cur.test = this.parseExpression();
  23688. } else {
  23689. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  23690. sawDefault = true;
  23691. cur.test = null;
  23692. }
  23693. this.expect(types$2.colon);
  23694. } else {
  23695. if (!cur) { this.unexpected(); }
  23696. cur.consequent.push(this.parseStatement(null));
  23697. }
  23698. }
  23699. this.exitScope();
  23700. if (cur) { this.finishNode(cur, "SwitchCase"); }
  23701. this.next(); // Closing brace
  23702. this.labels.pop();
  23703. return this.finishNode(node, "SwitchStatement")
  23704. };
  23705. pp$1.parseThrowStatement = function(node) {
  23706. this.next();
  23707. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  23708. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  23709. node.argument = this.parseExpression();
  23710. this.semicolon();
  23711. return this.finishNode(node, "ThrowStatement")
  23712. };
  23713. // Reused empty array added for node fields that are always empty.
  23714. var empty = [];
  23715. pp$1.parseTryStatement = function(node) {
  23716. this.next();
  23717. node.block = this.parseBlock();
  23718. node.handler = null;
  23719. if (this.type === types$2._catch) {
  23720. var clause = this.startNode();
  23721. this.next();
  23722. if (this.eat(types$2.parenL)) {
  23723. clause.param = this.parseBindingAtom();
  23724. var simple = clause.param.type === "Identifier";
  23725. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  23726. this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  23727. this.expect(types$2.parenR);
  23728. } else {
  23729. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  23730. clause.param = null;
  23731. this.enterScope(0);
  23732. }
  23733. clause.body = this.parseBlock(false);
  23734. this.exitScope();
  23735. node.handler = this.finishNode(clause, "CatchClause");
  23736. }
  23737. node.finalizer = this.eat(types$2._finally) ? this.parseBlock() : null;
  23738. if (!node.handler && !node.finalizer)
  23739. { this.raise(node.start, "Missing catch or finally clause"); }
  23740. return this.finishNode(node, "TryStatement")
  23741. };
  23742. pp$1.parseVarStatement = function(node, kind) {
  23743. this.next();
  23744. this.parseVar(node, false, kind);
  23745. this.semicolon();
  23746. return this.finishNode(node, "VariableDeclaration")
  23747. };
  23748. pp$1.parseWhileStatement = function(node) {
  23749. this.next();
  23750. node.test = this.parseParenExpression();
  23751. this.labels.push(loopLabel);
  23752. node.body = this.parseStatement("while");
  23753. this.labels.pop();
  23754. return this.finishNode(node, "WhileStatement")
  23755. };
  23756. pp$1.parseWithStatement = function(node) {
  23757. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  23758. this.next();
  23759. node.object = this.parseParenExpression();
  23760. node.body = this.parseStatement("with");
  23761. return this.finishNode(node, "WithStatement")
  23762. };
  23763. pp$1.parseEmptyStatement = function(node) {
  23764. this.next();
  23765. return this.finishNode(node, "EmptyStatement")
  23766. };
  23767. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  23768. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  23769. {
  23770. var label = list[i$1];
  23771. if (label.name === maybeName)
  23772. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  23773. } }
  23774. var kind = this.type.isLoop ? "loop" : this.type === types$2._switch ? "switch" : null;
  23775. for (var i = this.labels.length - 1; i >= 0; i--) {
  23776. var label$1 = this.labels[i];
  23777. if (label$1.statementStart === node.start) {
  23778. // Update information about previous labels on this node
  23779. label$1.statementStart = this.start;
  23780. label$1.kind = kind;
  23781. } else { break }
  23782. }
  23783. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  23784. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  23785. this.labels.pop();
  23786. node.label = expr;
  23787. return this.finishNode(node, "LabeledStatement")
  23788. };
  23789. pp$1.parseExpressionStatement = function(node, expr) {
  23790. node.expression = expr;
  23791. this.semicolon();
  23792. return this.finishNode(node, "ExpressionStatement")
  23793. };
  23794. // Parse a semicolon-enclosed block of statements, handling `"use
  23795. // strict"` declarations when `allowStrict` is true (used for
  23796. // function bodies).
  23797. pp$1.parseBlock = function(createNewLexicalScope, node) {
  23798. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  23799. if ( node === void 0 ) node = this.startNode();
  23800. node.body = [];
  23801. this.expect(types$2.braceL);
  23802. if (createNewLexicalScope) { this.enterScope(0); }
  23803. while (!this.eat(types$2.braceR)) {
  23804. var stmt = this.parseStatement(null);
  23805. node.body.push(stmt);
  23806. }
  23807. if (createNewLexicalScope) { this.exitScope(); }
  23808. return this.finishNode(node, "BlockStatement")
  23809. };
  23810. // Parse a regular `for` loop. The disambiguation code in
  23811. // `parseStatement` will already have parsed the init statement or
  23812. // expression.
  23813. pp$1.parseFor = function(node, init) {
  23814. node.init = init;
  23815. this.expect(types$2.semi);
  23816. node.test = this.type === types$2.semi ? null : this.parseExpression();
  23817. this.expect(types$2.semi);
  23818. node.update = this.type === types$2.parenR ? null : this.parseExpression();
  23819. this.expect(types$2.parenR);
  23820. node.body = this.parseStatement("for");
  23821. this.exitScope();
  23822. this.labels.pop();
  23823. return this.finishNode(node, "ForStatement")
  23824. };
  23825. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  23826. // same from parser's perspective.
  23827. pp$1.parseForIn = function(node, init) {
  23828. var isForIn = this.type === types$2._in;
  23829. this.next();
  23830. if (
  23831. init.type === "VariableDeclaration" &&
  23832. init.declarations[0].init != null &&
  23833. (
  23834. !isForIn ||
  23835. this.options.ecmaVersion < 8 ||
  23836. this.strict ||
  23837. init.kind !== "var" ||
  23838. init.declarations[0].id.type !== "Identifier"
  23839. )
  23840. ) {
  23841. this.raise(
  23842. init.start,
  23843. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  23844. );
  23845. } else if (init.type === "AssignmentPattern") {
  23846. this.raise(init.start, "Invalid left-hand side in for-loop");
  23847. }
  23848. node.left = init;
  23849. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  23850. this.expect(types$2.parenR);
  23851. node.body = this.parseStatement("for");
  23852. this.exitScope();
  23853. this.labels.pop();
  23854. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  23855. };
  23856. // Parse a list of variable declarations.
  23857. pp$1.parseVar = function(node, isFor, kind) {
  23858. node.declarations = [];
  23859. node.kind = kind;
  23860. for (;;) {
  23861. var decl = this.startNode();
  23862. this.parseVarId(decl, kind);
  23863. if (this.eat(types$2.eq)) {
  23864. decl.init = this.parseMaybeAssign(isFor);
  23865. } else if (kind === "const" && !(this.type === types$2._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  23866. this.unexpected();
  23867. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$2._in || this.isContextual("of")))) {
  23868. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  23869. } else {
  23870. decl.init = null;
  23871. }
  23872. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  23873. if (!this.eat(types$2.comma)) { break }
  23874. }
  23875. return node
  23876. };
  23877. pp$1.parseVarId = function(decl, kind) {
  23878. decl.id = this.parseBindingAtom();
  23879. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  23880. };
  23881. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  23882. // Parse a function declaration or literal (depending on the
  23883. // `statement & FUNC_STATEMENT`).
  23884. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  23885. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  23886. this.initFunction(node);
  23887. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  23888. if (this.type === types$2.star && (statement & FUNC_HANGING_STATEMENT))
  23889. { this.unexpected(); }
  23890. node.generator = this.eat(types$2.star);
  23891. }
  23892. if (this.options.ecmaVersion >= 8)
  23893. { node.async = !!isAsync; }
  23894. if (statement & FUNC_STATEMENT) {
  23895. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$2.name ? null : this.parseIdent();
  23896. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  23897. // If it is a regular function declaration in sloppy mode, then it is
  23898. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  23899. // mode depends on properties of the current scope (see
  23900. // treatFunctionsAsVar).
  23901. { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  23902. }
  23903. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  23904. this.yieldPos = 0;
  23905. this.awaitPos = 0;
  23906. this.awaitIdentPos = 0;
  23907. this.enterScope(functionFlags(node.async, node.generator));
  23908. if (!(statement & FUNC_STATEMENT))
  23909. { node.id = this.type === types$2.name ? this.parseIdent() : null; }
  23910. this.parseFunctionParams(node);
  23911. this.parseFunctionBody(node, allowExpressionBody, false);
  23912. this.yieldPos = oldYieldPos;
  23913. this.awaitPos = oldAwaitPos;
  23914. this.awaitIdentPos = oldAwaitIdentPos;
  23915. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  23916. };
  23917. pp$1.parseFunctionParams = function(node) {
  23918. this.expect(types$2.parenL);
  23919. node.params = this.parseBindingList(types$2.parenR, false, this.options.ecmaVersion >= 8);
  23920. this.checkYieldAwaitInDefaultParams();
  23921. };
  23922. // Parse a class declaration or literal (depending on the
  23923. // `isStatement` parameter).
  23924. pp$1.parseClass = function(node, isStatement) {
  23925. this.next();
  23926. // ecma-262 14.6 Class Definitions
  23927. // A class definition is always strict mode code.
  23928. var oldStrict = this.strict;
  23929. this.strict = true;
  23930. this.parseClassId(node, isStatement);
  23931. this.parseClassSuper(node);
  23932. var classBody = this.startNode();
  23933. var hadConstructor = false;
  23934. classBody.body = [];
  23935. this.expect(types$2.braceL);
  23936. while (!this.eat(types$2.braceR)) {
  23937. var element = this.parseClassElement(node.superClass !== null);
  23938. if (element) {
  23939. classBody.body.push(element);
  23940. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  23941. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  23942. hadConstructor = true;
  23943. }
  23944. }
  23945. }
  23946. node.body = this.finishNode(classBody, "ClassBody");
  23947. this.strict = oldStrict;
  23948. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  23949. };
  23950. pp$1.parseClassElement = function(constructorAllowsSuper) {
  23951. var this$1 = this;
  23952. if (this.eat(types$2.semi)) { return null }
  23953. var method = this.startNode();
  23954. var tryContextual = function (k, noLineBreak) {
  23955. if ( noLineBreak === void 0 ) noLineBreak = false;
  23956. var start = this$1.start, startLoc = this$1.startLoc;
  23957. if (!this$1.eatContextual(k)) { return false }
  23958. if (this$1.type !== types$2.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
  23959. if (method.key) { this$1.unexpected(); }
  23960. method.computed = false;
  23961. method.key = this$1.startNodeAt(start, startLoc);
  23962. method.key.name = k;
  23963. this$1.finishNode(method.key, "Identifier");
  23964. return false
  23965. };
  23966. method.kind = "method";
  23967. method.static = tryContextual("static");
  23968. var isGenerator = this.eat(types$2.star);
  23969. var isAsync = false;
  23970. if (!isGenerator) {
  23971. if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
  23972. isAsync = true;
  23973. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$2.star);
  23974. } else if (tryContextual("get")) {
  23975. method.kind = "get";
  23976. } else if (tryContextual("set")) {
  23977. method.kind = "set";
  23978. }
  23979. }
  23980. if (!method.key) { this.parsePropertyName(method); }
  23981. var key = method.key;
  23982. var allowsDirectSuper = false;
  23983. if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
  23984. key.type === "Literal" && key.value === "constructor")) {
  23985. if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
  23986. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  23987. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  23988. method.kind = "constructor";
  23989. allowsDirectSuper = constructorAllowsSuper;
  23990. } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
  23991. this.raise(key.start, "Classes may not have a static property named prototype");
  23992. }
  23993. this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
  23994. if (method.kind === "get" && method.value.params.length !== 0)
  23995. { this.raiseRecoverable(method.value.start, "getter should have no params"); }
  23996. if (method.kind === "set" && method.value.params.length !== 1)
  23997. { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
  23998. if (method.kind === "set" && method.value.params[0].type === "RestElement")
  23999. { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
  24000. return method
  24001. };
  24002. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  24003. method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  24004. return this.finishNode(method, "MethodDefinition")
  24005. };
  24006. pp$1.parseClassId = function(node, isStatement) {
  24007. if (this.type === types$2.name) {
  24008. node.id = this.parseIdent();
  24009. if (isStatement)
  24010. { this.checkLVal(node.id, BIND_LEXICAL, false); }
  24011. } else {
  24012. if (isStatement === true)
  24013. { this.unexpected(); }
  24014. node.id = null;
  24015. }
  24016. };
  24017. pp$1.parseClassSuper = function(node) {
  24018. node.superClass = this.eat(types$2._extends) ? this.parseExprSubscripts() : null;
  24019. };
  24020. // Parses module export declaration.
  24021. pp$1.parseExport = function(node, exports) {
  24022. this.next();
  24023. // export * from '...'
  24024. if (this.eat(types$2.star)) {
  24025. this.expectContextual("from");
  24026. if (this.type !== types$2.string) { this.unexpected(); }
  24027. node.source = this.parseExprAtom();
  24028. this.semicolon();
  24029. return this.finishNode(node, "ExportAllDeclaration")
  24030. }
  24031. if (this.eat(types$2._default)) { // export default ...
  24032. this.checkExport(exports, "default", this.lastTokStart);
  24033. var isAsync;
  24034. if (this.type === types$2._function || (isAsync = this.isAsyncFunction())) {
  24035. var fNode = this.startNode();
  24036. this.next();
  24037. if (isAsync) { this.next(); }
  24038. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  24039. } else if (this.type === types$2._class) {
  24040. var cNode = this.startNode();
  24041. node.declaration = this.parseClass(cNode, "nullableID");
  24042. } else {
  24043. node.declaration = this.parseMaybeAssign();
  24044. this.semicolon();
  24045. }
  24046. return this.finishNode(node, "ExportDefaultDeclaration")
  24047. }
  24048. // export var|const|let|function|class ...
  24049. if (this.shouldParseExportStatement()) {
  24050. node.declaration = this.parseStatement(null);
  24051. if (node.declaration.type === "VariableDeclaration")
  24052. { this.checkVariableExport(exports, node.declaration.declarations); }
  24053. else
  24054. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  24055. node.specifiers = [];
  24056. node.source = null;
  24057. } else { // export { x, y as z } [from '...']
  24058. node.declaration = null;
  24059. node.specifiers = this.parseExportSpecifiers(exports);
  24060. if (this.eatContextual("from")) {
  24061. if (this.type !== types$2.string) { this.unexpected(); }
  24062. node.source = this.parseExprAtom();
  24063. } else {
  24064. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  24065. // check for keywords used as local names
  24066. var spec = list[i];
  24067. this.checkUnreserved(spec.local);
  24068. // check if export is defined
  24069. this.checkLocalExport(spec.local);
  24070. }
  24071. node.source = null;
  24072. }
  24073. this.semicolon();
  24074. }
  24075. return this.finishNode(node, "ExportNamedDeclaration")
  24076. };
  24077. pp$1.checkExport = function(exports, name, pos) {
  24078. if (!exports) { return }
  24079. if (has$1(exports, name))
  24080. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  24081. exports[name] = true;
  24082. };
  24083. pp$1.checkPatternExport = function(exports, pat) {
  24084. var type = pat.type;
  24085. if (type === "Identifier")
  24086. { this.checkExport(exports, pat.name, pat.start); }
  24087. else if (type === "ObjectPattern")
  24088. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  24089. {
  24090. var prop = list[i];
  24091. this.checkPatternExport(exports, prop);
  24092. } }
  24093. else if (type === "ArrayPattern")
  24094. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  24095. var elt = list$1[i$1];
  24096. if (elt) { this.checkPatternExport(exports, elt); }
  24097. } }
  24098. else if (type === "Property")
  24099. { this.checkPatternExport(exports, pat.value); }
  24100. else if (type === "AssignmentPattern")
  24101. { this.checkPatternExport(exports, pat.left); }
  24102. else if (type === "RestElement")
  24103. { this.checkPatternExport(exports, pat.argument); }
  24104. else if (type === "ParenthesizedExpression")
  24105. { this.checkPatternExport(exports, pat.expression); }
  24106. };
  24107. pp$1.checkVariableExport = function(exports, decls) {
  24108. if (!exports) { return }
  24109. for (var i = 0, list = decls; i < list.length; i += 1)
  24110. {
  24111. var decl = list[i];
  24112. this.checkPatternExport(exports, decl.id);
  24113. }
  24114. };
  24115. pp$1.shouldParseExportStatement = function() {
  24116. return this.type.keyword === "var" ||
  24117. this.type.keyword === "const" ||
  24118. this.type.keyword === "class" ||
  24119. this.type.keyword === "function" ||
  24120. this.isLet() ||
  24121. this.isAsyncFunction()
  24122. };
  24123. // Parses a comma-separated list of module exports.
  24124. pp$1.parseExportSpecifiers = function(exports) {
  24125. var nodes = [], first = true;
  24126. // export { x, y as z } [from '...']
  24127. this.expect(types$2.braceL);
  24128. while (!this.eat(types$2.braceR)) {
  24129. if (!first) {
  24130. this.expect(types$2.comma);
  24131. if (this.afterTrailingComma(types$2.braceR)) { break }
  24132. } else { first = false; }
  24133. var node = this.startNode();
  24134. node.local = this.parseIdent(true);
  24135. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  24136. this.checkExport(exports, node.exported.name, node.exported.start);
  24137. nodes.push(this.finishNode(node, "ExportSpecifier"));
  24138. }
  24139. return nodes
  24140. };
  24141. // Parses import declaration.
  24142. pp$1.parseImport = function(node) {
  24143. this.next();
  24144. // import '...'
  24145. if (this.type === types$2.string) {
  24146. node.specifiers = empty;
  24147. node.source = this.parseExprAtom();
  24148. } else {
  24149. node.specifiers = this.parseImportSpecifiers();
  24150. this.expectContextual("from");
  24151. node.source = this.type === types$2.string ? this.parseExprAtom() : this.unexpected();
  24152. }
  24153. this.semicolon();
  24154. return this.finishNode(node, "ImportDeclaration")
  24155. };
  24156. // Parses a comma-separated list of module imports.
  24157. pp$1.parseImportSpecifiers = function() {
  24158. var nodes = [], first = true;
  24159. if (this.type === types$2.name) {
  24160. // import defaultObj, { x, y as z } from '...'
  24161. var node = this.startNode();
  24162. node.local = this.parseIdent();
  24163. this.checkLVal(node.local, BIND_LEXICAL);
  24164. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  24165. if (!this.eat(types$2.comma)) { return nodes }
  24166. }
  24167. if (this.type === types$2.star) {
  24168. var node$1 = this.startNode();
  24169. this.next();
  24170. this.expectContextual("as");
  24171. node$1.local = this.parseIdent();
  24172. this.checkLVal(node$1.local, BIND_LEXICAL);
  24173. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  24174. return nodes
  24175. }
  24176. this.expect(types$2.braceL);
  24177. while (!this.eat(types$2.braceR)) {
  24178. if (!first) {
  24179. this.expect(types$2.comma);
  24180. if (this.afterTrailingComma(types$2.braceR)) { break }
  24181. } else { first = false; }
  24182. var node$2 = this.startNode();
  24183. node$2.imported = this.parseIdent(true);
  24184. if (this.eatContextual("as")) {
  24185. node$2.local = this.parseIdent();
  24186. } else {
  24187. this.checkUnreserved(node$2.imported);
  24188. node$2.local = node$2.imported;
  24189. }
  24190. this.checkLVal(node$2.local, BIND_LEXICAL);
  24191. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  24192. }
  24193. return nodes
  24194. };
  24195. // Set `ExpressionStatement#directive` property for directive prologues.
  24196. pp$1.adaptDirectivePrologue = function(statements) {
  24197. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  24198. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  24199. }
  24200. };
  24201. pp$1.isDirectiveCandidate = function(statement) {
  24202. return (
  24203. statement.type === "ExpressionStatement" &&
  24204. statement.expression.type === "Literal" &&
  24205. typeof statement.expression.value === "string" &&
  24206. // Reject parenthesized strings.
  24207. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  24208. )
  24209. };
  24210. var pp$2 = Parser.prototype;
  24211. // Convert existing expression atom to assignable pattern
  24212. // if possible.
  24213. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  24214. if (this.options.ecmaVersion >= 6 && node) {
  24215. switch (node.type) {
  24216. case "Identifier":
  24217. if (this.inAsync && node.name === "await")
  24218. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  24219. break
  24220. case "ObjectPattern":
  24221. case "ArrayPattern":
  24222. case "RestElement":
  24223. break
  24224. case "ObjectExpression":
  24225. node.type = "ObjectPattern";
  24226. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  24227. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  24228. var prop = list[i];
  24229. this.toAssignable(prop, isBinding);
  24230. // Early error:
  24231. // AssignmentRestProperty[Yield, Await] :
  24232. // `...` DestructuringAssignmentTarget[Yield, Await]
  24233. //
  24234. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  24235. if (
  24236. prop.type === "RestElement" &&
  24237. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  24238. ) {
  24239. this.raise(prop.argument.start, "Unexpected token");
  24240. }
  24241. }
  24242. break
  24243. case "Property":
  24244. // AssignmentProperty has type === "Property"
  24245. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  24246. this.toAssignable(node.value, isBinding);
  24247. break
  24248. case "ArrayExpression":
  24249. node.type = "ArrayPattern";
  24250. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  24251. this.toAssignableList(node.elements, isBinding);
  24252. break
  24253. case "SpreadElement":
  24254. node.type = "RestElement";
  24255. this.toAssignable(node.argument, isBinding);
  24256. if (node.argument.type === "AssignmentPattern")
  24257. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  24258. break
  24259. case "AssignmentExpression":
  24260. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  24261. node.type = "AssignmentPattern";
  24262. delete node.operator;
  24263. this.toAssignable(node.left, isBinding);
  24264. // falls through to AssignmentPattern
  24265. case "AssignmentPattern":
  24266. break
  24267. case "ParenthesizedExpression":
  24268. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  24269. break
  24270. case "MemberExpression":
  24271. if (!isBinding) { break }
  24272. default:
  24273. this.raise(node.start, "Assigning to rvalue");
  24274. }
  24275. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  24276. return node
  24277. };
  24278. // Convert list of expression atoms to binding list.
  24279. pp$2.toAssignableList = function(exprList, isBinding) {
  24280. var end = exprList.length;
  24281. for (var i = 0; i < end; i++) {
  24282. var elt = exprList[i];
  24283. if (elt) { this.toAssignable(elt, isBinding); }
  24284. }
  24285. if (end) {
  24286. var last = exprList[end - 1];
  24287. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  24288. { this.unexpected(last.argument.start); }
  24289. }
  24290. return exprList
  24291. };
  24292. // Parses spread element.
  24293. pp$2.parseSpread = function(refDestructuringErrors) {
  24294. var node = this.startNode();
  24295. this.next();
  24296. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  24297. return this.finishNode(node, "SpreadElement")
  24298. };
  24299. pp$2.parseRestBinding = function() {
  24300. var node = this.startNode();
  24301. this.next();
  24302. // RestElement inside of a function parameter must be an identifier
  24303. if (this.options.ecmaVersion === 6 && this.type !== types$2.name)
  24304. { this.unexpected(); }
  24305. node.argument = this.parseBindingAtom();
  24306. return this.finishNode(node, "RestElement")
  24307. };
  24308. // Parses lvalue (assignable) atom.
  24309. pp$2.parseBindingAtom = function() {
  24310. if (this.options.ecmaVersion >= 6) {
  24311. switch (this.type) {
  24312. case types$2.bracketL:
  24313. var node = this.startNode();
  24314. this.next();
  24315. node.elements = this.parseBindingList(types$2.bracketR, true, true);
  24316. return this.finishNode(node, "ArrayPattern")
  24317. case types$2.braceL:
  24318. return this.parseObj(true)
  24319. }
  24320. }
  24321. return this.parseIdent()
  24322. };
  24323. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  24324. var elts = [], first = true;
  24325. while (!this.eat(close)) {
  24326. if (first) { first = false; }
  24327. else { this.expect(types$2.comma); }
  24328. if (allowEmpty && this.type === types$2.comma) {
  24329. elts.push(null);
  24330. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  24331. break
  24332. } else if (this.type === types$2.ellipsis) {
  24333. var rest = this.parseRestBinding();
  24334. this.parseBindingListItem(rest);
  24335. elts.push(rest);
  24336. if (this.type === types$2.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  24337. this.expect(close);
  24338. break
  24339. } else {
  24340. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  24341. this.parseBindingListItem(elem);
  24342. elts.push(elem);
  24343. }
  24344. }
  24345. return elts
  24346. };
  24347. pp$2.parseBindingListItem = function(param) {
  24348. return param
  24349. };
  24350. // Parses assignment pattern around given atom if possible.
  24351. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  24352. left = left || this.parseBindingAtom();
  24353. if (this.options.ecmaVersion < 6 || !this.eat(types$2.eq)) { return left }
  24354. var node = this.startNodeAt(startPos, startLoc);
  24355. node.left = left;
  24356. node.right = this.parseMaybeAssign();
  24357. return this.finishNode(node, "AssignmentPattern")
  24358. };
  24359. // Verify that a node is an lval — something that can be assigned
  24360. // to.
  24361. // bindingType can be either:
  24362. // 'var' indicating that the lval creates a 'var' binding
  24363. // 'let' indicating that the lval creates a lexical ('let' or 'const') binding
  24364. // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
  24365. pp$2.checkLVal = function(expr, bindingType, checkClashes) {
  24366. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  24367. switch (expr.type) {
  24368. case "Identifier":
  24369. if (bindingType === BIND_LEXICAL && expr.name === "let")
  24370. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  24371. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  24372. { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  24373. if (checkClashes) {
  24374. if (has$1(checkClashes, expr.name))
  24375. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  24376. checkClashes[expr.name] = true;
  24377. }
  24378. if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  24379. break
  24380. case "MemberExpression":
  24381. if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  24382. break
  24383. case "ObjectPattern":
  24384. for (var i = 0, list = expr.properties; i < list.length; i += 1)
  24385. {
  24386. var prop = list[i];
  24387. this.checkLVal(prop, bindingType, checkClashes);
  24388. }
  24389. break
  24390. case "Property":
  24391. // AssignmentProperty has type === "Property"
  24392. this.checkLVal(expr.value, bindingType, checkClashes);
  24393. break
  24394. case "ArrayPattern":
  24395. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  24396. var elem = list$1[i$1];
  24397. if (elem) { this.checkLVal(elem, bindingType, checkClashes); }
  24398. }
  24399. break
  24400. case "AssignmentPattern":
  24401. this.checkLVal(expr.left, bindingType, checkClashes);
  24402. break
  24403. case "RestElement":
  24404. this.checkLVal(expr.argument, bindingType, checkClashes);
  24405. break
  24406. case "ParenthesizedExpression":
  24407. this.checkLVal(expr.expression, bindingType, checkClashes);
  24408. break
  24409. default:
  24410. this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
  24411. }
  24412. };
  24413. // A recursive descent parser operates by defining functions for all
  24414. var pp$3 = Parser.prototype;
  24415. // Check if property name clashes with already added.
  24416. // Object/class getters and setters are not allowed to clash —
  24417. // either with each other or with an init property — and in
  24418. // strict mode, init properties are also not allowed to be repeated.
  24419. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  24420. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  24421. { return }
  24422. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  24423. { return }
  24424. var key = prop.key;
  24425. var name;
  24426. switch (key.type) {
  24427. case "Identifier": name = key.name; break
  24428. case "Literal": name = String(key.value); break
  24429. default: return
  24430. }
  24431. var kind = prop.kind;
  24432. if (this.options.ecmaVersion >= 6) {
  24433. if (name === "__proto__" && kind === "init") {
  24434. if (propHash.proto) {
  24435. if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; }
  24436. // Backwards-compat kludge. Can be removed in version 6.0
  24437. else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  24438. }
  24439. propHash.proto = true;
  24440. }
  24441. return
  24442. }
  24443. name = "$" + name;
  24444. var other = propHash[name];
  24445. if (other) {
  24446. var redefinition;
  24447. if (kind === "init") {
  24448. redefinition = this.strict && other.init || other.get || other.set;
  24449. } else {
  24450. redefinition = other.init || other[kind];
  24451. }
  24452. if (redefinition)
  24453. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  24454. } else {
  24455. other = propHash[name] = {
  24456. init: false,
  24457. get: false,
  24458. set: false
  24459. };
  24460. }
  24461. other[kind] = true;
  24462. };
  24463. // ### Expression parsing
  24464. // These nest, from the most general expression type at the top to
  24465. // 'atomic', nondivisible expression types at the bottom. Most of
  24466. // the functions will simply let the function(s) below them parse,
  24467. // and, *if* the syntactic construct they handle is present, wrap
  24468. // the AST node that the inner parser gave them in another node.
  24469. // Parse a full expression. The optional arguments are used to
  24470. // forbid the `in` operator (in for loops initalization expressions)
  24471. // and provide reference for storing '=' operator inside shorthand
  24472. // property assignment in contexts where both object expression
  24473. // and object pattern might appear (so it's possible to raise
  24474. // delayed syntax error at correct position).
  24475. pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  24476. var startPos = this.start, startLoc = this.startLoc;
  24477. var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  24478. if (this.type === types$2.comma) {
  24479. var node = this.startNodeAt(startPos, startLoc);
  24480. node.expressions = [expr];
  24481. while (this.eat(types$2.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
  24482. return this.finishNode(node, "SequenceExpression")
  24483. }
  24484. return expr
  24485. };
  24486. // Parse an assignment expression. This includes applications of
  24487. // operators like `+=`.
  24488. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  24489. if (this.isContextual("yield")) {
  24490. if (this.inGenerator) { return this.parseYield(noIn) }
  24491. // The tokenizer will assume an expression is allowed after
  24492. // `yield`, but this isn't that kind of yield
  24493. else { this.exprAllowed = false; }
  24494. }
  24495. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1;
  24496. if (refDestructuringErrors) {
  24497. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  24498. oldTrailingComma = refDestructuringErrors.trailingComma;
  24499. oldShorthandAssign = refDestructuringErrors.shorthandAssign;
  24500. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1;
  24501. } else {
  24502. refDestructuringErrors = new DestructuringErrors;
  24503. ownDestructuringErrors = true;
  24504. }
  24505. var startPos = this.start, startLoc = this.startLoc;
  24506. if (this.type === types$2.parenL || this.type === types$2.name)
  24507. { this.potentialArrowAt = this.start; }
  24508. var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  24509. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  24510. if (this.type.isAssign) {
  24511. var node = this.startNodeAt(startPos, startLoc);
  24512. node.operator = this.value;
  24513. node.left = this.type === types$2.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
  24514. if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
  24515. refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
  24516. this.checkLVal(left);
  24517. this.next();
  24518. node.right = this.parseMaybeAssign(noIn);
  24519. return this.finishNode(node, "AssignmentExpression")
  24520. } else {
  24521. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  24522. }
  24523. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  24524. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  24525. if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; }
  24526. return left
  24527. };
  24528. // Parse a ternary conditional (`?:`) operator.
  24529. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  24530. var startPos = this.start, startLoc = this.startLoc;
  24531. var expr = this.parseExprOps(noIn, refDestructuringErrors);
  24532. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  24533. if (this.eat(types$2.question)) {
  24534. var node = this.startNodeAt(startPos, startLoc);
  24535. node.test = expr;
  24536. node.consequent = this.parseMaybeAssign();
  24537. this.expect(types$2.colon);
  24538. node.alternate = this.parseMaybeAssign(noIn);
  24539. return this.finishNode(node, "ConditionalExpression")
  24540. }
  24541. return expr
  24542. };
  24543. // Start the precedence parser.
  24544. pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  24545. var startPos = this.start, startLoc = this.startLoc;
  24546. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  24547. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  24548. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  24549. };
  24550. // Parse binary operators with the operator precedence parsing
  24551. // algorithm. `left` is the left-hand side of the operator.
  24552. // `minPrec` provides context that allows the function to stop and
  24553. // defer further parser to one of its callers when it encounters an
  24554. // operator that has a lower precedence than the set it is parsing.
  24555. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  24556. var prec = this.type.binop;
  24557. if (prec != null && (!noIn || this.type !== types$2._in)) {
  24558. if (prec > minPrec) {
  24559. var logical = this.type === types$2.logicalOR || this.type === types$2.logicalAND;
  24560. var op = this.value;
  24561. this.next();
  24562. var startPos = this.start, startLoc = this.startLoc;
  24563. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
  24564. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
  24565. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  24566. }
  24567. }
  24568. return left
  24569. };
  24570. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  24571. var node = this.startNodeAt(startPos, startLoc);
  24572. node.left = left;
  24573. node.operator = op;
  24574. node.right = right;
  24575. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  24576. };
  24577. // Parse unary operators, both prefix and postfix.
  24578. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  24579. var startPos = this.start, startLoc = this.startLoc, expr;
  24580. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  24581. expr = this.parseAwait();
  24582. sawUnary = true;
  24583. } else if (this.type.prefix) {
  24584. var node = this.startNode(), update = this.type === types$2.incDec;
  24585. node.operator = this.value;
  24586. node.prefix = true;
  24587. this.next();
  24588. node.argument = this.parseMaybeUnary(null, true);
  24589. this.checkExpressionErrors(refDestructuringErrors, true);
  24590. if (update) { this.checkLVal(node.argument); }
  24591. else if (this.strict && node.operator === "delete" &&
  24592. node.argument.type === "Identifier")
  24593. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  24594. else { sawUnary = true; }
  24595. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  24596. } else {
  24597. expr = this.parseExprSubscripts(refDestructuringErrors);
  24598. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  24599. while (this.type.postfix && !this.canInsertSemicolon()) {
  24600. var node$1 = this.startNodeAt(startPos, startLoc);
  24601. node$1.operator = this.value;
  24602. node$1.prefix = false;
  24603. node$1.argument = expr;
  24604. this.checkLVal(expr);
  24605. this.next();
  24606. expr = this.finishNode(node$1, "UpdateExpression");
  24607. }
  24608. }
  24609. if (!sawUnary && this.eat(types$2.starstar))
  24610. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  24611. else
  24612. { return expr }
  24613. };
  24614. // Parse call, dot, and `[]`-subscript expressions.
  24615. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  24616. var startPos = this.start, startLoc = this.startLoc;
  24617. var expr = this.parseExprAtom(refDestructuringErrors);
  24618. var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
  24619. if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
  24620. var result = this.parseSubscripts(expr, startPos, startLoc);
  24621. if (refDestructuringErrors && result.type === "MemberExpression") {
  24622. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  24623. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  24624. }
  24625. return result
  24626. };
  24627. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  24628. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  24629. this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
  24630. while (true) {
  24631. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow);
  24632. if (element === base || element.type === "ArrowFunctionExpression") { return element }
  24633. base = element;
  24634. }
  24635. };
  24636. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) {
  24637. var computed = this.eat(types$2.bracketL);
  24638. if (computed || this.eat(types$2.dot)) {
  24639. var node = this.startNodeAt(startPos, startLoc);
  24640. node.object = base;
  24641. node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
  24642. node.computed = !!computed;
  24643. if (computed) { this.expect(types$2.bracketR); }
  24644. base = this.finishNode(node, "MemberExpression");
  24645. } else if (!noCalls && this.eat(types$2.parenL)) {
  24646. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  24647. this.yieldPos = 0;
  24648. this.awaitPos = 0;
  24649. this.awaitIdentPos = 0;
  24650. var exprList = this.parseExprList(types$2.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  24651. if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types$2.arrow)) {
  24652. this.checkPatternErrors(refDestructuringErrors, false);
  24653. this.checkYieldAwaitInDefaultParams();
  24654. if (this.awaitIdentPos > 0)
  24655. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  24656. this.yieldPos = oldYieldPos;
  24657. this.awaitPos = oldAwaitPos;
  24658. this.awaitIdentPos = oldAwaitIdentPos;
  24659. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  24660. }
  24661. this.checkExpressionErrors(refDestructuringErrors, true);
  24662. this.yieldPos = oldYieldPos || this.yieldPos;
  24663. this.awaitPos = oldAwaitPos || this.awaitPos;
  24664. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  24665. var node$1 = this.startNodeAt(startPos, startLoc);
  24666. node$1.callee = base;
  24667. node$1.arguments = exprList;
  24668. base = this.finishNode(node$1, "CallExpression");
  24669. } else if (this.type === types$2.backQuote) {
  24670. var node$2 = this.startNodeAt(startPos, startLoc);
  24671. node$2.tag = base;
  24672. node$2.quasi = this.parseTemplate({isTagged: true});
  24673. base = this.finishNode(node$2, "TaggedTemplateExpression");
  24674. }
  24675. return base
  24676. };
  24677. // Parse an atomic expression — either a single token that is an
  24678. // expression, an expression started by a keyword like `function` or
  24679. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  24680. // or `{}`.
  24681. pp$3.parseExprAtom = function(refDestructuringErrors) {
  24682. // If a division operator appears in an expression position, the
  24683. // tokenizer got confused, and we force it to read a regexp instead.
  24684. if (this.type === types$2.slash) { this.readRegexp(); }
  24685. var node, canBeArrow = this.potentialArrowAt === this.start;
  24686. switch (this.type) {
  24687. case types$2._super:
  24688. if (!this.allowSuper)
  24689. { this.raise(this.start, "'super' keyword outside a method"); }
  24690. node = this.startNode();
  24691. this.next();
  24692. if (this.type === types$2.parenL && !this.allowDirectSuper)
  24693. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  24694. // The `super` keyword can appear at below:
  24695. // SuperProperty:
  24696. // super [ Expression ]
  24697. // super . IdentifierName
  24698. // SuperCall:
  24699. // super ( Arguments )
  24700. if (this.type !== types$2.dot && this.type !== types$2.bracketL && this.type !== types$2.parenL)
  24701. { this.unexpected(); }
  24702. return this.finishNode(node, "Super")
  24703. case types$2._this:
  24704. node = this.startNode();
  24705. this.next();
  24706. return this.finishNode(node, "ThisExpression")
  24707. case types$2.name:
  24708. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  24709. var id = this.parseIdent(false);
  24710. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$2._function))
  24711. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  24712. if (canBeArrow && !this.canInsertSemicolon()) {
  24713. if (this.eat(types$2.arrow))
  24714. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  24715. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$2.name && !containsEsc) {
  24716. id = this.parseIdent(false);
  24717. if (this.canInsertSemicolon() || !this.eat(types$2.arrow))
  24718. { this.unexpected(); }
  24719. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  24720. }
  24721. }
  24722. return id
  24723. case types$2.regexp:
  24724. var value = this.value;
  24725. node = this.parseLiteral(value.value);
  24726. node.regex = {pattern: value.pattern, flags: value.flags};
  24727. return node
  24728. case types$2.num: case types$2.string:
  24729. return this.parseLiteral(this.value)
  24730. case types$2._null: case types$2._true: case types$2._false:
  24731. node = this.startNode();
  24732. node.value = this.type === types$2._null ? null : this.type === types$2._true;
  24733. node.raw = this.type.keyword;
  24734. this.next();
  24735. return this.finishNode(node, "Literal")
  24736. case types$2.parenL:
  24737. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  24738. if (refDestructuringErrors) {
  24739. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  24740. { refDestructuringErrors.parenthesizedAssign = start; }
  24741. if (refDestructuringErrors.parenthesizedBind < 0)
  24742. { refDestructuringErrors.parenthesizedBind = start; }
  24743. }
  24744. return expr
  24745. case types$2.bracketL:
  24746. node = this.startNode();
  24747. this.next();
  24748. node.elements = this.parseExprList(types$2.bracketR, true, true, refDestructuringErrors);
  24749. return this.finishNode(node, "ArrayExpression")
  24750. case types$2.braceL:
  24751. return this.parseObj(false, refDestructuringErrors)
  24752. case types$2._function:
  24753. node = this.startNode();
  24754. this.next();
  24755. return this.parseFunction(node, 0)
  24756. case types$2._class:
  24757. return this.parseClass(this.startNode(), false)
  24758. case types$2._new:
  24759. return this.parseNew()
  24760. case types$2.backQuote:
  24761. return this.parseTemplate()
  24762. case types$2._import:
  24763. if (this.options.ecmaVersion >= 11) {
  24764. return this.parseExprImport()
  24765. } else {
  24766. return this.unexpected()
  24767. }
  24768. default:
  24769. this.unexpected();
  24770. }
  24771. };
  24772. pp$3.parseExprImport = function() {
  24773. var node = this.startNode();
  24774. this.next(); // skip `import`
  24775. switch (this.type) {
  24776. case types$2.parenL:
  24777. return this.parseDynamicImport(node)
  24778. default:
  24779. this.unexpected();
  24780. }
  24781. };
  24782. pp$3.parseDynamicImport = function(node) {
  24783. this.next(); // skip `(`
  24784. // Parse node.source.
  24785. node.source = this.parseMaybeAssign();
  24786. // Verify ending.
  24787. if (!this.eat(types$2.parenR)) {
  24788. var errorPos = this.start;
  24789. if (this.eat(types$2.comma) && this.eat(types$2.parenR)) {
  24790. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  24791. } else {
  24792. this.unexpected(errorPos);
  24793. }
  24794. }
  24795. return this.finishNode(node, "ImportExpression")
  24796. };
  24797. pp$3.parseLiteral = function(value) {
  24798. var node = this.startNode();
  24799. node.value = value;
  24800. node.raw = this.input.slice(this.start, this.end);
  24801. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1); }
  24802. this.next();
  24803. return this.finishNode(node, "Literal")
  24804. };
  24805. pp$3.parseParenExpression = function() {
  24806. this.expect(types$2.parenL);
  24807. var val = this.parseExpression();
  24808. this.expect(types$2.parenR);
  24809. return val
  24810. };
  24811. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  24812. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  24813. if (this.options.ecmaVersion >= 6) {
  24814. this.next();
  24815. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  24816. var exprList = [], first = true, lastIsComma = false;
  24817. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  24818. this.yieldPos = 0;
  24819. this.awaitPos = 0;
  24820. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  24821. while (this.type !== types$2.parenR) {
  24822. first ? first = false : this.expect(types$2.comma);
  24823. if (allowTrailingComma && this.afterTrailingComma(types$2.parenR, true)) {
  24824. lastIsComma = true;
  24825. break
  24826. } else if (this.type === types$2.ellipsis) {
  24827. spreadStart = this.start;
  24828. exprList.push(this.parseParenItem(this.parseRestBinding()));
  24829. if (this.type === types$2.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  24830. break
  24831. } else {
  24832. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  24833. }
  24834. }
  24835. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  24836. this.expect(types$2.parenR);
  24837. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$2.arrow)) {
  24838. this.checkPatternErrors(refDestructuringErrors, false);
  24839. this.checkYieldAwaitInDefaultParams();
  24840. this.yieldPos = oldYieldPos;
  24841. this.awaitPos = oldAwaitPos;
  24842. return this.parseParenArrowList(startPos, startLoc, exprList)
  24843. }
  24844. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  24845. if (spreadStart) { this.unexpected(spreadStart); }
  24846. this.checkExpressionErrors(refDestructuringErrors, true);
  24847. this.yieldPos = oldYieldPos || this.yieldPos;
  24848. this.awaitPos = oldAwaitPos || this.awaitPos;
  24849. if (exprList.length > 1) {
  24850. val = this.startNodeAt(innerStartPos, innerStartLoc);
  24851. val.expressions = exprList;
  24852. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  24853. } else {
  24854. val = exprList[0];
  24855. }
  24856. } else {
  24857. val = this.parseParenExpression();
  24858. }
  24859. if (this.options.preserveParens) {
  24860. var par = this.startNodeAt(startPos, startLoc);
  24861. par.expression = val;
  24862. return this.finishNode(par, "ParenthesizedExpression")
  24863. } else {
  24864. return val
  24865. }
  24866. };
  24867. pp$3.parseParenItem = function(item) {
  24868. return item
  24869. };
  24870. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  24871. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  24872. };
  24873. // New's precedence is slightly tricky. It must allow its argument to
  24874. // be a `[]` or dot subscript expression, but not a call — at least,
  24875. // not without wrapping it in parentheses. Thus, it uses the noCalls
  24876. // argument to parseSubscripts to prevent it from consuming the
  24877. // argument list.
  24878. var empty$1 = [];
  24879. pp$3.parseNew = function() {
  24880. var node = this.startNode();
  24881. var meta = this.parseIdent(true);
  24882. if (this.options.ecmaVersion >= 6 && this.eat(types$2.dot)) {
  24883. node.meta = meta;
  24884. var containsEsc = this.containsEsc;
  24885. node.property = this.parseIdent(true);
  24886. if (node.property.name !== "target" || containsEsc)
  24887. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
  24888. if (!this.inNonArrowFunction())
  24889. { this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
  24890. return this.finishNode(node, "MetaProperty")
  24891. }
  24892. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$2._import;
  24893. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  24894. if (isImport && node.callee.type === "ImportExpression") {
  24895. this.raise(startPos, "Cannot use new with import()");
  24896. }
  24897. if (this.eat(types$2.parenL)) { node.arguments = this.parseExprList(types$2.parenR, this.options.ecmaVersion >= 8, false); }
  24898. else { node.arguments = empty$1; }
  24899. return this.finishNode(node, "NewExpression")
  24900. };
  24901. // Parse template expression.
  24902. pp$3.parseTemplateElement = function(ref) {
  24903. var isTagged = ref.isTagged;
  24904. var elem = this.startNode();
  24905. if (this.type === types$2.invalidTemplate) {
  24906. if (!isTagged) {
  24907. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  24908. }
  24909. elem.value = {
  24910. raw: this.value,
  24911. cooked: null
  24912. };
  24913. } else {
  24914. elem.value = {
  24915. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  24916. cooked: this.value
  24917. };
  24918. }
  24919. this.next();
  24920. elem.tail = this.type === types$2.backQuote;
  24921. return this.finishNode(elem, "TemplateElement")
  24922. };
  24923. pp$3.parseTemplate = function(ref) {
  24924. if ( ref === void 0 ) ref = {};
  24925. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  24926. var node = this.startNode();
  24927. this.next();
  24928. node.expressions = [];
  24929. var curElt = this.parseTemplateElement({isTagged: isTagged});
  24930. node.quasis = [curElt];
  24931. while (!curElt.tail) {
  24932. if (this.type === types$2.eof) { this.raise(this.pos, "Unterminated template literal"); }
  24933. this.expect(types$2.dollarBraceL);
  24934. node.expressions.push(this.parseExpression());
  24935. this.expect(types$2.braceR);
  24936. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  24937. }
  24938. this.next();
  24939. return this.finishNode(node, "TemplateLiteral")
  24940. };
  24941. pp$3.isAsyncProp = function(prop) {
  24942. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  24943. (this.type === types$2.name || this.type === types$2.num || this.type === types$2.string || this.type === types$2.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$2.star)) &&
  24944. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  24945. };
  24946. // Parse an object literal or binding pattern.
  24947. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  24948. var node = this.startNode(), first = true, propHash = {};
  24949. node.properties = [];
  24950. this.next();
  24951. while (!this.eat(types$2.braceR)) {
  24952. if (!first) {
  24953. this.expect(types$2.comma);
  24954. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$2.braceR)) { break }
  24955. } else { first = false; }
  24956. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  24957. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  24958. node.properties.push(prop);
  24959. }
  24960. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  24961. };
  24962. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  24963. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  24964. if (this.options.ecmaVersion >= 9 && this.eat(types$2.ellipsis)) {
  24965. if (isPattern) {
  24966. prop.argument = this.parseIdent(false);
  24967. if (this.type === types$2.comma) {
  24968. this.raise(this.start, "Comma is not permitted after the rest element");
  24969. }
  24970. return this.finishNode(prop, "RestElement")
  24971. }
  24972. // To disallow parenthesized identifier via `this.toAssignable()`.
  24973. if (this.type === types$2.parenL && refDestructuringErrors) {
  24974. if (refDestructuringErrors.parenthesizedAssign < 0) {
  24975. refDestructuringErrors.parenthesizedAssign = this.start;
  24976. }
  24977. if (refDestructuringErrors.parenthesizedBind < 0) {
  24978. refDestructuringErrors.parenthesizedBind = this.start;
  24979. }
  24980. }
  24981. // Parse argument.
  24982. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  24983. // To disallow trailing comma via `this.toAssignable()`.
  24984. if (this.type === types$2.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  24985. refDestructuringErrors.trailingComma = this.start;
  24986. }
  24987. // Finish
  24988. return this.finishNode(prop, "SpreadElement")
  24989. }
  24990. if (this.options.ecmaVersion >= 6) {
  24991. prop.method = false;
  24992. prop.shorthand = false;
  24993. if (isPattern || refDestructuringErrors) {
  24994. startPos = this.start;
  24995. startLoc = this.startLoc;
  24996. }
  24997. if (!isPattern)
  24998. { isGenerator = this.eat(types$2.star); }
  24999. }
  25000. var containsEsc = this.containsEsc;
  25001. this.parsePropertyName(prop);
  25002. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  25003. isAsync = true;
  25004. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$2.star);
  25005. this.parsePropertyName(prop, refDestructuringErrors);
  25006. } else {
  25007. isAsync = false;
  25008. }
  25009. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  25010. return this.finishNode(prop, "Property")
  25011. };
  25012. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  25013. if ((isGenerator || isAsync) && this.type === types$2.colon)
  25014. { this.unexpected(); }
  25015. if (this.eat(types$2.colon)) {
  25016. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  25017. prop.kind = "init";
  25018. } else if (this.options.ecmaVersion >= 6 && this.type === types$2.parenL) {
  25019. if (isPattern) { this.unexpected(); }
  25020. prop.kind = "init";
  25021. prop.method = true;
  25022. prop.value = this.parseMethod(isGenerator, isAsync);
  25023. } else if (!isPattern && !containsEsc &&
  25024. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  25025. (prop.key.name === "get" || prop.key.name === "set") &&
  25026. (this.type !== types$2.comma && this.type !== types$2.braceR)) {
  25027. if (isGenerator || isAsync) { this.unexpected(); }
  25028. prop.kind = prop.key.name;
  25029. this.parsePropertyName(prop);
  25030. prop.value = this.parseMethod(false);
  25031. var paramCount = prop.kind === "get" ? 0 : 1;
  25032. if (prop.value.params.length !== paramCount) {
  25033. var start = prop.value.start;
  25034. if (prop.kind === "get")
  25035. { this.raiseRecoverable(start, "getter should have no params"); }
  25036. else
  25037. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  25038. } else {
  25039. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  25040. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  25041. }
  25042. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  25043. if (isGenerator || isAsync) { this.unexpected(); }
  25044. this.checkUnreserved(prop.key);
  25045. if (prop.key.name === "await" && !this.awaitIdentPos)
  25046. { this.awaitIdentPos = startPos; }
  25047. prop.kind = "init";
  25048. if (isPattern) {
  25049. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
  25050. } else if (this.type === types$2.eq && refDestructuringErrors) {
  25051. if (refDestructuringErrors.shorthandAssign < 0)
  25052. { refDestructuringErrors.shorthandAssign = this.start; }
  25053. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
  25054. } else {
  25055. prop.value = prop.key;
  25056. }
  25057. prop.shorthand = true;
  25058. } else { this.unexpected(); }
  25059. };
  25060. pp$3.parsePropertyName = function(prop) {
  25061. if (this.options.ecmaVersion >= 6) {
  25062. if (this.eat(types$2.bracketL)) {
  25063. prop.computed = true;
  25064. prop.key = this.parseMaybeAssign();
  25065. this.expect(types$2.bracketR);
  25066. return prop.key
  25067. } else {
  25068. prop.computed = false;
  25069. }
  25070. }
  25071. return prop.key = this.type === types$2.num || this.type === types$2.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  25072. };
  25073. // Initialize empty function node.
  25074. pp$3.initFunction = function(node) {
  25075. node.id = null;
  25076. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  25077. if (this.options.ecmaVersion >= 8) { node.async = false; }
  25078. };
  25079. // Parse object or class method.
  25080. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  25081. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  25082. this.initFunction(node);
  25083. if (this.options.ecmaVersion >= 6)
  25084. { node.generator = isGenerator; }
  25085. if (this.options.ecmaVersion >= 8)
  25086. { node.async = !!isAsync; }
  25087. this.yieldPos = 0;
  25088. this.awaitPos = 0;
  25089. this.awaitIdentPos = 0;
  25090. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  25091. this.expect(types$2.parenL);
  25092. node.params = this.parseBindingList(types$2.parenR, false, this.options.ecmaVersion >= 8);
  25093. this.checkYieldAwaitInDefaultParams();
  25094. this.parseFunctionBody(node, false, true);
  25095. this.yieldPos = oldYieldPos;
  25096. this.awaitPos = oldAwaitPos;
  25097. this.awaitIdentPos = oldAwaitIdentPos;
  25098. return this.finishNode(node, "FunctionExpression")
  25099. };
  25100. // Parse arrow function expression with given parameters.
  25101. pp$3.parseArrowExpression = function(node, params, isAsync) {
  25102. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  25103. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  25104. this.initFunction(node);
  25105. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  25106. this.yieldPos = 0;
  25107. this.awaitPos = 0;
  25108. this.awaitIdentPos = 0;
  25109. node.params = this.toAssignableList(params, true);
  25110. this.parseFunctionBody(node, true, false);
  25111. this.yieldPos = oldYieldPos;
  25112. this.awaitPos = oldAwaitPos;
  25113. this.awaitIdentPos = oldAwaitIdentPos;
  25114. return this.finishNode(node, "ArrowFunctionExpression")
  25115. };
  25116. // Parse function body and check parameters.
  25117. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  25118. var isExpression = isArrowFunction && this.type !== types$2.braceL;
  25119. var oldStrict = this.strict, useStrict = false;
  25120. if (isExpression) {
  25121. node.body = this.parseMaybeAssign();
  25122. node.expression = true;
  25123. this.checkParams(node, false);
  25124. } else {
  25125. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  25126. if (!oldStrict || nonSimple) {
  25127. useStrict = this.strictDirective(this.end);
  25128. // If this is a strict mode function, verify that argument names
  25129. // are not repeated, and it does not try to bind the words `eval`
  25130. // or `arguments`.
  25131. if (useStrict && nonSimple)
  25132. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  25133. }
  25134. // Start a new scope with regard to labels and the `inFunction`
  25135. // flag (restore them to their old value afterwards).
  25136. var oldLabels = this.labels;
  25137. this.labels = [];
  25138. if (useStrict) { this.strict = true; }
  25139. // Add the params to varDeclaredNames to ensure that an error is thrown
  25140. // if a let/const declaration in the function clashes with one of the params.
  25141. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  25142. node.body = this.parseBlock(false);
  25143. node.expression = false;
  25144. this.adaptDirectivePrologue(node.body.body);
  25145. this.labels = oldLabels;
  25146. }
  25147. this.exitScope();
  25148. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  25149. if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); }
  25150. this.strict = oldStrict;
  25151. };
  25152. pp$3.isSimpleParamList = function(params) {
  25153. for (var i = 0, list = params; i < list.length; i += 1)
  25154. {
  25155. var param = list[i];
  25156. if (param.type !== "Identifier") { return false
  25157. } }
  25158. return true
  25159. };
  25160. // Checks function params for various disallowed patterns such as using "eval"
  25161. // or "arguments" and duplicate parameters.
  25162. pp$3.checkParams = function(node, allowDuplicates) {
  25163. var nameHash = {};
  25164. for (var i = 0, list = node.params; i < list.length; i += 1)
  25165. {
  25166. var param = list[i];
  25167. this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
  25168. }
  25169. };
  25170. // Parses a comma-separated list of expressions, and returns them as
  25171. // an array. `close` is the token type that ends the list, and
  25172. // `allowEmpty` can be turned on to allow subsequent commas with
  25173. // nothing in between them to be parsed as `null` (which is needed
  25174. // for array literals).
  25175. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  25176. var elts = [], first = true;
  25177. while (!this.eat(close)) {
  25178. if (!first) {
  25179. this.expect(types$2.comma);
  25180. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  25181. } else { first = false; }
  25182. var elt = (void 0);
  25183. if (allowEmpty && this.type === types$2.comma)
  25184. { elt = null; }
  25185. else if (this.type === types$2.ellipsis) {
  25186. elt = this.parseSpread(refDestructuringErrors);
  25187. if (refDestructuringErrors && this.type === types$2.comma && refDestructuringErrors.trailingComma < 0)
  25188. { refDestructuringErrors.trailingComma = this.start; }
  25189. } else {
  25190. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  25191. }
  25192. elts.push(elt);
  25193. }
  25194. return elts
  25195. };
  25196. pp$3.checkUnreserved = function(ref) {
  25197. var start = ref.start;
  25198. var end = ref.end;
  25199. var name = ref.name;
  25200. if (this.inGenerator && name === "yield")
  25201. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  25202. if (this.inAsync && name === "await")
  25203. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  25204. if (this.keywords.test(name))
  25205. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  25206. if (this.options.ecmaVersion < 6 &&
  25207. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  25208. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  25209. if (re.test(name)) {
  25210. if (!this.inAsync && name === "await")
  25211. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  25212. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  25213. }
  25214. };
  25215. // Parse the next token as an identifier. If `liberal` is true (used
  25216. // when parsing properties), it will also convert keywords into
  25217. // identifiers.
  25218. pp$3.parseIdent = function(liberal, isBinding) {
  25219. var node = this.startNode();
  25220. if (this.type === types$2.name) {
  25221. node.name = this.value;
  25222. } else if (this.type.keyword) {
  25223. node.name = this.type.keyword;
  25224. // To fix https://github.com/acornjs/acorn/issues/575
  25225. // `class` and `function` keywords push new context into this.context.
  25226. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  25227. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  25228. if ((node.name === "class" || node.name === "function") &&
  25229. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  25230. this.context.pop();
  25231. }
  25232. } else {
  25233. this.unexpected();
  25234. }
  25235. this.next();
  25236. this.finishNode(node, "Identifier");
  25237. if (!liberal) {
  25238. this.checkUnreserved(node);
  25239. if (node.name === "await" && !this.awaitIdentPos)
  25240. { this.awaitIdentPos = node.start; }
  25241. }
  25242. return node
  25243. };
  25244. // Parses yield expression inside generator.
  25245. pp$3.parseYield = function(noIn) {
  25246. if (!this.yieldPos) { this.yieldPos = this.start; }
  25247. var node = this.startNode();
  25248. this.next();
  25249. if (this.type === types$2.semi || this.canInsertSemicolon() || (this.type !== types$2.star && !this.type.startsExpr)) {
  25250. node.delegate = false;
  25251. node.argument = null;
  25252. } else {
  25253. node.delegate = this.eat(types$2.star);
  25254. node.argument = this.parseMaybeAssign(noIn);
  25255. }
  25256. return this.finishNode(node, "YieldExpression")
  25257. };
  25258. pp$3.parseAwait = function() {
  25259. if (!this.awaitPos) { this.awaitPos = this.start; }
  25260. var node = this.startNode();
  25261. this.next();
  25262. node.argument = this.parseMaybeUnary(null, true);
  25263. return this.finishNode(node, "AwaitExpression")
  25264. };
  25265. var pp$4 = Parser.prototype;
  25266. // This function is used to raise exceptions on parse errors. It
  25267. // takes an offset integer (into the current `input`) to indicate
  25268. // the location of the error, attaches the position to the end
  25269. // of the error message, and then raises a `SyntaxError` with that
  25270. // message.
  25271. pp$4.raise = function(pos, message) {
  25272. var loc = getLineInfo(this.input, pos);
  25273. message += " (" + loc.line + ":" + loc.column + ")";
  25274. var err = new SyntaxError(message);
  25275. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  25276. throw err
  25277. };
  25278. pp$4.raiseRecoverable = pp$4.raise;
  25279. pp$4.curPosition = function() {
  25280. if (this.options.locations) {
  25281. return new Position(this.curLine, this.pos - this.lineStart)
  25282. }
  25283. };
  25284. var pp$5 = Parser.prototype;
  25285. var Scope = function Scope(flags) {
  25286. this.flags = flags;
  25287. // A list of var-declared names in the current lexical scope
  25288. this.var = [];
  25289. // A list of lexically-declared names in the current lexical scope
  25290. this.lexical = [];
  25291. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  25292. this.functions = [];
  25293. };
  25294. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  25295. pp$5.enterScope = function(flags) {
  25296. this.scopeStack.push(new Scope(flags));
  25297. };
  25298. pp$5.exitScope = function() {
  25299. this.scopeStack.pop();
  25300. };
  25301. // The spec says:
  25302. // > At the top level of a function, or script, function declarations are
  25303. // > treated like var declarations rather than like lexical declarations.
  25304. pp$5.treatFunctionsAsVarInScope = function(scope) {
  25305. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  25306. };
  25307. pp$5.declareName = function(name, bindingType, pos) {
  25308. var redeclared = false;
  25309. if (bindingType === BIND_LEXICAL) {
  25310. var scope = this.currentScope();
  25311. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  25312. scope.lexical.push(name);
  25313. if (this.inModule && (scope.flags & SCOPE_TOP))
  25314. { delete this.undefinedExports[name]; }
  25315. } else if (bindingType === BIND_SIMPLE_CATCH) {
  25316. var scope$1 = this.currentScope();
  25317. scope$1.lexical.push(name);
  25318. } else if (bindingType === BIND_FUNCTION) {
  25319. var scope$2 = this.currentScope();
  25320. if (this.treatFunctionsAsVar)
  25321. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  25322. else
  25323. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  25324. scope$2.functions.push(name);
  25325. } else {
  25326. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  25327. var scope$3 = this.scopeStack[i];
  25328. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  25329. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  25330. redeclared = true;
  25331. break
  25332. }
  25333. scope$3.var.push(name);
  25334. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  25335. { delete this.undefinedExports[name]; }
  25336. if (scope$3.flags & SCOPE_VAR) { break }
  25337. }
  25338. }
  25339. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  25340. };
  25341. pp$5.checkLocalExport = function(id) {
  25342. // scope.functions must be empty as Module code is always strict.
  25343. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  25344. this.scopeStack[0].var.indexOf(id.name) === -1) {
  25345. this.undefinedExports[id.name] = id;
  25346. }
  25347. };
  25348. pp$5.currentScope = function() {
  25349. return this.scopeStack[this.scopeStack.length - 1]
  25350. };
  25351. pp$5.currentVarScope = function() {
  25352. for (var i = this.scopeStack.length - 1;; i--) {
  25353. var scope = this.scopeStack[i];
  25354. if (scope.flags & SCOPE_VAR) { return scope }
  25355. }
  25356. };
  25357. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  25358. pp$5.currentThisScope = function() {
  25359. for (var i = this.scopeStack.length - 1;; i--) {
  25360. var scope = this.scopeStack[i];
  25361. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  25362. }
  25363. };
  25364. var Node = function Node(parser, pos, loc) {
  25365. this.type = "";
  25366. this.start = pos;
  25367. this.end = 0;
  25368. if (parser.options.locations)
  25369. { this.loc = new SourceLocation(parser, loc); }
  25370. if (parser.options.directSourceFile)
  25371. { this.sourceFile = parser.options.directSourceFile; }
  25372. if (parser.options.ranges)
  25373. { this.range = [pos, 0]; }
  25374. };
  25375. // Start an AST node, attaching a start offset.
  25376. var pp$6 = Parser.prototype;
  25377. pp$6.startNode = function() {
  25378. return new Node(this, this.start, this.startLoc)
  25379. };
  25380. pp$6.startNodeAt = function(pos, loc) {
  25381. return new Node(this, pos, loc)
  25382. };
  25383. // Finish an AST node, adding `type` and `end` properties.
  25384. function finishNodeAt(node, type, pos, loc) {
  25385. node.type = type;
  25386. node.end = pos;
  25387. if (this.options.locations)
  25388. { node.loc.end = loc; }
  25389. if (this.options.ranges)
  25390. { node.range[1] = pos; }
  25391. return node
  25392. }
  25393. pp$6.finishNode = function(node, type) {
  25394. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  25395. };
  25396. // Finish node at given position
  25397. pp$6.finishNodeAt = function(node, type, pos, loc) {
  25398. return finishNodeAt.call(this, node, type, pos, loc)
  25399. };
  25400. // The algorithm used to determine whether a regexp can appear at a
  25401. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  25402. this.token = token;
  25403. this.isExpr = !!isExpr;
  25404. this.preserveSpace = !!preserveSpace;
  25405. this.override = override;
  25406. this.generator = !!generator;
  25407. };
  25408. var types$1$1 = {
  25409. b_stat: new TokContext("{", false),
  25410. b_expr: new TokContext("{", true),
  25411. b_tmpl: new TokContext("${", false),
  25412. p_stat: new TokContext("(", false),
  25413. p_expr: new TokContext("(", true),
  25414. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  25415. f_stat: new TokContext("function", false),
  25416. f_expr: new TokContext("function", true),
  25417. f_expr_gen: new TokContext("function", true, false, null, true),
  25418. f_gen: new TokContext("function", false, false, null, true)
  25419. };
  25420. var pp$7 = Parser.prototype;
  25421. pp$7.initialContext = function() {
  25422. return [types$1$1.b_stat]
  25423. };
  25424. pp$7.braceIsBlock = function(prevType) {
  25425. var parent = this.curContext();
  25426. if (parent === types$1$1.f_expr || parent === types$1$1.f_stat)
  25427. { return true }
  25428. if (prevType === types$2.colon && (parent === types$1$1.b_stat || parent === types$1$1.b_expr))
  25429. { return !parent.isExpr }
  25430. // The check for `tt.name && exprAllowed` detects whether we are
  25431. // after a `yield` or `of` construct. See the `updateContext` for
  25432. // `tt.name`.
  25433. if (prevType === types$2._return || prevType === types$2.name && this.exprAllowed)
  25434. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  25435. if (prevType === types$2._else || prevType === types$2.semi || prevType === types$2.eof || prevType === types$2.parenR || prevType === types$2.arrow)
  25436. { return true }
  25437. if (prevType === types$2.braceL)
  25438. { return parent === types$1$1.b_stat }
  25439. if (prevType === types$2._var || prevType === types$2._const || prevType === types$2.name)
  25440. { return false }
  25441. return !this.exprAllowed
  25442. };
  25443. pp$7.inGeneratorContext = function() {
  25444. for (var i = this.context.length - 1; i >= 1; i--) {
  25445. var context = this.context[i];
  25446. if (context.token === "function")
  25447. { return context.generator }
  25448. }
  25449. return false
  25450. };
  25451. pp$7.updateContext = function(prevType) {
  25452. var update, type = this.type;
  25453. if (type.keyword && prevType === types$2.dot)
  25454. { this.exprAllowed = false; }
  25455. else if (update = type.updateContext)
  25456. { update.call(this, prevType); }
  25457. else
  25458. { this.exprAllowed = type.beforeExpr; }
  25459. };
  25460. // Token-specific context update code
  25461. types$2.parenR.updateContext = types$2.braceR.updateContext = function() {
  25462. if (this.context.length === 1) {
  25463. this.exprAllowed = true;
  25464. return
  25465. }
  25466. var out = this.context.pop();
  25467. if (out === types$1$1.b_stat && this.curContext().token === "function") {
  25468. out = this.context.pop();
  25469. }
  25470. this.exprAllowed = !out.isExpr;
  25471. };
  25472. types$2.braceL.updateContext = function(prevType) {
  25473. this.context.push(this.braceIsBlock(prevType) ? types$1$1.b_stat : types$1$1.b_expr);
  25474. this.exprAllowed = true;
  25475. };
  25476. types$2.dollarBraceL.updateContext = function() {
  25477. this.context.push(types$1$1.b_tmpl);
  25478. this.exprAllowed = true;
  25479. };
  25480. types$2.parenL.updateContext = function(prevType) {
  25481. var statementParens = prevType === types$2._if || prevType === types$2._for || prevType === types$2._with || prevType === types$2._while;
  25482. this.context.push(statementParens ? types$1$1.p_stat : types$1$1.p_expr);
  25483. this.exprAllowed = true;
  25484. };
  25485. types$2.incDec.updateContext = function() {
  25486. // tokExprAllowed stays unchanged
  25487. };
  25488. types$2._function.updateContext = types$2._class.updateContext = function(prevType) {
  25489. if (prevType.beforeExpr && prevType !== types$2.semi && prevType !== types$2._else &&
  25490. !(prevType === types$2._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  25491. !((prevType === types$2.colon || prevType === types$2.braceL) && this.curContext() === types$1$1.b_stat))
  25492. { this.context.push(types$1$1.f_expr); }
  25493. else
  25494. { this.context.push(types$1$1.f_stat); }
  25495. this.exprAllowed = false;
  25496. };
  25497. types$2.backQuote.updateContext = function() {
  25498. if (this.curContext() === types$1$1.q_tmpl)
  25499. { this.context.pop(); }
  25500. else
  25501. { this.context.push(types$1$1.q_tmpl); }
  25502. this.exprAllowed = false;
  25503. };
  25504. types$2.star.updateContext = function(prevType) {
  25505. if (prevType === types$2._function) {
  25506. var index = this.context.length - 1;
  25507. if (this.context[index] === types$1$1.f_expr)
  25508. { this.context[index] = types$1$1.f_expr_gen; }
  25509. else
  25510. { this.context[index] = types$1$1.f_gen; }
  25511. }
  25512. this.exprAllowed = true;
  25513. };
  25514. types$2.name.updateContext = function(prevType) {
  25515. var allowed = false;
  25516. if (this.options.ecmaVersion >= 6 && prevType !== types$2.dot) {
  25517. if (this.value === "of" && !this.exprAllowed ||
  25518. this.value === "yield" && this.inGeneratorContext())
  25519. { allowed = true; }
  25520. }
  25521. this.exprAllowed = allowed;
  25522. };
  25523. // This file contains Unicode properties extracted from the ECMAScript
  25524. // specification. The lists are extracted like so:
  25525. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  25526. // #table-binary-unicode-properties
  25527. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  25528. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  25529. var ecma11BinaryProperties = ecma10BinaryProperties;
  25530. var unicodeBinaryProperties = {
  25531. 9: ecma9BinaryProperties,
  25532. 10: ecma10BinaryProperties,
  25533. 11: ecma11BinaryProperties
  25534. };
  25535. // #table-unicode-general-category-values
  25536. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  25537. // #table-unicode-script-values
  25538. var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  25539. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  25540. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  25541. var unicodeScriptValues = {
  25542. 9: ecma9ScriptValues,
  25543. 10: ecma10ScriptValues,
  25544. 11: ecma11ScriptValues
  25545. };
  25546. var data = {};
  25547. function buildUnicodeData(ecmaVersion) {
  25548. var d = data[ecmaVersion] = {
  25549. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  25550. nonBinary: {
  25551. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  25552. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  25553. }
  25554. };
  25555. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  25556. d.nonBinary.gc = d.nonBinary.General_Category;
  25557. d.nonBinary.sc = d.nonBinary.Script;
  25558. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  25559. }
  25560. buildUnicodeData(9);
  25561. buildUnicodeData(10);
  25562. buildUnicodeData(11);
  25563. var pp$8 = Parser.prototype;
  25564. var RegExpValidationState = function RegExpValidationState(parser) {
  25565. this.parser = parser;
  25566. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
  25567. this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];
  25568. this.source = "";
  25569. this.flags = "";
  25570. this.start = 0;
  25571. this.switchU = false;
  25572. this.switchN = false;
  25573. this.pos = 0;
  25574. this.lastIntValue = 0;
  25575. this.lastStringValue = "";
  25576. this.lastAssertionIsQuantifiable = false;
  25577. this.numCapturingParens = 0;
  25578. this.maxBackReference = 0;
  25579. this.groupNames = [];
  25580. this.backReferenceNames = [];
  25581. };
  25582. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  25583. var unicode = flags.indexOf("u") !== -1;
  25584. this.start = start | 0;
  25585. this.source = pattern + "";
  25586. this.flags = flags;
  25587. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  25588. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  25589. };
  25590. RegExpValidationState.prototype.raise = function raise (message) {
  25591. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  25592. };
  25593. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  25594. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  25595. RegExpValidationState.prototype.at = function at (i) {
  25596. var s = this.source;
  25597. var l = s.length;
  25598. if (i >= l) {
  25599. return -1
  25600. }
  25601. var c = s.charCodeAt(i);
  25602. if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  25603. return c
  25604. }
  25605. return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00
  25606. };
  25607. RegExpValidationState.prototype.nextIndex = function nextIndex (i) {
  25608. var s = this.source;
  25609. var l = s.length;
  25610. if (i >= l) {
  25611. return l
  25612. }
  25613. var c = s.charCodeAt(i);
  25614. if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  25615. return i + 1
  25616. }
  25617. return i + 2
  25618. };
  25619. RegExpValidationState.prototype.current = function current () {
  25620. return this.at(this.pos)
  25621. };
  25622. RegExpValidationState.prototype.lookahead = function lookahead () {
  25623. return this.at(this.nextIndex(this.pos))
  25624. };
  25625. RegExpValidationState.prototype.advance = function advance () {
  25626. this.pos = this.nextIndex(this.pos);
  25627. };
  25628. RegExpValidationState.prototype.eat = function eat (ch) {
  25629. if (this.current() === ch) {
  25630. this.advance();
  25631. return true
  25632. }
  25633. return false
  25634. };
  25635. function codePointToString(ch) {
  25636. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  25637. ch -= 0x10000;
  25638. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  25639. }
  25640. /**
  25641. * Validate the flags part of a given RegExpLiteral.
  25642. *
  25643. * @param {RegExpValidationState} state The state to validate RegExp.
  25644. * @returns {void}
  25645. */
  25646. pp$8.validateRegExpFlags = function(state) {
  25647. var validFlags = state.validFlags;
  25648. var flags = state.flags;
  25649. for (var i = 0; i < flags.length; i++) {
  25650. var flag = flags.charAt(i);
  25651. if (validFlags.indexOf(flag) === -1) {
  25652. this.raise(state.start, "Invalid regular expression flag");
  25653. }
  25654. if (flags.indexOf(flag, i + 1) > -1) {
  25655. this.raise(state.start, "Duplicate regular expression flag");
  25656. }
  25657. }
  25658. };
  25659. /**
  25660. * Validate the pattern part of a given RegExpLiteral.
  25661. *
  25662. * @param {RegExpValidationState} state The state to validate RegExp.
  25663. * @returns {void}
  25664. */
  25665. pp$8.validateRegExpPattern = function(state) {
  25666. this.regexp_pattern(state);
  25667. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  25668. // parsing contains a |GroupName|, reparse with the goal symbol
  25669. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  25670. // exception if _P_ did not conform to the grammar, if any elements of _P_
  25671. // were not matched by the parse, or if any Early Error conditions exist.
  25672. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  25673. state.switchN = true;
  25674. this.regexp_pattern(state);
  25675. }
  25676. };
  25677. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  25678. pp$8.regexp_pattern = function(state) {
  25679. state.pos = 0;
  25680. state.lastIntValue = 0;
  25681. state.lastStringValue = "";
  25682. state.lastAssertionIsQuantifiable = false;
  25683. state.numCapturingParens = 0;
  25684. state.maxBackReference = 0;
  25685. state.groupNames.length = 0;
  25686. state.backReferenceNames.length = 0;
  25687. this.regexp_disjunction(state);
  25688. if (state.pos !== state.source.length) {
  25689. // Make the same messages as V8.
  25690. if (state.eat(0x29 /* ) */)) {
  25691. state.raise("Unmatched ')'");
  25692. }
  25693. if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) {
  25694. state.raise("Lone quantifier brackets");
  25695. }
  25696. }
  25697. if (state.maxBackReference > state.numCapturingParens) {
  25698. state.raise("Invalid escape");
  25699. }
  25700. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  25701. var name = list[i];
  25702. if (state.groupNames.indexOf(name) === -1) {
  25703. state.raise("Invalid named capture referenced");
  25704. }
  25705. }
  25706. };
  25707. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  25708. pp$8.regexp_disjunction = function(state) {
  25709. this.regexp_alternative(state);
  25710. while (state.eat(0x7C /* | */)) {
  25711. this.regexp_alternative(state);
  25712. }
  25713. // Make the same message as V8.
  25714. if (this.regexp_eatQuantifier(state, true)) {
  25715. state.raise("Nothing to repeat");
  25716. }
  25717. if (state.eat(0x7B /* { */)) {
  25718. state.raise("Lone quantifier brackets");
  25719. }
  25720. };
  25721. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  25722. pp$8.regexp_alternative = function(state) {
  25723. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  25724. { }
  25725. };
  25726. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  25727. pp$8.regexp_eatTerm = function(state) {
  25728. if (this.regexp_eatAssertion(state)) {
  25729. // Handle `QuantifiableAssertion Quantifier` alternative.
  25730. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  25731. // is a QuantifiableAssertion.
  25732. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  25733. // Make the same message as V8.
  25734. if (state.switchU) {
  25735. state.raise("Invalid quantifier");
  25736. }
  25737. }
  25738. return true
  25739. }
  25740. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  25741. this.regexp_eatQuantifier(state);
  25742. return true
  25743. }
  25744. return false
  25745. };
  25746. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  25747. pp$8.regexp_eatAssertion = function(state) {
  25748. var start = state.pos;
  25749. state.lastAssertionIsQuantifiable = false;
  25750. // ^, $
  25751. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  25752. return true
  25753. }
  25754. // \b \B
  25755. if (state.eat(0x5C /* \ */)) {
  25756. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  25757. return true
  25758. }
  25759. state.pos = start;
  25760. }
  25761. // Lookahead / Lookbehind
  25762. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  25763. var lookbehind = false;
  25764. if (this.options.ecmaVersion >= 9) {
  25765. lookbehind = state.eat(0x3C /* < */);
  25766. }
  25767. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  25768. this.regexp_disjunction(state);
  25769. if (!state.eat(0x29 /* ) */)) {
  25770. state.raise("Unterminated group");
  25771. }
  25772. state.lastAssertionIsQuantifiable = !lookbehind;
  25773. return true
  25774. }
  25775. }
  25776. state.pos = start;
  25777. return false
  25778. };
  25779. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  25780. pp$8.regexp_eatQuantifier = function(state, noError) {
  25781. if ( noError === void 0 ) noError = false;
  25782. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  25783. state.eat(0x3F /* ? */);
  25784. return true
  25785. }
  25786. return false
  25787. };
  25788. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  25789. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  25790. return (
  25791. state.eat(0x2A /* * */) ||
  25792. state.eat(0x2B /* + */) ||
  25793. state.eat(0x3F /* ? */) ||
  25794. this.regexp_eatBracedQuantifier(state, noError)
  25795. )
  25796. };
  25797. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  25798. var start = state.pos;
  25799. if (state.eat(0x7B /* { */)) {
  25800. var min = 0, max = -1;
  25801. if (this.regexp_eatDecimalDigits(state)) {
  25802. min = state.lastIntValue;
  25803. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  25804. max = state.lastIntValue;
  25805. }
  25806. if (state.eat(0x7D /* } */)) {
  25807. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  25808. if (max !== -1 && max < min && !noError) {
  25809. state.raise("numbers out of order in {} quantifier");
  25810. }
  25811. return true
  25812. }
  25813. }
  25814. if (state.switchU && !noError) {
  25815. state.raise("Incomplete quantifier");
  25816. }
  25817. state.pos = start;
  25818. }
  25819. return false
  25820. };
  25821. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  25822. pp$8.regexp_eatAtom = function(state) {
  25823. return (
  25824. this.regexp_eatPatternCharacters(state) ||
  25825. state.eat(0x2E /* . */) ||
  25826. this.regexp_eatReverseSolidusAtomEscape(state) ||
  25827. this.regexp_eatCharacterClass(state) ||
  25828. this.regexp_eatUncapturingGroup(state) ||
  25829. this.regexp_eatCapturingGroup(state)
  25830. )
  25831. };
  25832. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  25833. var start = state.pos;
  25834. if (state.eat(0x5C /* \ */)) {
  25835. if (this.regexp_eatAtomEscape(state)) {
  25836. return true
  25837. }
  25838. state.pos = start;
  25839. }
  25840. return false
  25841. };
  25842. pp$8.regexp_eatUncapturingGroup = function(state) {
  25843. var start = state.pos;
  25844. if (state.eat(0x28 /* ( */)) {
  25845. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  25846. this.regexp_disjunction(state);
  25847. if (state.eat(0x29 /* ) */)) {
  25848. return true
  25849. }
  25850. state.raise("Unterminated group");
  25851. }
  25852. state.pos = start;
  25853. }
  25854. return false
  25855. };
  25856. pp$8.regexp_eatCapturingGroup = function(state) {
  25857. if (state.eat(0x28 /* ( */)) {
  25858. if (this.options.ecmaVersion >= 9) {
  25859. this.regexp_groupSpecifier(state);
  25860. } else if (state.current() === 0x3F /* ? */) {
  25861. state.raise("Invalid group");
  25862. }
  25863. this.regexp_disjunction(state);
  25864. if (state.eat(0x29 /* ) */)) {
  25865. state.numCapturingParens += 1;
  25866. return true
  25867. }
  25868. state.raise("Unterminated group");
  25869. }
  25870. return false
  25871. };
  25872. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  25873. pp$8.regexp_eatExtendedAtom = function(state) {
  25874. return (
  25875. state.eat(0x2E /* . */) ||
  25876. this.regexp_eatReverseSolidusAtomEscape(state) ||
  25877. this.regexp_eatCharacterClass(state) ||
  25878. this.regexp_eatUncapturingGroup(state) ||
  25879. this.regexp_eatCapturingGroup(state) ||
  25880. this.regexp_eatInvalidBracedQuantifier(state) ||
  25881. this.regexp_eatExtendedPatternCharacter(state)
  25882. )
  25883. };
  25884. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  25885. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  25886. if (this.regexp_eatBracedQuantifier(state, true)) {
  25887. state.raise("Nothing to repeat");
  25888. }
  25889. return false
  25890. };
  25891. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  25892. pp$8.regexp_eatSyntaxCharacter = function(state) {
  25893. var ch = state.current();
  25894. if (isSyntaxCharacter(ch)) {
  25895. state.lastIntValue = ch;
  25896. state.advance();
  25897. return true
  25898. }
  25899. return false
  25900. };
  25901. function isSyntaxCharacter(ch) {
  25902. return (
  25903. ch === 0x24 /* $ */ ||
  25904. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  25905. ch === 0x2E /* . */ ||
  25906. ch === 0x3F /* ? */ ||
  25907. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  25908. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  25909. )
  25910. }
  25911. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  25912. // But eat eager.
  25913. pp$8.regexp_eatPatternCharacters = function(state) {
  25914. var start = state.pos;
  25915. var ch = 0;
  25916. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  25917. state.advance();
  25918. }
  25919. return state.pos !== start
  25920. };
  25921. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  25922. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  25923. var ch = state.current();
  25924. if (
  25925. ch !== -1 &&
  25926. ch !== 0x24 /* $ */ &&
  25927. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  25928. ch !== 0x2E /* . */ &&
  25929. ch !== 0x3F /* ? */ &&
  25930. ch !== 0x5B /* [ */ &&
  25931. ch !== 0x5E /* ^ */ &&
  25932. ch !== 0x7C /* | */
  25933. ) {
  25934. state.advance();
  25935. return true
  25936. }
  25937. return false
  25938. };
  25939. // GroupSpecifier[U] ::
  25940. // [empty]
  25941. // `?` GroupName[?U]
  25942. pp$8.regexp_groupSpecifier = function(state) {
  25943. if (state.eat(0x3F /* ? */)) {
  25944. if (this.regexp_eatGroupName(state)) {
  25945. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  25946. state.raise("Duplicate capture group name");
  25947. }
  25948. state.groupNames.push(state.lastStringValue);
  25949. return
  25950. }
  25951. state.raise("Invalid group");
  25952. }
  25953. };
  25954. // GroupName[U] ::
  25955. // `<` RegExpIdentifierName[?U] `>`
  25956. // Note: this updates `state.lastStringValue` property with the eaten name.
  25957. pp$8.regexp_eatGroupName = function(state) {
  25958. state.lastStringValue = "";
  25959. if (state.eat(0x3C /* < */)) {
  25960. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  25961. return true
  25962. }
  25963. state.raise("Invalid capture group name");
  25964. }
  25965. return false
  25966. };
  25967. // RegExpIdentifierName[U] ::
  25968. // RegExpIdentifierStart[?U]
  25969. // RegExpIdentifierName[?U] RegExpIdentifierPart[?U]
  25970. // Note: this updates `state.lastStringValue` property with the eaten name.
  25971. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  25972. state.lastStringValue = "";
  25973. if (this.regexp_eatRegExpIdentifierStart(state)) {
  25974. state.lastStringValue += codePointToString(state.lastIntValue);
  25975. while (this.regexp_eatRegExpIdentifierPart(state)) {
  25976. state.lastStringValue += codePointToString(state.lastIntValue);
  25977. }
  25978. return true
  25979. }
  25980. return false
  25981. };
  25982. // RegExpIdentifierStart[U] ::
  25983. // UnicodeIDStart
  25984. // `$`
  25985. // `_`
  25986. // `\` RegExpUnicodeEscapeSequence[?U]
  25987. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  25988. var start = state.pos;
  25989. var ch = state.current();
  25990. state.advance();
  25991. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
  25992. ch = state.lastIntValue;
  25993. }
  25994. if (isRegExpIdentifierStart(ch)) {
  25995. state.lastIntValue = ch;
  25996. return true
  25997. }
  25998. state.pos = start;
  25999. return false
  26000. };
  26001. function isRegExpIdentifierStart(ch) {
  26002. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  26003. }
  26004. // RegExpIdentifierPart[U] ::
  26005. // UnicodeIDContinue
  26006. // `$`
  26007. // `_`
  26008. // `\` RegExpUnicodeEscapeSequence[?U]
  26009. // <ZWNJ>
  26010. // <ZWJ>
  26011. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  26012. var start = state.pos;
  26013. var ch = state.current();
  26014. state.advance();
  26015. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
  26016. ch = state.lastIntValue;
  26017. }
  26018. if (isRegExpIdentifierPart(ch)) {
  26019. state.lastIntValue = ch;
  26020. return true
  26021. }
  26022. state.pos = start;
  26023. return false
  26024. };
  26025. function isRegExpIdentifierPart(ch) {
  26026. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  26027. }
  26028. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  26029. pp$8.regexp_eatAtomEscape = function(state) {
  26030. if (
  26031. this.regexp_eatBackReference(state) ||
  26032. this.regexp_eatCharacterClassEscape(state) ||
  26033. this.regexp_eatCharacterEscape(state) ||
  26034. (state.switchN && this.regexp_eatKGroupName(state))
  26035. ) {
  26036. return true
  26037. }
  26038. if (state.switchU) {
  26039. // Make the same message as V8.
  26040. if (state.current() === 0x63 /* c */) {
  26041. state.raise("Invalid unicode escape");
  26042. }
  26043. state.raise("Invalid escape");
  26044. }
  26045. return false
  26046. };
  26047. pp$8.regexp_eatBackReference = function(state) {
  26048. var start = state.pos;
  26049. if (this.regexp_eatDecimalEscape(state)) {
  26050. var n = state.lastIntValue;
  26051. if (state.switchU) {
  26052. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  26053. if (n > state.maxBackReference) {
  26054. state.maxBackReference = n;
  26055. }
  26056. return true
  26057. }
  26058. if (n <= state.numCapturingParens) {
  26059. return true
  26060. }
  26061. state.pos = start;
  26062. }
  26063. return false
  26064. };
  26065. pp$8.regexp_eatKGroupName = function(state) {
  26066. if (state.eat(0x6B /* k */)) {
  26067. if (this.regexp_eatGroupName(state)) {
  26068. state.backReferenceNames.push(state.lastStringValue);
  26069. return true
  26070. }
  26071. state.raise("Invalid named reference");
  26072. }
  26073. return false
  26074. };
  26075. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  26076. pp$8.regexp_eatCharacterEscape = function(state) {
  26077. return (
  26078. this.regexp_eatControlEscape(state) ||
  26079. this.regexp_eatCControlLetter(state) ||
  26080. this.regexp_eatZero(state) ||
  26081. this.regexp_eatHexEscapeSequence(state) ||
  26082. this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
  26083. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  26084. this.regexp_eatIdentityEscape(state)
  26085. )
  26086. };
  26087. pp$8.regexp_eatCControlLetter = function(state) {
  26088. var start = state.pos;
  26089. if (state.eat(0x63 /* c */)) {
  26090. if (this.regexp_eatControlLetter(state)) {
  26091. return true
  26092. }
  26093. state.pos = start;
  26094. }
  26095. return false
  26096. };
  26097. pp$8.regexp_eatZero = function(state) {
  26098. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  26099. state.lastIntValue = 0;
  26100. state.advance();
  26101. return true
  26102. }
  26103. return false
  26104. };
  26105. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  26106. pp$8.regexp_eatControlEscape = function(state) {
  26107. var ch = state.current();
  26108. if (ch === 0x74 /* t */) {
  26109. state.lastIntValue = 0x09; /* \t */
  26110. state.advance();
  26111. return true
  26112. }
  26113. if (ch === 0x6E /* n */) {
  26114. state.lastIntValue = 0x0A; /* \n */
  26115. state.advance();
  26116. return true
  26117. }
  26118. if (ch === 0x76 /* v */) {
  26119. state.lastIntValue = 0x0B; /* \v */
  26120. state.advance();
  26121. return true
  26122. }
  26123. if (ch === 0x66 /* f */) {
  26124. state.lastIntValue = 0x0C; /* \f */
  26125. state.advance();
  26126. return true
  26127. }
  26128. if (ch === 0x72 /* r */) {
  26129. state.lastIntValue = 0x0D; /* \r */
  26130. state.advance();
  26131. return true
  26132. }
  26133. return false
  26134. };
  26135. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  26136. pp$8.regexp_eatControlLetter = function(state) {
  26137. var ch = state.current();
  26138. if (isControlLetter(ch)) {
  26139. state.lastIntValue = ch % 0x20;
  26140. state.advance();
  26141. return true
  26142. }
  26143. return false
  26144. };
  26145. function isControlLetter(ch) {
  26146. return (
  26147. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  26148. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  26149. )
  26150. }
  26151. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  26152. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state) {
  26153. var start = state.pos;
  26154. if (state.eat(0x75 /* u */)) {
  26155. if (this.regexp_eatFixedHexDigits(state, 4)) {
  26156. var lead = state.lastIntValue;
  26157. if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  26158. var leadSurrogateEnd = state.pos;
  26159. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  26160. var trail = state.lastIntValue;
  26161. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  26162. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  26163. return true
  26164. }
  26165. }
  26166. state.pos = leadSurrogateEnd;
  26167. state.lastIntValue = lead;
  26168. }
  26169. return true
  26170. }
  26171. if (
  26172. state.switchU &&
  26173. state.eat(0x7B /* { */) &&
  26174. this.regexp_eatHexDigits(state) &&
  26175. state.eat(0x7D /* } */) &&
  26176. isValidUnicode(state.lastIntValue)
  26177. ) {
  26178. return true
  26179. }
  26180. if (state.switchU) {
  26181. state.raise("Invalid unicode escape");
  26182. }
  26183. state.pos = start;
  26184. }
  26185. return false
  26186. };
  26187. function isValidUnicode(ch) {
  26188. return ch >= 0 && ch <= 0x10FFFF
  26189. }
  26190. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  26191. pp$8.regexp_eatIdentityEscape = function(state) {
  26192. if (state.switchU) {
  26193. if (this.regexp_eatSyntaxCharacter(state)) {
  26194. return true
  26195. }
  26196. if (state.eat(0x2F /* / */)) {
  26197. state.lastIntValue = 0x2F; /* / */
  26198. return true
  26199. }
  26200. return false
  26201. }
  26202. var ch = state.current();
  26203. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  26204. state.lastIntValue = ch;
  26205. state.advance();
  26206. return true
  26207. }
  26208. return false
  26209. };
  26210. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  26211. pp$8.regexp_eatDecimalEscape = function(state) {
  26212. state.lastIntValue = 0;
  26213. var ch = state.current();
  26214. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  26215. do {
  26216. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  26217. state.advance();
  26218. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  26219. return true
  26220. }
  26221. return false
  26222. };
  26223. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  26224. pp$8.regexp_eatCharacterClassEscape = function(state) {
  26225. var ch = state.current();
  26226. if (isCharacterClassEscape(ch)) {
  26227. state.lastIntValue = -1;
  26228. state.advance();
  26229. return true
  26230. }
  26231. if (
  26232. state.switchU &&
  26233. this.options.ecmaVersion >= 9 &&
  26234. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  26235. ) {
  26236. state.lastIntValue = -1;
  26237. state.advance();
  26238. if (
  26239. state.eat(0x7B /* { */) &&
  26240. this.regexp_eatUnicodePropertyValueExpression(state) &&
  26241. state.eat(0x7D /* } */)
  26242. ) {
  26243. return true
  26244. }
  26245. state.raise("Invalid property name");
  26246. }
  26247. return false
  26248. };
  26249. function isCharacterClassEscape(ch) {
  26250. return (
  26251. ch === 0x64 /* d */ ||
  26252. ch === 0x44 /* D */ ||
  26253. ch === 0x73 /* s */ ||
  26254. ch === 0x53 /* S */ ||
  26255. ch === 0x77 /* w */ ||
  26256. ch === 0x57 /* W */
  26257. )
  26258. }
  26259. // UnicodePropertyValueExpression ::
  26260. // UnicodePropertyName `=` UnicodePropertyValue
  26261. // LoneUnicodePropertyNameOrValue
  26262. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  26263. var start = state.pos;
  26264. // UnicodePropertyName `=` UnicodePropertyValue
  26265. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  26266. var name = state.lastStringValue;
  26267. if (this.regexp_eatUnicodePropertyValue(state)) {
  26268. var value = state.lastStringValue;
  26269. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  26270. return true
  26271. }
  26272. }
  26273. state.pos = start;
  26274. // LoneUnicodePropertyNameOrValue
  26275. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  26276. var nameOrValue = state.lastStringValue;
  26277. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  26278. return true
  26279. }
  26280. return false
  26281. };
  26282. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  26283. if (!has$1(state.unicodeProperties.nonBinary, name))
  26284. { state.raise("Invalid property name"); }
  26285. if (!state.unicodeProperties.nonBinary[name].test(value))
  26286. { state.raise("Invalid property value"); }
  26287. };
  26288. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  26289. if (!state.unicodeProperties.binary.test(nameOrValue))
  26290. { state.raise("Invalid property name"); }
  26291. };
  26292. // UnicodePropertyName ::
  26293. // UnicodePropertyNameCharacters
  26294. pp$8.regexp_eatUnicodePropertyName = function(state) {
  26295. var ch = 0;
  26296. state.lastStringValue = "";
  26297. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  26298. state.lastStringValue += codePointToString(ch);
  26299. state.advance();
  26300. }
  26301. return state.lastStringValue !== ""
  26302. };
  26303. function isUnicodePropertyNameCharacter(ch) {
  26304. return isControlLetter(ch) || ch === 0x5F /* _ */
  26305. }
  26306. // UnicodePropertyValue ::
  26307. // UnicodePropertyValueCharacters
  26308. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  26309. var ch = 0;
  26310. state.lastStringValue = "";
  26311. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  26312. state.lastStringValue += codePointToString(ch);
  26313. state.advance();
  26314. }
  26315. return state.lastStringValue !== ""
  26316. };
  26317. function isUnicodePropertyValueCharacter(ch) {
  26318. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  26319. }
  26320. // LoneUnicodePropertyNameOrValue ::
  26321. // UnicodePropertyValueCharacters
  26322. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  26323. return this.regexp_eatUnicodePropertyValue(state)
  26324. };
  26325. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  26326. pp$8.regexp_eatCharacterClass = function(state) {
  26327. if (state.eat(0x5B /* [ */)) {
  26328. state.eat(0x5E /* ^ */);
  26329. this.regexp_classRanges(state);
  26330. if (state.eat(0x5D /* [ */)) {
  26331. return true
  26332. }
  26333. // Unreachable since it threw "unterminated regular expression" error before.
  26334. state.raise("Unterminated character class");
  26335. }
  26336. return false
  26337. };
  26338. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  26339. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  26340. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  26341. pp$8.regexp_classRanges = function(state) {
  26342. while (this.regexp_eatClassAtom(state)) {
  26343. var left = state.lastIntValue;
  26344. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  26345. var right = state.lastIntValue;
  26346. if (state.switchU && (left === -1 || right === -1)) {
  26347. state.raise("Invalid character class");
  26348. }
  26349. if (left !== -1 && right !== -1 && left > right) {
  26350. state.raise("Range out of order in character class");
  26351. }
  26352. }
  26353. }
  26354. };
  26355. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  26356. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  26357. pp$8.regexp_eatClassAtom = function(state) {
  26358. var start = state.pos;
  26359. if (state.eat(0x5C /* \ */)) {
  26360. if (this.regexp_eatClassEscape(state)) {
  26361. return true
  26362. }
  26363. if (state.switchU) {
  26364. // Make the same message as V8.
  26365. var ch$1 = state.current();
  26366. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  26367. state.raise("Invalid class escape");
  26368. }
  26369. state.raise("Invalid escape");
  26370. }
  26371. state.pos = start;
  26372. }
  26373. var ch = state.current();
  26374. if (ch !== 0x5D /* [ */) {
  26375. state.lastIntValue = ch;
  26376. state.advance();
  26377. return true
  26378. }
  26379. return false
  26380. };
  26381. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  26382. pp$8.regexp_eatClassEscape = function(state) {
  26383. var start = state.pos;
  26384. if (state.eat(0x62 /* b */)) {
  26385. state.lastIntValue = 0x08; /* <BS> */
  26386. return true
  26387. }
  26388. if (state.switchU && state.eat(0x2D /* - */)) {
  26389. state.lastIntValue = 0x2D; /* - */
  26390. return true
  26391. }
  26392. if (!state.switchU && state.eat(0x63 /* c */)) {
  26393. if (this.regexp_eatClassControlLetter(state)) {
  26394. return true
  26395. }
  26396. state.pos = start;
  26397. }
  26398. return (
  26399. this.regexp_eatCharacterClassEscape(state) ||
  26400. this.regexp_eatCharacterEscape(state)
  26401. )
  26402. };
  26403. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  26404. pp$8.regexp_eatClassControlLetter = function(state) {
  26405. var ch = state.current();
  26406. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  26407. state.lastIntValue = ch % 0x20;
  26408. state.advance();
  26409. return true
  26410. }
  26411. return false
  26412. };
  26413. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  26414. pp$8.regexp_eatHexEscapeSequence = function(state) {
  26415. var start = state.pos;
  26416. if (state.eat(0x78 /* x */)) {
  26417. if (this.regexp_eatFixedHexDigits(state, 2)) {
  26418. return true
  26419. }
  26420. if (state.switchU) {
  26421. state.raise("Invalid escape");
  26422. }
  26423. state.pos = start;
  26424. }
  26425. return false
  26426. };
  26427. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  26428. pp$8.regexp_eatDecimalDigits = function(state) {
  26429. var start = state.pos;
  26430. var ch = 0;
  26431. state.lastIntValue = 0;
  26432. while (isDecimalDigit(ch = state.current())) {
  26433. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  26434. state.advance();
  26435. }
  26436. return state.pos !== start
  26437. };
  26438. function isDecimalDigit(ch) {
  26439. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  26440. }
  26441. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  26442. pp$8.regexp_eatHexDigits = function(state) {
  26443. var start = state.pos;
  26444. var ch = 0;
  26445. state.lastIntValue = 0;
  26446. while (isHexDigit(ch = state.current())) {
  26447. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  26448. state.advance();
  26449. }
  26450. return state.pos !== start
  26451. };
  26452. function isHexDigit(ch) {
  26453. return (
  26454. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  26455. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  26456. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  26457. )
  26458. }
  26459. function hexToInt(ch) {
  26460. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  26461. return 10 + (ch - 0x41 /* A */)
  26462. }
  26463. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  26464. return 10 + (ch - 0x61 /* a */)
  26465. }
  26466. return ch - 0x30 /* 0 */
  26467. }
  26468. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  26469. // Allows only 0-377(octal) i.e. 0-255(decimal).
  26470. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  26471. if (this.regexp_eatOctalDigit(state)) {
  26472. var n1 = state.lastIntValue;
  26473. if (this.regexp_eatOctalDigit(state)) {
  26474. var n2 = state.lastIntValue;
  26475. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  26476. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  26477. } else {
  26478. state.lastIntValue = n1 * 8 + n2;
  26479. }
  26480. } else {
  26481. state.lastIntValue = n1;
  26482. }
  26483. return true
  26484. }
  26485. return false
  26486. };
  26487. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  26488. pp$8.regexp_eatOctalDigit = function(state) {
  26489. var ch = state.current();
  26490. if (isOctalDigit(ch)) {
  26491. state.lastIntValue = ch - 0x30; /* 0 */
  26492. state.advance();
  26493. return true
  26494. }
  26495. state.lastIntValue = 0;
  26496. return false
  26497. };
  26498. function isOctalDigit(ch) {
  26499. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  26500. }
  26501. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  26502. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  26503. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  26504. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  26505. var start = state.pos;
  26506. state.lastIntValue = 0;
  26507. for (var i = 0; i < length; ++i) {
  26508. var ch = state.current();
  26509. if (!isHexDigit(ch)) {
  26510. state.pos = start;
  26511. return false
  26512. }
  26513. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  26514. state.advance();
  26515. }
  26516. return true
  26517. };
  26518. // Object type used to represent tokens. Note that normally, tokens
  26519. // simply exist as properties on the parser object. This is only
  26520. // used for the onToken callback and the external tokenizer.
  26521. var Token = function Token(p) {
  26522. this.type = p.type;
  26523. this.value = p.value;
  26524. this.start = p.start;
  26525. this.end = p.end;
  26526. if (p.options.locations)
  26527. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  26528. if (p.options.ranges)
  26529. { this.range = [p.start, p.end]; }
  26530. };
  26531. // ## Tokenizer
  26532. var pp$9 = Parser.prototype;
  26533. // Move to the next token
  26534. pp$9.next = function() {
  26535. if (this.options.onToken)
  26536. { this.options.onToken(new Token(this)); }
  26537. this.lastTokEnd = this.end;
  26538. this.lastTokStart = this.start;
  26539. this.lastTokEndLoc = this.endLoc;
  26540. this.lastTokStartLoc = this.startLoc;
  26541. this.nextToken();
  26542. };
  26543. pp$9.getToken = function() {
  26544. this.next();
  26545. return new Token(this)
  26546. };
  26547. // If we're in an ES6 environment, make parsers iterable
  26548. if (typeof Symbol !== "undefined")
  26549. { pp$9[Symbol.iterator] = function() {
  26550. var this$1 = this;
  26551. return {
  26552. next: function () {
  26553. var token = this$1.getToken();
  26554. return {
  26555. done: token.type === types$2.eof,
  26556. value: token
  26557. }
  26558. }
  26559. }
  26560. }; }
  26561. // Toggle strict mode. Re-reads the next number or string to please
  26562. // pedantic tests (`"use strict"; 010;` should fail).
  26563. pp$9.curContext = function() {
  26564. return this.context[this.context.length - 1]
  26565. };
  26566. // Read a single token, updating the parser object's token-related
  26567. // properties.
  26568. pp$9.nextToken = function() {
  26569. var curContext = this.curContext();
  26570. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  26571. this.start = this.pos;
  26572. if (this.options.locations) { this.startLoc = this.curPosition(); }
  26573. if (this.pos >= this.input.length) { return this.finishToken(types$2.eof) }
  26574. if (curContext.override) { return curContext.override(this) }
  26575. else { this.readToken(this.fullCharCodeAtPos()); }
  26576. };
  26577. pp$9.readToken = function(code) {
  26578. // Identifier or keyword. '\uXXXX' sequences are allowed in
  26579. // identifiers, so '\' also dispatches to that.
  26580. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  26581. { return this.readWord() }
  26582. return this.getTokenFromCode(code)
  26583. };
  26584. pp$9.fullCharCodeAtPos = function() {
  26585. var code = this.input.charCodeAt(this.pos);
  26586. if (code <= 0xd7ff || code >= 0xe000) { return code }
  26587. var next = this.input.charCodeAt(this.pos + 1);
  26588. return (code << 10) + next - 0x35fdc00
  26589. };
  26590. pp$9.skipBlockComment = function() {
  26591. var startLoc = this.options.onComment && this.curPosition();
  26592. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  26593. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  26594. this.pos = end + 2;
  26595. if (this.options.locations) {
  26596. lineBreakG.lastIndex = start;
  26597. var match;
  26598. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  26599. ++this.curLine;
  26600. this.lineStart = match.index + match[0].length;
  26601. }
  26602. }
  26603. if (this.options.onComment)
  26604. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  26605. startLoc, this.curPosition()); }
  26606. };
  26607. pp$9.skipLineComment = function(startSkip) {
  26608. var start = this.pos;
  26609. var startLoc = this.options.onComment && this.curPosition();
  26610. var ch = this.input.charCodeAt(this.pos += startSkip);
  26611. while (this.pos < this.input.length && !isNewLine(ch)) {
  26612. ch = this.input.charCodeAt(++this.pos);
  26613. }
  26614. if (this.options.onComment)
  26615. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  26616. startLoc, this.curPosition()); }
  26617. };
  26618. // Called at the start of the parse and after every token. Skips
  26619. // whitespace and comments, and.
  26620. pp$9.skipSpace = function() {
  26621. loop: while (this.pos < this.input.length) {
  26622. var ch = this.input.charCodeAt(this.pos);
  26623. switch (ch) {
  26624. case 32: case 160: // ' '
  26625. ++this.pos;
  26626. break
  26627. case 13:
  26628. if (this.input.charCodeAt(this.pos + 1) === 10) {
  26629. ++this.pos;
  26630. }
  26631. case 10: case 8232: case 8233:
  26632. ++this.pos;
  26633. if (this.options.locations) {
  26634. ++this.curLine;
  26635. this.lineStart = this.pos;
  26636. }
  26637. break
  26638. case 47: // '/'
  26639. switch (this.input.charCodeAt(this.pos + 1)) {
  26640. case 42: // '*'
  26641. this.skipBlockComment();
  26642. break
  26643. case 47:
  26644. this.skipLineComment(2);
  26645. break
  26646. default:
  26647. break loop
  26648. }
  26649. break
  26650. default:
  26651. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  26652. ++this.pos;
  26653. } else {
  26654. break loop
  26655. }
  26656. }
  26657. }
  26658. };
  26659. // Called at the end of every token. Sets `end`, `val`, and
  26660. // maintains `context` and `exprAllowed`, and skips the space after
  26661. // the token, so that the next one's `start` will point at the
  26662. // right position.
  26663. pp$9.finishToken = function(type, val) {
  26664. this.end = this.pos;
  26665. if (this.options.locations) { this.endLoc = this.curPosition(); }
  26666. var prevType = this.type;
  26667. this.type = type;
  26668. this.value = val;
  26669. this.updateContext(prevType);
  26670. };
  26671. // ### Token reading
  26672. // This is the function that is called to fetch the next token. It
  26673. // is somewhat obscure, because it works in character codes rather
  26674. // than characters, and because operator parsing has been inlined
  26675. // into it.
  26676. //
  26677. // All in the name of speed.
  26678. //
  26679. pp$9.readToken_dot = function() {
  26680. var next = this.input.charCodeAt(this.pos + 1);
  26681. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  26682. var next2 = this.input.charCodeAt(this.pos + 2);
  26683. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  26684. this.pos += 3;
  26685. return this.finishToken(types$2.ellipsis)
  26686. } else {
  26687. ++this.pos;
  26688. return this.finishToken(types$2.dot)
  26689. }
  26690. };
  26691. pp$9.readToken_slash = function() { // '/'
  26692. var next = this.input.charCodeAt(this.pos + 1);
  26693. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  26694. if (next === 61) { return this.finishOp(types$2.assign, 2) }
  26695. return this.finishOp(types$2.slash, 1)
  26696. };
  26697. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  26698. var next = this.input.charCodeAt(this.pos + 1);
  26699. var size = 1;
  26700. var tokentype = code === 42 ? types$2.star : types$2.modulo;
  26701. // exponentiation operator ** and **=
  26702. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  26703. ++size;
  26704. tokentype = types$2.starstar;
  26705. next = this.input.charCodeAt(this.pos + 2);
  26706. }
  26707. if (next === 61) { return this.finishOp(types$2.assign, size + 1) }
  26708. return this.finishOp(tokentype, size)
  26709. };
  26710. pp$9.readToken_pipe_amp = function(code) { // '|&'
  26711. var next = this.input.charCodeAt(this.pos + 1);
  26712. if (next === code) { return this.finishOp(code === 124 ? types$2.logicalOR : types$2.logicalAND, 2) }
  26713. if (next === 61) { return this.finishOp(types$2.assign, 2) }
  26714. return this.finishOp(code === 124 ? types$2.bitwiseOR : types$2.bitwiseAND, 1)
  26715. };
  26716. pp$9.readToken_caret = function() { // '^'
  26717. var next = this.input.charCodeAt(this.pos + 1);
  26718. if (next === 61) { return this.finishOp(types$2.assign, 2) }
  26719. return this.finishOp(types$2.bitwiseXOR, 1)
  26720. };
  26721. pp$9.readToken_plus_min = function(code) { // '+-'
  26722. var next = this.input.charCodeAt(this.pos + 1);
  26723. if (next === code) {
  26724. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  26725. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  26726. // A `-->` line comment
  26727. this.skipLineComment(3);
  26728. this.skipSpace();
  26729. return this.nextToken()
  26730. }
  26731. return this.finishOp(types$2.incDec, 2)
  26732. }
  26733. if (next === 61) { return this.finishOp(types$2.assign, 2) }
  26734. return this.finishOp(types$2.plusMin, 1)
  26735. };
  26736. pp$9.readToken_lt_gt = function(code) { // '<>'
  26737. var next = this.input.charCodeAt(this.pos + 1);
  26738. var size = 1;
  26739. if (next === code) {
  26740. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  26741. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$2.assign, size + 1) }
  26742. return this.finishOp(types$2.bitShift, size)
  26743. }
  26744. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  26745. this.input.charCodeAt(this.pos + 3) === 45) {
  26746. // `<!--`, an XML-style comment that should be interpreted as a line comment
  26747. this.skipLineComment(4);
  26748. this.skipSpace();
  26749. return this.nextToken()
  26750. }
  26751. if (next === 61) { size = 2; }
  26752. return this.finishOp(types$2.relational, size)
  26753. };
  26754. pp$9.readToken_eq_excl = function(code) { // '=!'
  26755. var next = this.input.charCodeAt(this.pos + 1);
  26756. if (next === 61) { return this.finishOp(types$2.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  26757. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  26758. this.pos += 2;
  26759. return this.finishToken(types$2.arrow)
  26760. }
  26761. return this.finishOp(code === 61 ? types$2.eq : types$2.prefix, 1)
  26762. };
  26763. pp$9.getTokenFromCode = function(code) {
  26764. switch (code) {
  26765. // The interpretation of a dot depends on whether it is followed
  26766. // by a digit or another two dots.
  26767. case 46: // '.'
  26768. return this.readToken_dot()
  26769. // Punctuation tokens.
  26770. case 40: ++this.pos; return this.finishToken(types$2.parenL)
  26771. case 41: ++this.pos; return this.finishToken(types$2.parenR)
  26772. case 59: ++this.pos; return this.finishToken(types$2.semi)
  26773. case 44: ++this.pos; return this.finishToken(types$2.comma)
  26774. case 91: ++this.pos; return this.finishToken(types$2.bracketL)
  26775. case 93: ++this.pos; return this.finishToken(types$2.bracketR)
  26776. case 123: ++this.pos; return this.finishToken(types$2.braceL)
  26777. case 125: ++this.pos; return this.finishToken(types$2.braceR)
  26778. case 58: ++this.pos; return this.finishToken(types$2.colon)
  26779. case 63: ++this.pos; return this.finishToken(types$2.question)
  26780. case 96: // '`'
  26781. if (this.options.ecmaVersion < 6) { break }
  26782. ++this.pos;
  26783. return this.finishToken(types$2.backQuote)
  26784. case 48: // '0'
  26785. var next = this.input.charCodeAt(this.pos + 1);
  26786. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  26787. if (this.options.ecmaVersion >= 6) {
  26788. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  26789. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  26790. }
  26791. // Anything else beginning with a digit is an integer, octal
  26792. // number, or float.
  26793. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  26794. return this.readNumber(false)
  26795. // Quotes produce strings.
  26796. case 34: case 39: // '"', "'"
  26797. return this.readString(code)
  26798. // Operators are parsed inline in tiny state machines. '=' (61) is
  26799. // often referred to. `finishOp` simply skips the amount of
  26800. // characters it is given as second argument, and returns a token
  26801. // of the type given by its first argument.
  26802. case 47: // '/'
  26803. return this.readToken_slash()
  26804. case 37: case 42: // '%*'
  26805. return this.readToken_mult_modulo_exp(code)
  26806. case 124: case 38: // '|&'
  26807. return this.readToken_pipe_amp(code)
  26808. case 94: // '^'
  26809. return this.readToken_caret()
  26810. case 43: case 45: // '+-'
  26811. return this.readToken_plus_min(code)
  26812. case 60: case 62: // '<>'
  26813. return this.readToken_lt_gt(code)
  26814. case 61: case 33: // '=!'
  26815. return this.readToken_eq_excl(code)
  26816. case 126: // '~'
  26817. return this.finishOp(types$2.prefix, 1)
  26818. }
  26819. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  26820. };
  26821. pp$9.finishOp = function(type, size) {
  26822. var str = this.input.slice(this.pos, this.pos + size);
  26823. this.pos += size;
  26824. return this.finishToken(type, str)
  26825. };
  26826. pp$9.readRegexp = function() {
  26827. var escaped, inClass, start = this.pos;
  26828. for (;;) {
  26829. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  26830. var ch = this.input.charAt(this.pos);
  26831. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  26832. if (!escaped) {
  26833. if (ch === "[") { inClass = true; }
  26834. else if (ch === "]" && inClass) { inClass = false; }
  26835. else if (ch === "/" && !inClass) { break }
  26836. escaped = ch === "\\";
  26837. } else { escaped = false; }
  26838. ++this.pos;
  26839. }
  26840. var pattern = this.input.slice(start, this.pos);
  26841. ++this.pos;
  26842. var flagsStart = this.pos;
  26843. var flags = this.readWord1();
  26844. if (this.containsEsc) { this.unexpected(flagsStart); }
  26845. // Validate pattern
  26846. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  26847. state.reset(start, pattern, flags);
  26848. this.validateRegExpFlags(state);
  26849. this.validateRegExpPattern(state);
  26850. // Create Literal#value property value.
  26851. var value = null;
  26852. try {
  26853. value = new RegExp(pattern, flags);
  26854. } catch (e) {
  26855. // ESTree requires null if it failed to instantiate RegExp object.
  26856. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  26857. }
  26858. return this.finishToken(types$2.regexp, {pattern: pattern, flags: flags, value: value})
  26859. };
  26860. // Read an integer in the given radix. Return null if zero digits
  26861. // were read, the integer value otherwise. When `len` is given, this
  26862. // will return `null` unless the integer has exactly `len` digits.
  26863. pp$9.readInt = function(radix, len) {
  26864. var start = this.pos, total = 0;
  26865. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  26866. var code = this.input.charCodeAt(this.pos), val = (void 0);
  26867. if (code >= 97) { val = code - 97 + 10; } // a
  26868. else if (code >= 65) { val = code - 65 + 10; } // A
  26869. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  26870. else { val = Infinity; }
  26871. if (val >= radix) { break }
  26872. ++this.pos;
  26873. total = total * radix + val;
  26874. }
  26875. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  26876. return total
  26877. };
  26878. pp$9.readRadixNumber = function(radix) {
  26879. var start = this.pos;
  26880. this.pos += 2; // 0x
  26881. var val = this.readInt(radix);
  26882. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  26883. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  26884. val = typeof BigInt !== "undefined" ? BigInt(this.input.slice(start, this.pos)) : null;
  26885. ++this.pos;
  26886. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26887. return this.finishToken(types$2.num, val)
  26888. };
  26889. // Read an integer, octal integer, or floating-point number.
  26890. pp$9.readNumber = function(startsWithDot) {
  26891. var start = this.pos;
  26892. if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  26893. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  26894. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  26895. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  26896. var next = this.input.charCodeAt(this.pos);
  26897. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  26898. var str$1 = this.input.slice(start, this.pos);
  26899. var val$1 = typeof BigInt !== "undefined" ? BigInt(str$1) : null;
  26900. ++this.pos;
  26901. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26902. return this.finishToken(types$2.num, val$1)
  26903. }
  26904. if (next === 46 && !octal) { // '.'
  26905. ++this.pos;
  26906. this.readInt(10);
  26907. next = this.input.charCodeAt(this.pos);
  26908. }
  26909. if ((next === 69 || next === 101) && !octal) { // 'eE'
  26910. next = this.input.charCodeAt(++this.pos);
  26911. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  26912. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  26913. }
  26914. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26915. var str = this.input.slice(start, this.pos);
  26916. var val = octal ? parseInt(str, 8) : parseFloat(str);
  26917. return this.finishToken(types$2.num, val)
  26918. };
  26919. // Read a string value, interpreting backslash-escapes.
  26920. pp$9.readCodePoint = function() {
  26921. var ch = this.input.charCodeAt(this.pos), code;
  26922. if (ch === 123) { // '{'
  26923. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  26924. var codePos = ++this.pos;
  26925. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  26926. ++this.pos;
  26927. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  26928. } else {
  26929. code = this.readHexChar(4);
  26930. }
  26931. return code
  26932. };
  26933. function codePointToString$1(code) {
  26934. // UTF-16 Decoding
  26935. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  26936. code -= 0x10000;
  26937. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  26938. }
  26939. pp$9.readString = function(quote) {
  26940. var out = "", chunkStart = ++this.pos;
  26941. for (;;) {
  26942. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  26943. var ch = this.input.charCodeAt(this.pos);
  26944. if (ch === quote) { break }
  26945. if (ch === 92) { // '\'
  26946. out += this.input.slice(chunkStart, this.pos);
  26947. out += this.readEscapedChar(false);
  26948. chunkStart = this.pos;
  26949. } else {
  26950. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  26951. ++this.pos;
  26952. }
  26953. }
  26954. out += this.input.slice(chunkStart, this.pos++);
  26955. return this.finishToken(types$2.string, out)
  26956. };
  26957. // Reads template string tokens.
  26958. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  26959. pp$9.tryReadTemplateToken = function() {
  26960. this.inTemplateElement = true;
  26961. try {
  26962. this.readTmplToken();
  26963. } catch (err) {
  26964. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  26965. this.readInvalidTemplateToken();
  26966. } else {
  26967. throw err
  26968. }
  26969. }
  26970. this.inTemplateElement = false;
  26971. };
  26972. pp$9.invalidStringToken = function(position, message) {
  26973. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  26974. throw INVALID_TEMPLATE_ESCAPE_ERROR
  26975. } else {
  26976. this.raise(position, message);
  26977. }
  26978. };
  26979. pp$9.readTmplToken = function() {
  26980. var out = "", chunkStart = this.pos;
  26981. for (;;) {
  26982. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  26983. var ch = this.input.charCodeAt(this.pos);
  26984. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  26985. if (this.pos === this.start && (this.type === types$2.template || this.type === types$2.invalidTemplate)) {
  26986. if (ch === 36) {
  26987. this.pos += 2;
  26988. return this.finishToken(types$2.dollarBraceL)
  26989. } else {
  26990. ++this.pos;
  26991. return this.finishToken(types$2.backQuote)
  26992. }
  26993. }
  26994. out += this.input.slice(chunkStart, this.pos);
  26995. return this.finishToken(types$2.template, out)
  26996. }
  26997. if (ch === 92) { // '\'
  26998. out += this.input.slice(chunkStart, this.pos);
  26999. out += this.readEscapedChar(true);
  27000. chunkStart = this.pos;
  27001. } else if (isNewLine(ch)) {
  27002. out += this.input.slice(chunkStart, this.pos);
  27003. ++this.pos;
  27004. switch (ch) {
  27005. case 13:
  27006. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  27007. case 10:
  27008. out += "\n";
  27009. break
  27010. default:
  27011. out += String.fromCharCode(ch);
  27012. break
  27013. }
  27014. if (this.options.locations) {
  27015. ++this.curLine;
  27016. this.lineStart = this.pos;
  27017. }
  27018. chunkStart = this.pos;
  27019. } else {
  27020. ++this.pos;
  27021. }
  27022. }
  27023. };
  27024. // Reads a template token to search for the end, without validating any escape sequences
  27025. pp$9.readInvalidTemplateToken = function() {
  27026. for (; this.pos < this.input.length; this.pos++) {
  27027. switch (this.input[this.pos]) {
  27028. case "\\":
  27029. ++this.pos;
  27030. break
  27031. case "$":
  27032. if (this.input[this.pos + 1] !== "{") {
  27033. break
  27034. }
  27035. // falls through
  27036. case "`":
  27037. return this.finishToken(types$2.invalidTemplate, this.input.slice(this.start, this.pos))
  27038. // no default
  27039. }
  27040. }
  27041. this.raise(this.start, "Unterminated template");
  27042. };
  27043. // Used to read escaped characters
  27044. pp$9.readEscapedChar = function(inTemplate) {
  27045. var ch = this.input.charCodeAt(++this.pos);
  27046. ++this.pos;
  27047. switch (ch) {
  27048. case 110: return "\n" // 'n' -> '\n'
  27049. case 114: return "\r" // 'r' -> '\r'
  27050. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  27051. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  27052. case 116: return "\t" // 't' -> '\t'
  27053. case 98: return "\b" // 'b' -> '\b'
  27054. case 118: return "\u000b" // 'v' -> '\u000b'
  27055. case 102: return "\f" // 'f' -> '\f'
  27056. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  27057. case 10: // ' \n'
  27058. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  27059. return ""
  27060. default:
  27061. if (ch >= 48 && ch <= 55) {
  27062. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  27063. var octal = parseInt(octalStr, 8);
  27064. if (octal > 255) {
  27065. octalStr = octalStr.slice(0, -1);
  27066. octal = parseInt(octalStr, 8);
  27067. }
  27068. this.pos += octalStr.length - 1;
  27069. ch = this.input.charCodeAt(this.pos);
  27070. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  27071. this.invalidStringToken(
  27072. this.pos - 1 - octalStr.length,
  27073. inTemplate
  27074. ? "Octal literal in template string"
  27075. : "Octal literal in strict mode"
  27076. );
  27077. }
  27078. return String.fromCharCode(octal)
  27079. }
  27080. if (isNewLine(ch)) {
  27081. // Unicode new line characters after \ get removed from output in both
  27082. // template literals and strings
  27083. return ""
  27084. }
  27085. return String.fromCharCode(ch)
  27086. }
  27087. };
  27088. // Used to read character escape sequences ('\x', '\u', '\U').
  27089. pp$9.readHexChar = function(len) {
  27090. var codePos = this.pos;
  27091. var n = this.readInt(16, len);
  27092. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  27093. return n
  27094. };
  27095. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  27096. // to whether the word contained a '\u' escape.
  27097. //
  27098. // Incrementally adds only escaped chars, adding other chunks as-is
  27099. // as a micro-optimization.
  27100. pp$9.readWord1 = function() {
  27101. this.containsEsc = false;
  27102. var word = "", first = true, chunkStart = this.pos;
  27103. var astral = this.options.ecmaVersion >= 6;
  27104. while (this.pos < this.input.length) {
  27105. var ch = this.fullCharCodeAtPos();
  27106. if (isIdentifierChar(ch, astral)) {
  27107. this.pos += ch <= 0xffff ? 1 : 2;
  27108. } else if (ch === 92) { // "\"
  27109. this.containsEsc = true;
  27110. word += this.input.slice(chunkStart, this.pos);
  27111. var escStart = this.pos;
  27112. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  27113. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  27114. ++this.pos;
  27115. var esc = this.readCodePoint();
  27116. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  27117. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  27118. word += codePointToString$1(esc);
  27119. chunkStart = this.pos;
  27120. } else {
  27121. break
  27122. }
  27123. first = false;
  27124. }
  27125. return word + this.input.slice(chunkStart, this.pos)
  27126. };
  27127. // Read an identifier or keyword token. Will check for reserved
  27128. // words when necessary.
  27129. pp$9.readWord = function() {
  27130. var word = this.readWord1();
  27131. var type = types$2.name;
  27132. if (this.keywords.test(word)) {
  27133. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
  27134. type = keywords$1[word];
  27135. }
  27136. return this.finishToken(type, word)
  27137. };
  27138. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  27139. var version = "7.1.0";
  27140. Parser.acorn = {
  27141. Parser: Parser,
  27142. version: version,
  27143. defaultOptions: defaultOptions,
  27144. Position: Position,
  27145. SourceLocation: SourceLocation,
  27146. getLineInfo: getLineInfo,
  27147. Node: Node,
  27148. TokenType: TokenType,
  27149. tokTypes: types$2,
  27150. keywordTypes: keywords$1,
  27151. TokContext: TokContext,
  27152. tokContexts: types$1$1,
  27153. isIdentifierChar: isIdentifierChar,
  27154. isIdentifierStart: isIdentifierStart,
  27155. Token: Token,
  27156. isNewLine: isNewLine,
  27157. lineBreak: lineBreak,
  27158. lineBreakG: lineBreakG,
  27159. nonASCIIwhitespace: nonASCIIwhitespace
  27160. };
  27161. /**
  27162. * Parse a js source to generate the AST
  27163. * @param {string} source - javascript source
  27164. * @param {Object} options - parser options
  27165. * @returns {AST} AST tree
  27166. */
  27167. function generateAST(source, options) {
  27168. return main_2$1(source, {
  27169. parser: {
  27170. parse(source, opts) {
  27171. return Parser.parse(source, {
  27172. ...opts,
  27173. ecmaVersion: 2020
  27174. })
  27175. }
  27176. },
  27177. ...options
  27178. })
  27179. }
  27180. var builtin = {
  27181. "Array": false,
  27182. "ArrayBuffer": false,
  27183. Atomics: false,
  27184. BigInt: false,
  27185. BigInt64Array: false,
  27186. BigUint64Array: false,
  27187. "Boolean": false,
  27188. constructor: false,
  27189. "DataView": false,
  27190. "Date": false,
  27191. "decodeURI": false,
  27192. "decodeURIComponent": false,
  27193. "encodeURI": false,
  27194. "encodeURIComponent": false,
  27195. "Error": false,
  27196. "escape": false,
  27197. "eval": false,
  27198. "EvalError": false,
  27199. "Float32Array": false,
  27200. "Float64Array": false,
  27201. "Function": false,
  27202. globalThis: false,
  27203. hasOwnProperty: false,
  27204. "Infinity": false,
  27205. "Int16Array": false,
  27206. "Int32Array": false,
  27207. "Int8Array": false,
  27208. "isFinite": false,
  27209. "isNaN": false,
  27210. isPrototypeOf: false,
  27211. "JSON": false,
  27212. "Map": false,
  27213. "Math": false,
  27214. "NaN": false,
  27215. "Number": false,
  27216. "Object": false,
  27217. "parseFloat": false,
  27218. "parseInt": false,
  27219. "Promise": false,
  27220. propertyIsEnumerable: false,
  27221. "Proxy": false,
  27222. "RangeError": false,
  27223. "ReferenceError": false,
  27224. "Reflect": false,
  27225. "RegExp": false,
  27226. "Set": false,
  27227. SharedArrayBuffer: false,
  27228. "String": false,
  27229. "Symbol": false,
  27230. "SyntaxError": false,
  27231. toLocaleString: false,
  27232. toString: false,
  27233. "TypeError": false,
  27234. "Uint16Array": false,
  27235. "Uint32Array": false,
  27236. "Uint8Array": false,
  27237. "Uint8ClampedArray": false,
  27238. "undefined": false,
  27239. "unescape": false,
  27240. "URIError": false,
  27241. valueOf: false,
  27242. "WeakMap": false,
  27243. "WeakSet": false
  27244. };
  27245. var es5 = {
  27246. "Array": false,
  27247. "Boolean": false,
  27248. constructor: false,
  27249. "Date": false,
  27250. "decodeURI": false,
  27251. "decodeURIComponent": false,
  27252. "encodeURI": false,
  27253. "encodeURIComponent": false,
  27254. "Error": false,
  27255. "escape": false,
  27256. "eval": false,
  27257. "EvalError": false,
  27258. "Function": false,
  27259. hasOwnProperty: false,
  27260. "Infinity": false,
  27261. "isFinite": false,
  27262. "isNaN": false,
  27263. isPrototypeOf: false,
  27264. "JSON": false,
  27265. "Math": false,
  27266. "NaN": false,
  27267. "Number": false,
  27268. "Object": false,
  27269. "parseFloat": false,
  27270. "parseInt": false,
  27271. propertyIsEnumerable: false,
  27272. "RangeError": false,
  27273. "ReferenceError": false,
  27274. "RegExp": false,
  27275. "String": false,
  27276. "SyntaxError": false,
  27277. toLocaleString: false,
  27278. toString: false,
  27279. "TypeError": false,
  27280. "undefined": false,
  27281. "unescape": false,
  27282. "URIError": false,
  27283. valueOf: false
  27284. };
  27285. var es2015 = {
  27286. "Array": false,
  27287. "ArrayBuffer": false,
  27288. "Boolean": false,
  27289. constructor: false,
  27290. "DataView": false,
  27291. "Date": false,
  27292. "decodeURI": false,
  27293. "decodeURIComponent": false,
  27294. "encodeURI": false,
  27295. "encodeURIComponent": false,
  27296. "Error": false,
  27297. "escape": false,
  27298. "eval": false,
  27299. "EvalError": false,
  27300. "Float32Array": false,
  27301. "Float64Array": false,
  27302. "Function": false,
  27303. hasOwnProperty: false,
  27304. "Infinity": false,
  27305. "Int16Array": false,
  27306. "Int32Array": false,
  27307. "Int8Array": false,
  27308. "isFinite": false,
  27309. "isNaN": false,
  27310. isPrototypeOf: false,
  27311. "JSON": false,
  27312. "Map": false,
  27313. "Math": false,
  27314. "NaN": false,
  27315. "Number": false,
  27316. "Object": false,
  27317. "parseFloat": false,
  27318. "parseInt": false,
  27319. "Promise": false,
  27320. propertyIsEnumerable: false,
  27321. "Proxy": false,
  27322. "RangeError": false,
  27323. "ReferenceError": false,
  27324. "Reflect": false,
  27325. "RegExp": false,
  27326. "Set": false,
  27327. "String": false,
  27328. "Symbol": false,
  27329. "SyntaxError": false,
  27330. toLocaleString: false,
  27331. toString: false,
  27332. "TypeError": false,
  27333. "Uint16Array": false,
  27334. "Uint32Array": false,
  27335. "Uint8Array": false,
  27336. "Uint8ClampedArray": false,
  27337. "undefined": false,
  27338. "unescape": false,
  27339. "URIError": false,
  27340. valueOf: false,
  27341. "WeakMap": false,
  27342. "WeakSet": false
  27343. };
  27344. var es2017 = {
  27345. "Array": false,
  27346. "ArrayBuffer": false,
  27347. Atomics: false,
  27348. "Boolean": false,
  27349. constructor: false,
  27350. "DataView": false,
  27351. "Date": false,
  27352. "decodeURI": false,
  27353. "decodeURIComponent": false,
  27354. "encodeURI": false,
  27355. "encodeURIComponent": false,
  27356. "Error": false,
  27357. "escape": false,
  27358. "eval": false,
  27359. "EvalError": false,
  27360. "Float32Array": false,
  27361. "Float64Array": false,
  27362. "Function": false,
  27363. hasOwnProperty: false,
  27364. "Infinity": false,
  27365. "Int16Array": false,
  27366. "Int32Array": false,
  27367. "Int8Array": false,
  27368. "isFinite": false,
  27369. "isNaN": false,
  27370. isPrototypeOf: false,
  27371. "JSON": false,
  27372. "Map": false,
  27373. "Math": false,
  27374. "NaN": false,
  27375. "Number": false,
  27376. "Object": false,
  27377. "parseFloat": false,
  27378. "parseInt": false,
  27379. "Promise": false,
  27380. propertyIsEnumerable: false,
  27381. "Proxy": false,
  27382. "RangeError": false,
  27383. "ReferenceError": false,
  27384. "Reflect": false,
  27385. "RegExp": false,
  27386. "Set": false,
  27387. SharedArrayBuffer: false,
  27388. "String": false,
  27389. "Symbol": false,
  27390. "SyntaxError": false,
  27391. toLocaleString: false,
  27392. toString: false,
  27393. "TypeError": false,
  27394. "Uint16Array": false,
  27395. "Uint32Array": false,
  27396. "Uint8Array": false,
  27397. "Uint8ClampedArray": false,
  27398. "undefined": false,
  27399. "unescape": false,
  27400. "URIError": false,
  27401. valueOf: false,
  27402. "WeakMap": false,
  27403. "WeakSet": false
  27404. };
  27405. var browser = {
  27406. AbortController: false,
  27407. AbortSignal: false,
  27408. addEventListener: false,
  27409. alert: false,
  27410. AnalyserNode: false,
  27411. Animation: false,
  27412. AnimationEffectReadOnly: false,
  27413. AnimationEffectTiming: false,
  27414. AnimationEffectTimingReadOnly: false,
  27415. AnimationEvent: false,
  27416. AnimationPlaybackEvent: false,
  27417. AnimationTimeline: false,
  27418. applicationCache: false,
  27419. ApplicationCache: false,
  27420. ApplicationCacheErrorEvent: false,
  27421. atob: false,
  27422. Attr: false,
  27423. Audio: false,
  27424. AudioBuffer: false,
  27425. AudioBufferSourceNode: false,
  27426. AudioContext: false,
  27427. AudioDestinationNode: false,
  27428. AudioListener: false,
  27429. AudioNode: false,
  27430. AudioParam: false,
  27431. AudioProcessingEvent: false,
  27432. AudioScheduledSourceNode: false,
  27433. "AudioWorkletGlobalScope ": false,
  27434. AudioWorkletNode: false,
  27435. AudioWorkletProcessor: false,
  27436. BarProp: false,
  27437. BaseAudioContext: false,
  27438. BatteryManager: false,
  27439. BeforeUnloadEvent: false,
  27440. BiquadFilterNode: false,
  27441. Blob: false,
  27442. BlobEvent: false,
  27443. blur: false,
  27444. BroadcastChannel: false,
  27445. btoa: false,
  27446. BudgetService: false,
  27447. ByteLengthQueuingStrategy: false,
  27448. Cache: false,
  27449. caches: false,
  27450. CacheStorage: false,
  27451. cancelAnimationFrame: false,
  27452. cancelIdleCallback: false,
  27453. CanvasCaptureMediaStreamTrack: false,
  27454. CanvasGradient: false,
  27455. CanvasPattern: false,
  27456. CanvasRenderingContext2D: false,
  27457. ChannelMergerNode: false,
  27458. ChannelSplitterNode: false,
  27459. CharacterData: false,
  27460. clearInterval: false,
  27461. clearTimeout: false,
  27462. clientInformation: false,
  27463. ClipboardEvent: false,
  27464. close: false,
  27465. closed: false,
  27466. CloseEvent: false,
  27467. Comment: false,
  27468. CompositionEvent: false,
  27469. confirm: false,
  27470. console: false,
  27471. ConstantSourceNode: false,
  27472. ConvolverNode: false,
  27473. CountQueuingStrategy: false,
  27474. createImageBitmap: false,
  27475. Credential: false,
  27476. CredentialsContainer: false,
  27477. crypto: false,
  27478. Crypto: false,
  27479. CryptoKey: false,
  27480. CSS: false,
  27481. CSSConditionRule: false,
  27482. CSSFontFaceRule: false,
  27483. CSSGroupingRule: false,
  27484. CSSImportRule: false,
  27485. CSSKeyframeRule: false,
  27486. CSSKeyframesRule: false,
  27487. CSSMediaRule: false,
  27488. CSSNamespaceRule: false,
  27489. CSSPageRule: false,
  27490. CSSRule: false,
  27491. CSSRuleList: false,
  27492. CSSStyleDeclaration: false,
  27493. CSSStyleRule: false,
  27494. CSSStyleSheet: false,
  27495. CSSSupportsRule: false,
  27496. CustomElementRegistry: false,
  27497. customElements: false,
  27498. CustomEvent: false,
  27499. DataTransfer: false,
  27500. DataTransferItem: false,
  27501. DataTransferItemList: false,
  27502. defaultstatus: false,
  27503. defaultStatus: false,
  27504. DelayNode: false,
  27505. DeviceMotionEvent: false,
  27506. DeviceOrientationEvent: false,
  27507. devicePixelRatio: false,
  27508. dispatchEvent: false,
  27509. document: false,
  27510. Document: false,
  27511. DocumentFragment: false,
  27512. DocumentType: false,
  27513. DOMError: false,
  27514. DOMException: false,
  27515. DOMImplementation: false,
  27516. DOMMatrix: false,
  27517. DOMMatrixReadOnly: false,
  27518. DOMParser: false,
  27519. DOMPoint: false,
  27520. DOMPointReadOnly: false,
  27521. DOMQuad: false,
  27522. DOMRect: false,
  27523. DOMRectReadOnly: false,
  27524. DOMStringList: false,
  27525. DOMStringMap: false,
  27526. DOMTokenList: false,
  27527. DragEvent: false,
  27528. DynamicsCompressorNode: false,
  27529. Element: false,
  27530. ErrorEvent: false,
  27531. event: false,
  27532. Event: false,
  27533. EventSource: false,
  27534. EventTarget: false,
  27535. external: false,
  27536. fetch: false,
  27537. File: false,
  27538. FileList: false,
  27539. FileReader: false,
  27540. find: false,
  27541. focus: false,
  27542. FocusEvent: false,
  27543. FontFace: false,
  27544. FontFaceSetLoadEvent: false,
  27545. FormData: false,
  27546. frameElement: false,
  27547. frames: false,
  27548. GainNode: false,
  27549. Gamepad: false,
  27550. GamepadButton: false,
  27551. GamepadEvent: false,
  27552. getComputedStyle: false,
  27553. getSelection: false,
  27554. HashChangeEvent: false,
  27555. Headers: false,
  27556. history: false,
  27557. History: false,
  27558. HTMLAllCollection: false,
  27559. HTMLAnchorElement: false,
  27560. HTMLAreaElement: false,
  27561. HTMLAudioElement: false,
  27562. HTMLBaseElement: false,
  27563. HTMLBodyElement: false,
  27564. HTMLBRElement: false,
  27565. HTMLButtonElement: false,
  27566. HTMLCanvasElement: false,
  27567. HTMLCollection: false,
  27568. HTMLContentElement: false,
  27569. HTMLDataElement: false,
  27570. HTMLDataListElement: false,
  27571. HTMLDetailsElement: false,
  27572. HTMLDialogElement: false,
  27573. HTMLDirectoryElement: false,
  27574. HTMLDivElement: false,
  27575. HTMLDListElement: false,
  27576. HTMLDocument: false,
  27577. HTMLElement: false,
  27578. HTMLEmbedElement: false,
  27579. HTMLFieldSetElement: false,
  27580. HTMLFontElement: false,
  27581. HTMLFormControlsCollection: false,
  27582. HTMLFormElement: false,
  27583. HTMLFrameElement: false,
  27584. HTMLFrameSetElement: false,
  27585. HTMLHeadElement: false,
  27586. HTMLHeadingElement: false,
  27587. HTMLHRElement: false,
  27588. HTMLHtmlElement: false,
  27589. HTMLIFrameElement: false,
  27590. HTMLImageElement: false,
  27591. HTMLInputElement: false,
  27592. HTMLLabelElement: false,
  27593. HTMLLegendElement: false,
  27594. HTMLLIElement: false,
  27595. HTMLLinkElement: false,
  27596. HTMLMapElement: false,
  27597. HTMLMarqueeElement: false,
  27598. HTMLMediaElement: false,
  27599. HTMLMenuElement: false,
  27600. HTMLMetaElement: false,
  27601. HTMLMeterElement: false,
  27602. HTMLModElement: false,
  27603. HTMLObjectElement: false,
  27604. HTMLOListElement: false,
  27605. HTMLOptGroupElement: false,
  27606. HTMLOptionElement: false,
  27607. HTMLOptionsCollection: false,
  27608. HTMLOutputElement: false,
  27609. HTMLParagraphElement: false,
  27610. HTMLParamElement: false,
  27611. HTMLPictureElement: false,
  27612. HTMLPreElement: false,
  27613. HTMLProgressElement: false,
  27614. HTMLQuoteElement: false,
  27615. HTMLScriptElement: false,
  27616. HTMLSelectElement: false,
  27617. HTMLShadowElement: false,
  27618. HTMLSlotElement: false,
  27619. HTMLSourceElement: false,
  27620. HTMLSpanElement: false,
  27621. HTMLStyleElement: false,
  27622. HTMLTableCaptionElement: false,
  27623. HTMLTableCellElement: false,
  27624. HTMLTableColElement: false,
  27625. HTMLTableElement: false,
  27626. HTMLTableRowElement: false,
  27627. HTMLTableSectionElement: false,
  27628. HTMLTemplateElement: false,
  27629. HTMLTextAreaElement: false,
  27630. HTMLTimeElement: false,
  27631. HTMLTitleElement: false,
  27632. HTMLTrackElement: false,
  27633. HTMLUListElement: false,
  27634. HTMLUnknownElement: false,
  27635. HTMLVideoElement: false,
  27636. IDBCursor: false,
  27637. IDBCursorWithValue: false,
  27638. IDBDatabase: false,
  27639. IDBFactory: false,
  27640. IDBIndex: false,
  27641. IDBKeyRange: false,
  27642. IDBObjectStore: false,
  27643. IDBOpenDBRequest: false,
  27644. IDBRequest: false,
  27645. IDBTransaction: false,
  27646. IDBVersionChangeEvent: false,
  27647. IdleDeadline: false,
  27648. IIRFilterNode: false,
  27649. Image: false,
  27650. ImageBitmap: false,
  27651. ImageBitmapRenderingContext: false,
  27652. ImageCapture: false,
  27653. ImageData: false,
  27654. indexedDB: false,
  27655. innerHeight: false,
  27656. innerWidth: false,
  27657. InputEvent: false,
  27658. IntersectionObserver: false,
  27659. IntersectionObserverEntry: false,
  27660. "Intl": false,
  27661. isSecureContext: false,
  27662. KeyboardEvent: false,
  27663. KeyframeEffect: false,
  27664. KeyframeEffectReadOnly: false,
  27665. length: false,
  27666. localStorage: false,
  27667. location: true,
  27668. Location: false,
  27669. locationbar: false,
  27670. matchMedia: false,
  27671. MediaDeviceInfo: false,
  27672. MediaDevices: false,
  27673. MediaElementAudioSourceNode: false,
  27674. MediaEncryptedEvent: false,
  27675. MediaError: false,
  27676. MediaKeyMessageEvent: false,
  27677. MediaKeySession: false,
  27678. MediaKeyStatusMap: false,
  27679. MediaKeySystemAccess: false,
  27680. MediaList: false,
  27681. MediaQueryList: false,
  27682. MediaQueryListEvent: false,
  27683. MediaRecorder: false,
  27684. MediaSettingsRange: false,
  27685. MediaSource: false,
  27686. MediaStream: false,
  27687. MediaStreamAudioDestinationNode: false,
  27688. MediaStreamAudioSourceNode: false,
  27689. MediaStreamEvent: false,
  27690. MediaStreamTrack: false,
  27691. MediaStreamTrackEvent: false,
  27692. menubar: false,
  27693. MessageChannel: false,
  27694. MessageEvent: false,
  27695. MessagePort: false,
  27696. MIDIAccess: false,
  27697. MIDIConnectionEvent: false,
  27698. MIDIInput: false,
  27699. MIDIInputMap: false,
  27700. MIDIMessageEvent: false,
  27701. MIDIOutput: false,
  27702. MIDIOutputMap: false,
  27703. MIDIPort: false,
  27704. MimeType: false,
  27705. MimeTypeArray: false,
  27706. MouseEvent: false,
  27707. moveBy: false,
  27708. moveTo: false,
  27709. MutationEvent: false,
  27710. MutationObserver: false,
  27711. MutationRecord: false,
  27712. name: false,
  27713. NamedNodeMap: false,
  27714. NavigationPreloadManager: false,
  27715. navigator: false,
  27716. Navigator: false,
  27717. NetworkInformation: false,
  27718. Node: false,
  27719. NodeFilter: false,
  27720. NodeIterator: false,
  27721. NodeList: false,
  27722. Notification: false,
  27723. OfflineAudioCompletionEvent: false,
  27724. OfflineAudioContext: false,
  27725. offscreenBuffering: false,
  27726. OffscreenCanvas: true,
  27727. onabort: true,
  27728. onafterprint: true,
  27729. onanimationend: true,
  27730. onanimationiteration: true,
  27731. onanimationstart: true,
  27732. onappinstalled: true,
  27733. onauxclick: true,
  27734. onbeforeinstallprompt: true,
  27735. onbeforeprint: true,
  27736. onbeforeunload: true,
  27737. onblur: true,
  27738. oncancel: true,
  27739. oncanplay: true,
  27740. oncanplaythrough: true,
  27741. onchange: true,
  27742. onclick: true,
  27743. onclose: true,
  27744. oncontextmenu: true,
  27745. oncuechange: true,
  27746. ondblclick: true,
  27747. ondevicemotion: true,
  27748. ondeviceorientation: true,
  27749. ondeviceorientationabsolute: true,
  27750. ondrag: true,
  27751. ondragend: true,
  27752. ondragenter: true,
  27753. ondragleave: true,
  27754. ondragover: true,
  27755. ondragstart: true,
  27756. ondrop: true,
  27757. ondurationchange: true,
  27758. onemptied: true,
  27759. onended: true,
  27760. onerror: true,
  27761. onfocus: true,
  27762. ongotpointercapture: true,
  27763. onhashchange: true,
  27764. oninput: true,
  27765. oninvalid: true,
  27766. onkeydown: true,
  27767. onkeypress: true,
  27768. onkeyup: true,
  27769. onlanguagechange: true,
  27770. onload: true,
  27771. onloadeddata: true,
  27772. onloadedmetadata: true,
  27773. onloadstart: true,
  27774. onlostpointercapture: true,
  27775. onmessage: true,
  27776. onmessageerror: true,
  27777. onmousedown: true,
  27778. onmouseenter: true,
  27779. onmouseleave: true,
  27780. onmousemove: true,
  27781. onmouseout: true,
  27782. onmouseover: true,
  27783. onmouseup: true,
  27784. onmousewheel: true,
  27785. onoffline: true,
  27786. ononline: true,
  27787. onpagehide: true,
  27788. onpageshow: true,
  27789. onpause: true,
  27790. onplay: true,
  27791. onplaying: true,
  27792. onpointercancel: true,
  27793. onpointerdown: true,
  27794. onpointerenter: true,
  27795. onpointerleave: true,
  27796. onpointermove: true,
  27797. onpointerout: true,
  27798. onpointerover: true,
  27799. onpointerup: true,
  27800. onpopstate: true,
  27801. onprogress: true,
  27802. onratechange: true,
  27803. onrejectionhandled: true,
  27804. onreset: true,
  27805. onresize: true,
  27806. onscroll: true,
  27807. onsearch: true,
  27808. onseeked: true,
  27809. onseeking: true,
  27810. onselect: true,
  27811. onstalled: true,
  27812. onstorage: true,
  27813. onsubmit: true,
  27814. onsuspend: true,
  27815. ontimeupdate: true,
  27816. ontoggle: true,
  27817. ontransitionend: true,
  27818. onunhandledrejection: true,
  27819. onunload: true,
  27820. onvolumechange: true,
  27821. onwaiting: true,
  27822. onwheel: true,
  27823. open: false,
  27824. openDatabase: false,
  27825. opener: false,
  27826. Option: false,
  27827. origin: false,
  27828. OscillatorNode: false,
  27829. outerHeight: false,
  27830. outerWidth: false,
  27831. PageTransitionEvent: false,
  27832. pageXOffset: false,
  27833. pageYOffset: false,
  27834. PannerNode: false,
  27835. parent: false,
  27836. Path2D: false,
  27837. PaymentAddress: false,
  27838. PaymentRequest: false,
  27839. PaymentRequestUpdateEvent: false,
  27840. PaymentResponse: false,
  27841. performance: false,
  27842. Performance: false,
  27843. PerformanceEntry: false,
  27844. PerformanceLongTaskTiming: false,
  27845. PerformanceMark: false,
  27846. PerformanceMeasure: false,
  27847. PerformanceNavigation: false,
  27848. PerformanceNavigationTiming: false,
  27849. PerformanceObserver: false,
  27850. PerformanceObserverEntryList: false,
  27851. PerformancePaintTiming: false,
  27852. PerformanceResourceTiming: false,
  27853. PerformanceTiming: false,
  27854. PeriodicWave: false,
  27855. Permissions: false,
  27856. PermissionStatus: false,
  27857. personalbar: false,
  27858. PhotoCapabilities: false,
  27859. Plugin: false,
  27860. PluginArray: false,
  27861. PointerEvent: false,
  27862. PopStateEvent: false,
  27863. postMessage: false,
  27864. Presentation: false,
  27865. PresentationAvailability: false,
  27866. PresentationConnection: false,
  27867. PresentationConnectionAvailableEvent: false,
  27868. PresentationConnectionCloseEvent: false,
  27869. PresentationConnectionList: false,
  27870. PresentationReceiver: false,
  27871. PresentationRequest: false,
  27872. print: false,
  27873. ProcessingInstruction: false,
  27874. ProgressEvent: false,
  27875. PromiseRejectionEvent: false,
  27876. prompt: false,
  27877. PushManager: false,
  27878. PushSubscription: false,
  27879. PushSubscriptionOptions: false,
  27880. queueMicrotask: false,
  27881. RadioNodeList: false,
  27882. Range: false,
  27883. ReadableStream: false,
  27884. registerProcessor: false,
  27885. RemotePlayback: false,
  27886. removeEventListener: false,
  27887. Request: false,
  27888. requestAnimationFrame: false,
  27889. requestIdleCallback: false,
  27890. resizeBy: false,
  27891. ResizeObserver: false,
  27892. ResizeObserverEntry: false,
  27893. resizeTo: false,
  27894. Response: false,
  27895. RTCCertificate: false,
  27896. RTCDataChannel: false,
  27897. RTCDataChannelEvent: false,
  27898. RTCDtlsTransport: false,
  27899. RTCIceCandidate: false,
  27900. RTCIceGatherer: false,
  27901. RTCIceTransport: false,
  27902. RTCPeerConnection: false,
  27903. RTCPeerConnectionIceEvent: false,
  27904. RTCRtpContributingSource: false,
  27905. RTCRtpReceiver: false,
  27906. RTCRtpSender: false,
  27907. RTCSctpTransport: false,
  27908. RTCSessionDescription: false,
  27909. RTCStatsReport: false,
  27910. RTCTrackEvent: false,
  27911. screen: false,
  27912. Screen: false,
  27913. screenLeft: false,
  27914. ScreenOrientation: false,
  27915. screenTop: false,
  27916. screenX: false,
  27917. screenY: false,
  27918. ScriptProcessorNode: false,
  27919. scroll: false,
  27920. scrollbars: false,
  27921. scrollBy: false,
  27922. scrollTo: false,
  27923. scrollX: false,
  27924. scrollY: false,
  27925. SecurityPolicyViolationEvent: false,
  27926. Selection: false,
  27927. self: false,
  27928. ServiceWorker: false,
  27929. ServiceWorkerContainer: false,
  27930. ServiceWorkerRegistration: false,
  27931. sessionStorage: false,
  27932. setInterval: false,
  27933. setTimeout: false,
  27934. ShadowRoot: false,
  27935. SharedWorker: false,
  27936. SourceBuffer: false,
  27937. SourceBufferList: false,
  27938. speechSynthesis: false,
  27939. SpeechSynthesisEvent: false,
  27940. SpeechSynthesisUtterance: false,
  27941. StaticRange: false,
  27942. status: false,
  27943. statusbar: false,
  27944. StereoPannerNode: false,
  27945. stop: false,
  27946. Storage: false,
  27947. StorageEvent: false,
  27948. StorageManager: false,
  27949. styleMedia: false,
  27950. StyleSheet: false,
  27951. StyleSheetList: false,
  27952. SubtleCrypto: false,
  27953. SVGAElement: false,
  27954. SVGAngle: false,
  27955. SVGAnimatedAngle: false,
  27956. SVGAnimatedBoolean: false,
  27957. SVGAnimatedEnumeration: false,
  27958. SVGAnimatedInteger: false,
  27959. SVGAnimatedLength: false,
  27960. SVGAnimatedLengthList: false,
  27961. SVGAnimatedNumber: false,
  27962. SVGAnimatedNumberList: false,
  27963. SVGAnimatedPreserveAspectRatio: false,
  27964. SVGAnimatedRect: false,
  27965. SVGAnimatedString: false,
  27966. SVGAnimatedTransformList: false,
  27967. SVGAnimateElement: false,
  27968. SVGAnimateMotionElement: false,
  27969. SVGAnimateTransformElement: false,
  27970. SVGAnimationElement: false,
  27971. SVGCircleElement: false,
  27972. SVGClipPathElement: false,
  27973. SVGComponentTransferFunctionElement: false,
  27974. SVGDefsElement: false,
  27975. SVGDescElement: false,
  27976. SVGDiscardElement: false,
  27977. SVGElement: false,
  27978. SVGEllipseElement: false,
  27979. SVGFEBlendElement: false,
  27980. SVGFEColorMatrixElement: false,
  27981. SVGFEComponentTransferElement: false,
  27982. SVGFECompositeElement: false,
  27983. SVGFEConvolveMatrixElement: false,
  27984. SVGFEDiffuseLightingElement: false,
  27985. SVGFEDisplacementMapElement: false,
  27986. SVGFEDistantLightElement: false,
  27987. SVGFEDropShadowElement: false,
  27988. SVGFEFloodElement: false,
  27989. SVGFEFuncAElement: false,
  27990. SVGFEFuncBElement: false,
  27991. SVGFEFuncGElement: false,
  27992. SVGFEFuncRElement: false,
  27993. SVGFEGaussianBlurElement: false,
  27994. SVGFEImageElement: false,
  27995. SVGFEMergeElement: false,
  27996. SVGFEMergeNodeElement: false,
  27997. SVGFEMorphologyElement: false,
  27998. SVGFEOffsetElement: false,
  27999. SVGFEPointLightElement: false,
  28000. SVGFESpecularLightingElement: false,
  28001. SVGFESpotLightElement: false,
  28002. SVGFETileElement: false,
  28003. SVGFETurbulenceElement: false,
  28004. SVGFilterElement: false,
  28005. SVGForeignObjectElement: false,
  28006. SVGGElement: false,
  28007. SVGGeometryElement: false,
  28008. SVGGradientElement: false,
  28009. SVGGraphicsElement: false,
  28010. SVGImageElement: false,
  28011. SVGLength: false,
  28012. SVGLengthList: false,
  28013. SVGLinearGradientElement: false,
  28014. SVGLineElement: false,
  28015. SVGMarkerElement: false,
  28016. SVGMaskElement: false,
  28017. SVGMatrix: false,
  28018. SVGMetadataElement: false,
  28019. SVGMPathElement: false,
  28020. SVGNumber: false,
  28021. SVGNumberList: false,
  28022. SVGPathElement: false,
  28023. SVGPatternElement: false,
  28024. SVGPoint: false,
  28025. SVGPointList: false,
  28026. SVGPolygonElement: false,
  28027. SVGPolylineElement: false,
  28028. SVGPreserveAspectRatio: false,
  28029. SVGRadialGradientElement: false,
  28030. SVGRect: false,
  28031. SVGRectElement: false,
  28032. SVGScriptElement: false,
  28033. SVGSetElement: false,
  28034. SVGStopElement: false,
  28035. SVGStringList: false,
  28036. SVGStyleElement: false,
  28037. SVGSVGElement: false,
  28038. SVGSwitchElement: false,
  28039. SVGSymbolElement: false,
  28040. SVGTextContentElement: false,
  28041. SVGTextElement: false,
  28042. SVGTextPathElement: false,
  28043. SVGTextPositioningElement: false,
  28044. SVGTitleElement: false,
  28045. SVGTransform: false,
  28046. SVGTransformList: false,
  28047. SVGTSpanElement: false,
  28048. SVGUnitTypes: false,
  28049. SVGUseElement: false,
  28050. SVGViewElement: false,
  28051. TaskAttributionTiming: false,
  28052. Text: false,
  28053. TextDecoder: false,
  28054. TextEncoder: false,
  28055. TextEvent: false,
  28056. TextMetrics: false,
  28057. TextTrack: false,
  28058. TextTrackCue: false,
  28059. TextTrackCueList: false,
  28060. TextTrackList: false,
  28061. TimeRanges: false,
  28062. toolbar: false,
  28063. top: false,
  28064. Touch: false,
  28065. TouchEvent: false,
  28066. TouchList: false,
  28067. TrackEvent: false,
  28068. TransitionEvent: false,
  28069. TreeWalker: false,
  28070. UIEvent: false,
  28071. URL: false,
  28072. URLSearchParams: false,
  28073. ValidityState: false,
  28074. visualViewport: false,
  28075. VisualViewport: false,
  28076. VTTCue: false,
  28077. WaveShaperNode: false,
  28078. WebAssembly: false,
  28079. WebGL2RenderingContext: false,
  28080. WebGLActiveInfo: false,
  28081. WebGLBuffer: false,
  28082. WebGLContextEvent: false,
  28083. WebGLFramebuffer: false,
  28084. WebGLProgram: false,
  28085. WebGLQuery: false,
  28086. WebGLRenderbuffer: false,
  28087. WebGLRenderingContext: false,
  28088. WebGLSampler: false,
  28089. WebGLShader: false,
  28090. WebGLShaderPrecisionFormat: false,
  28091. WebGLSync: false,
  28092. WebGLTexture: false,
  28093. WebGLTransformFeedback: false,
  28094. WebGLUniformLocation: false,
  28095. WebGLVertexArrayObject: false,
  28096. WebSocket: false,
  28097. WheelEvent: false,
  28098. window: false,
  28099. Window: false,
  28100. Worker: false,
  28101. WritableStream: false,
  28102. XMLDocument: false,
  28103. XMLHttpRequest: false,
  28104. XMLHttpRequestEventTarget: false,
  28105. XMLHttpRequestUpload: false,
  28106. XMLSerializer: false,
  28107. XPathEvaluator: false,
  28108. XPathExpression: false,
  28109. XPathResult: false,
  28110. XSLTProcessor: false
  28111. };
  28112. var worker = {
  28113. addEventListener: false,
  28114. applicationCache: false,
  28115. atob: false,
  28116. Blob: false,
  28117. BroadcastChannel: false,
  28118. btoa: false,
  28119. Cache: false,
  28120. caches: false,
  28121. clearInterval: false,
  28122. clearTimeout: false,
  28123. close: true,
  28124. console: false,
  28125. fetch: false,
  28126. FileReaderSync: false,
  28127. FormData: false,
  28128. Headers: false,
  28129. IDBCursor: false,
  28130. IDBCursorWithValue: false,
  28131. IDBDatabase: false,
  28132. IDBFactory: false,
  28133. IDBIndex: false,
  28134. IDBKeyRange: false,
  28135. IDBObjectStore: false,
  28136. IDBOpenDBRequest: false,
  28137. IDBRequest: false,
  28138. IDBTransaction: false,
  28139. IDBVersionChangeEvent: false,
  28140. ImageData: false,
  28141. importScripts: true,
  28142. indexedDB: false,
  28143. location: false,
  28144. MessageChannel: false,
  28145. MessagePort: false,
  28146. name: false,
  28147. navigator: false,
  28148. Notification: false,
  28149. onclose: true,
  28150. onconnect: true,
  28151. onerror: true,
  28152. onlanguagechange: true,
  28153. onmessage: true,
  28154. onoffline: true,
  28155. ononline: true,
  28156. onrejectionhandled: true,
  28157. onunhandledrejection: true,
  28158. performance: false,
  28159. Performance: false,
  28160. PerformanceEntry: false,
  28161. PerformanceMark: false,
  28162. PerformanceMeasure: false,
  28163. PerformanceNavigation: false,
  28164. PerformanceResourceTiming: false,
  28165. PerformanceTiming: false,
  28166. postMessage: true,
  28167. "Promise": false,
  28168. queueMicrotask: false,
  28169. removeEventListener: false,
  28170. Request: false,
  28171. Response: false,
  28172. self: true,
  28173. ServiceWorkerRegistration: false,
  28174. setInterval: false,
  28175. setTimeout: false,
  28176. TextDecoder: false,
  28177. TextEncoder: false,
  28178. URL: false,
  28179. URLSearchParams: false,
  28180. WebSocket: false,
  28181. Worker: false,
  28182. WorkerGlobalScope: false,
  28183. XMLHttpRequest: false
  28184. };
  28185. var node = {
  28186. __dirname: false,
  28187. __filename: false,
  28188. Buffer: false,
  28189. clearImmediate: false,
  28190. clearInterval: false,
  28191. clearTimeout: false,
  28192. console: false,
  28193. exports: true,
  28194. global: false,
  28195. "Intl": false,
  28196. module: false,
  28197. process: false,
  28198. queueMicrotask: false,
  28199. require: false,
  28200. setImmediate: false,
  28201. setInterval: false,
  28202. setTimeout: false,
  28203. TextDecoder: false,
  28204. TextEncoder: false,
  28205. URL: false,
  28206. URLSearchParams: false
  28207. };
  28208. var commonjs = {
  28209. exports: true,
  28210. global: false,
  28211. module: false,
  28212. require: false
  28213. };
  28214. var amd = {
  28215. define: false,
  28216. require: false
  28217. };
  28218. var mocha = {
  28219. after: false,
  28220. afterEach: false,
  28221. before: false,
  28222. beforeEach: false,
  28223. context: false,
  28224. describe: false,
  28225. it: false,
  28226. mocha: false,
  28227. run: false,
  28228. setup: false,
  28229. specify: false,
  28230. suite: false,
  28231. suiteSetup: false,
  28232. suiteTeardown: false,
  28233. teardown: false,
  28234. test: false,
  28235. xcontext: false,
  28236. xdescribe: false,
  28237. xit: false,
  28238. xspecify: false
  28239. };
  28240. var jasmine = {
  28241. afterAll: false,
  28242. afterEach: false,
  28243. beforeAll: false,
  28244. beforeEach: false,
  28245. describe: false,
  28246. expect: false,
  28247. expectAsync: false,
  28248. fail: false,
  28249. fdescribe: false,
  28250. fit: false,
  28251. it: false,
  28252. jasmine: false,
  28253. pending: false,
  28254. runs: false,
  28255. spyOn: false,
  28256. spyOnAllFunctions: false,
  28257. spyOnProperty: false,
  28258. waits: false,
  28259. waitsFor: false,
  28260. xdescribe: false,
  28261. xit: false
  28262. };
  28263. var jest = {
  28264. afterAll: false,
  28265. afterEach: false,
  28266. beforeAll: false,
  28267. beforeEach: false,
  28268. describe: false,
  28269. expect: false,
  28270. fdescribe: false,
  28271. fit: false,
  28272. it: false,
  28273. jest: false,
  28274. pit: false,
  28275. require: false,
  28276. test: false,
  28277. xdescribe: false,
  28278. xit: false,
  28279. xtest: false
  28280. };
  28281. var qunit = {
  28282. asyncTest: false,
  28283. deepEqual: false,
  28284. equal: false,
  28285. expect: false,
  28286. module: false,
  28287. notDeepEqual: false,
  28288. notEqual: false,
  28289. notOk: false,
  28290. notPropEqual: false,
  28291. notStrictEqual: false,
  28292. ok: false,
  28293. propEqual: false,
  28294. QUnit: false,
  28295. raises: false,
  28296. start: false,
  28297. stop: false,
  28298. strictEqual: false,
  28299. test: false,
  28300. throws: false
  28301. };
  28302. var phantomjs = {
  28303. console: true,
  28304. exports: true,
  28305. phantom: true,
  28306. require: true,
  28307. WebPage: true
  28308. };
  28309. var couch = {
  28310. emit: false,
  28311. exports: false,
  28312. getRow: false,
  28313. log: false,
  28314. module: false,
  28315. provides: false,
  28316. require: false,
  28317. respond: false,
  28318. send: false,
  28319. start: false,
  28320. sum: false
  28321. };
  28322. var rhino = {
  28323. defineClass: false,
  28324. deserialize: false,
  28325. gc: false,
  28326. help: false,
  28327. importClass: false,
  28328. importPackage: false,
  28329. java: false,
  28330. load: false,
  28331. loadClass: false,
  28332. Packages: false,
  28333. print: false,
  28334. quit: false,
  28335. readFile: false,
  28336. readUrl: false,
  28337. runCommand: false,
  28338. seal: false,
  28339. serialize: false,
  28340. spawn: false,
  28341. sync: false,
  28342. toint32: false,
  28343. version: false
  28344. };
  28345. var nashorn = {
  28346. __DIR__: false,
  28347. __FILE__: false,
  28348. __LINE__: false,
  28349. com: false,
  28350. edu: false,
  28351. exit: false,
  28352. java: false,
  28353. Java: false,
  28354. javafx: false,
  28355. JavaImporter: false,
  28356. javax: false,
  28357. JSAdapter: false,
  28358. load: false,
  28359. loadWithNewGlobal: false,
  28360. org: false,
  28361. Packages: false,
  28362. print: false,
  28363. quit: false
  28364. };
  28365. var wsh = {
  28366. ActiveXObject: true,
  28367. Enumerator: true,
  28368. GetObject: true,
  28369. ScriptEngine: true,
  28370. ScriptEngineBuildVersion: true,
  28371. ScriptEngineMajorVersion: true,
  28372. ScriptEngineMinorVersion: true,
  28373. VBArray: true,
  28374. WScript: true,
  28375. WSH: true,
  28376. XDomainRequest: true
  28377. };
  28378. var jquery = {
  28379. $: false,
  28380. jQuery: false
  28381. };
  28382. var yui = {
  28383. YAHOO: false,
  28384. YAHOO_config: false,
  28385. YUI: false,
  28386. YUI_config: false
  28387. };
  28388. var shelljs = {
  28389. cat: false,
  28390. cd: false,
  28391. chmod: false,
  28392. config: false,
  28393. cp: false,
  28394. dirs: false,
  28395. echo: false,
  28396. env: false,
  28397. error: false,
  28398. exec: false,
  28399. exit: false,
  28400. find: false,
  28401. grep: false,
  28402. ln: false,
  28403. ls: false,
  28404. mkdir: false,
  28405. mv: false,
  28406. popd: false,
  28407. pushd: false,
  28408. pwd: false,
  28409. rm: false,
  28410. sed: false,
  28411. set: false,
  28412. target: false,
  28413. tempdir: false,
  28414. test: false,
  28415. touch: false,
  28416. which: false
  28417. };
  28418. var prototypejs = {
  28419. $: false,
  28420. $$: false,
  28421. $A: false,
  28422. $break: false,
  28423. $continue: false,
  28424. $F: false,
  28425. $H: false,
  28426. $R: false,
  28427. $w: false,
  28428. Abstract: false,
  28429. Ajax: false,
  28430. Autocompleter: false,
  28431. Builder: false,
  28432. Class: false,
  28433. Control: false,
  28434. Draggable: false,
  28435. Draggables: false,
  28436. Droppables: false,
  28437. Effect: false,
  28438. Element: false,
  28439. Enumerable: false,
  28440. Event: false,
  28441. Field: false,
  28442. Form: false,
  28443. Hash: false,
  28444. Insertion: false,
  28445. ObjectRange: false,
  28446. PeriodicalExecuter: false,
  28447. Position: false,
  28448. Prototype: false,
  28449. Scriptaculous: false,
  28450. Selector: false,
  28451. Sortable: false,
  28452. SortableObserver: false,
  28453. Sound: false,
  28454. Template: false,
  28455. Toggle: false,
  28456. Try: false
  28457. };
  28458. var meteor = {
  28459. _: false,
  28460. $: false,
  28461. Accounts: false,
  28462. AccountsClient: false,
  28463. AccountsCommon: false,
  28464. AccountsServer: false,
  28465. App: false,
  28466. Assets: false,
  28467. Blaze: false,
  28468. check: false,
  28469. Cordova: false,
  28470. DDP: false,
  28471. DDPRateLimiter: false,
  28472. DDPServer: false,
  28473. Deps: false,
  28474. EJSON: false,
  28475. Email: false,
  28476. HTTP: false,
  28477. Log: false,
  28478. Match: false,
  28479. Meteor: false,
  28480. Mongo: false,
  28481. MongoInternals: false,
  28482. Npm: false,
  28483. Package: false,
  28484. Plugin: false,
  28485. process: false,
  28486. Random: false,
  28487. ReactiveDict: false,
  28488. ReactiveVar: false,
  28489. Router: false,
  28490. ServiceConfiguration: false,
  28491. Session: false,
  28492. share: false,
  28493. Spacebars: false,
  28494. Template: false,
  28495. Tinytest: false,
  28496. Tracker: false,
  28497. UI: false,
  28498. Utils: false,
  28499. WebApp: false,
  28500. WebAppInternals: false
  28501. };
  28502. var mongo = {
  28503. _isWindows: false,
  28504. _rand: false,
  28505. BulkWriteResult: false,
  28506. cat: false,
  28507. cd: false,
  28508. connect: false,
  28509. db: false,
  28510. getHostName: false,
  28511. getMemInfo: false,
  28512. hostname: false,
  28513. ISODate: false,
  28514. listFiles: false,
  28515. load: false,
  28516. ls: false,
  28517. md5sumFile: false,
  28518. mkdir: false,
  28519. Mongo: false,
  28520. NumberInt: false,
  28521. NumberLong: false,
  28522. ObjectId: false,
  28523. PlanCache: false,
  28524. print: false,
  28525. printjson: false,
  28526. pwd: false,
  28527. quit: false,
  28528. removeFile: false,
  28529. rs: false,
  28530. sh: false,
  28531. UUID: false,
  28532. version: false,
  28533. WriteResult: false
  28534. };
  28535. var applescript = {
  28536. $: false,
  28537. Application: false,
  28538. Automation: false,
  28539. console: false,
  28540. delay: false,
  28541. Library: false,
  28542. ObjC: false,
  28543. ObjectSpecifier: false,
  28544. Path: false,
  28545. Progress: false,
  28546. Ref: false
  28547. };
  28548. var serviceworker = {
  28549. addEventListener: false,
  28550. applicationCache: false,
  28551. atob: false,
  28552. Blob: false,
  28553. BroadcastChannel: false,
  28554. btoa: false,
  28555. Cache: false,
  28556. caches: false,
  28557. CacheStorage: false,
  28558. clearInterval: false,
  28559. clearTimeout: false,
  28560. Client: false,
  28561. clients: false,
  28562. Clients: false,
  28563. close: true,
  28564. console: false,
  28565. ExtendableEvent: false,
  28566. ExtendableMessageEvent: false,
  28567. fetch: false,
  28568. FetchEvent: false,
  28569. FileReaderSync: false,
  28570. FormData: false,
  28571. Headers: false,
  28572. IDBCursor: false,
  28573. IDBCursorWithValue: false,
  28574. IDBDatabase: false,
  28575. IDBFactory: false,
  28576. IDBIndex: false,
  28577. IDBKeyRange: false,
  28578. IDBObjectStore: false,
  28579. IDBOpenDBRequest: false,
  28580. IDBRequest: false,
  28581. IDBTransaction: false,
  28582. IDBVersionChangeEvent: false,
  28583. ImageData: false,
  28584. importScripts: false,
  28585. indexedDB: false,
  28586. location: false,
  28587. MessageChannel: false,
  28588. MessagePort: false,
  28589. name: false,
  28590. navigator: false,
  28591. Notification: false,
  28592. onclose: true,
  28593. onconnect: true,
  28594. onerror: true,
  28595. onfetch: true,
  28596. oninstall: true,
  28597. onlanguagechange: true,
  28598. onmessage: true,
  28599. onmessageerror: true,
  28600. onnotificationclick: true,
  28601. onnotificationclose: true,
  28602. onoffline: true,
  28603. ononline: true,
  28604. onpush: true,
  28605. onpushsubscriptionchange: true,
  28606. onrejectionhandled: true,
  28607. onsync: true,
  28608. onunhandledrejection: true,
  28609. performance: false,
  28610. Performance: false,
  28611. PerformanceEntry: false,
  28612. PerformanceMark: false,
  28613. PerformanceMeasure: false,
  28614. PerformanceNavigation: false,
  28615. PerformanceResourceTiming: false,
  28616. PerformanceTiming: false,
  28617. postMessage: true,
  28618. "Promise": false,
  28619. queueMicrotask: false,
  28620. registration: false,
  28621. removeEventListener: false,
  28622. Request: false,
  28623. Response: false,
  28624. self: false,
  28625. ServiceWorker: false,
  28626. ServiceWorkerContainer: false,
  28627. ServiceWorkerGlobalScope: false,
  28628. ServiceWorkerMessageEvent: false,
  28629. ServiceWorkerRegistration: false,
  28630. setInterval: false,
  28631. setTimeout: false,
  28632. skipWaiting: false,
  28633. TextDecoder: false,
  28634. TextEncoder: false,
  28635. URL: false,
  28636. URLSearchParams: false,
  28637. WebSocket: false,
  28638. WindowClient: false,
  28639. Worker: false,
  28640. WorkerGlobalScope: false,
  28641. XMLHttpRequest: false
  28642. };
  28643. var atomtest = {
  28644. advanceClock: false,
  28645. fakeClearInterval: false,
  28646. fakeClearTimeout: false,
  28647. fakeSetInterval: false,
  28648. fakeSetTimeout: false,
  28649. resetTimeouts: false,
  28650. waitsForPromise: false
  28651. };
  28652. var embertest = {
  28653. andThen: false,
  28654. click: false,
  28655. currentPath: false,
  28656. currentRouteName: false,
  28657. currentURL: false,
  28658. fillIn: false,
  28659. find: false,
  28660. findAll: false,
  28661. findWithAssert: false,
  28662. keyEvent: false,
  28663. pauseTest: false,
  28664. resumeTest: false,
  28665. triggerEvent: false,
  28666. visit: false,
  28667. wait: false
  28668. };
  28669. var protractor = {
  28670. $: false,
  28671. $$: false,
  28672. browser: false,
  28673. by: false,
  28674. By: false,
  28675. DartObject: false,
  28676. element: false,
  28677. protractor: false
  28678. };
  28679. var webextensions = {
  28680. browser: false,
  28681. chrome: false,
  28682. opr: false
  28683. };
  28684. var greasemonkey = {
  28685. cloneInto: false,
  28686. createObjectIn: false,
  28687. exportFunction: false,
  28688. GM: false,
  28689. GM_addStyle: false,
  28690. GM_deleteValue: false,
  28691. GM_getResourceText: false,
  28692. GM_getResourceURL: false,
  28693. GM_getValue: false,
  28694. GM_info: false,
  28695. GM_listValues: false,
  28696. GM_log: false,
  28697. GM_openInTab: false,
  28698. GM_registerMenuCommand: false,
  28699. GM_setClipboard: false,
  28700. GM_setValue: false,
  28701. GM_xmlhttpRequest: false,
  28702. unsafeWindow: false
  28703. };
  28704. var devtools = {
  28705. $: false,
  28706. $_: false,
  28707. $$: false,
  28708. $0: false,
  28709. $1: false,
  28710. $2: false,
  28711. $3: false,
  28712. $4: false,
  28713. $x: false,
  28714. chrome: false,
  28715. clear: false,
  28716. copy: false,
  28717. debug: false,
  28718. dir: false,
  28719. dirxml: false,
  28720. getEventListeners: false,
  28721. inspect: false,
  28722. keys: false,
  28723. monitor: false,
  28724. monitorEvents: false,
  28725. profile: false,
  28726. profileEnd: false,
  28727. queryObjects: false,
  28728. table: false,
  28729. undebug: false,
  28730. unmonitor: false,
  28731. unmonitorEvents: false,
  28732. values: false
  28733. };
  28734. var globals = {
  28735. builtin: builtin,
  28736. es5: es5,
  28737. es2015: es2015,
  28738. es2017: es2017,
  28739. browser: browser,
  28740. worker: worker,
  28741. node: node,
  28742. commonjs: commonjs,
  28743. amd: amd,
  28744. mocha: mocha,
  28745. jasmine: jasmine,
  28746. jest: jest,
  28747. qunit: qunit,
  28748. phantomjs: phantomjs,
  28749. couch: couch,
  28750. rhino: rhino,
  28751. nashorn: nashorn,
  28752. wsh: wsh,
  28753. jquery: jquery,
  28754. yui: yui,
  28755. shelljs: shelljs,
  28756. prototypejs: prototypejs,
  28757. meteor: meteor,
  28758. mongo: mongo,
  28759. applescript: applescript,
  28760. serviceworker: serviceworker,
  28761. atomtest: atomtest,
  28762. embertest: embertest,
  28763. protractor: protractor,
  28764. "shared-node-browser": {
  28765. clearInterval: false,
  28766. clearTimeout: false,
  28767. console: false,
  28768. setInterval: false,
  28769. setTimeout: false,
  28770. URL: false,
  28771. URLSearchParams: false
  28772. },
  28773. webextensions: webextensions,
  28774. greasemonkey: greasemonkey,
  28775. devtools: devtools
  28776. };
  28777. var globals$1 = /*#__PURE__*/Object.freeze({
  28778. __proto__: null,
  28779. builtin: builtin,
  28780. es5: es5,
  28781. es2015: es2015,
  28782. es2017: es2017,
  28783. browser: browser,
  28784. worker: worker,
  28785. node: node,
  28786. commonjs: commonjs,
  28787. amd: amd,
  28788. mocha: mocha,
  28789. jasmine: jasmine,
  28790. jest: jest,
  28791. qunit: qunit,
  28792. phantomjs: phantomjs,
  28793. couch: couch,
  28794. rhino: rhino,
  28795. nashorn: nashorn,
  28796. wsh: wsh,
  28797. jquery: jquery,
  28798. yui: yui,
  28799. shelljs: shelljs,
  28800. prototypejs: prototypejs,
  28801. meteor: meteor,
  28802. mongo: mongo,
  28803. applescript: applescript,
  28804. serviceworker: serviceworker,
  28805. atomtest: atomtest,
  28806. embertest: embertest,
  28807. protractor: protractor,
  28808. webextensions: webextensions,
  28809. greasemonkey: greasemonkey,
  28810. devtools: devtools,
  28811. 'default': globals
  28812. });
  28813. var require$$0 = getCjsExportFromNamespace(globals$1);
  28814. var globals$2 = require$$0;
  28815. const browserAPIs = Object.keys(globals$2.browser);
  28816. const builtinAPIs = Object.keys(globals$2.builtin);
  28817. const isIdentifier = n => namedTypes.Identifier.check(n);
  28818. const isLiteral = n => namedTypes.Literal.check(n);
  28819. const isExpressionStatement = n => namedTypes.ExpressionStatement.check(n);
  28820. const isThisExpression = n => namedTypes.ThisExpression.check(n);
  28821. const isNewExpression = n => namedTypes.NewExpression.check(n);
  28822. const isSequenceExpression = n => namedTypes.SequenceExpression.check(n);
  28823. const isBinaryExpression = n => namedTypes.BinaryExpression.check(n);
  28824. const isExportDefaultStatement = n => namedTypes.ExportDefaultDeclaration.check(n);
  28825. const isBrowserAPI = ({name}) => browserAPIs.includes(name);
  28826. const isBuiltinAPI = ({name}) => builtinAPIs.includes(name);
  28827. const isRaw = n => n && n.raw;
  28828. /**
  28829. * Find the export default statement
  28830. * @param { Array } body - tree structure containing the program code
  28831. * @returns { Object } node containing only the code of the export default statement
  28832. */
  28833. function findExportDefaultStatement(body) {
  28834. return body.find(isExportDefaultStatement)
  28835. }
  28836. /**
  28837. * Find all the code in an ast program except for the export default statements
  28838. * @param { Array } body - tree structure containing the program code
  28839. * @returns { Array } array containing all the program code except the export default expressions
  28840. */
  28841. function filterNonExportDefaultStatements(body) {
  28842. return body.filter(node => !isExportDefaultStatement(node))
  28843. }
  28844. /**
  28845. * Get the body of the AST structure
  28846. * @param { Object } ast - ast object generated by recast
  28847. * @returns { Array } array containing the program code
  28848. */
  28849. function getProgramBody(ast) {
  28850. return ast.body || ast.program.body
  28851. }
  28852. /**
  28853. * Extend the AST adding the new tag method containing our tag sourcecode
  28854. * @param { Object } ast - current output ast
  28855. * @param { Object } exportDefaultNode - tag export default node
  28856. * @returns { Object } the output ast having the "tag" key extended with the content of the export default
  28857. */
  28858. function extendTagProperty(ast, exportDefaultNode) {
  28859. types$1.visit(ast, {
  28860. visitProperty(path) {
  28861. if (path.value.key.value === TAG_LOGIC_PROPERTY) {
  28862. path.value.value = exportDefaultNode.declaration;
  28863. return false
  28864. }
  28865. this.traverse(path);
  28866. }
  28867. });
  28868. return ast
  28869. }
  28870. /**
  28871. * Generate the component javascript logic
  28872. * @param { Object } sourceNode - node generated by the riot compiler
  28873. * @param { string } source - original component source code
  28874. * @param { Object } meta - compilation meta information
  28875. * @param { AST } ast - current AST output
  28876. * @returns { AST } the AST generated
  28877. */
  28878. function javascript(sourceNode, source, meta, ast) {
  28879. const preprocessorName = getPreprocessorTypeByAttribute(sourceNode);
  28880. const javascriptNode = addLineOffset(sourceNode.text.text, source, sourceNode);
  28881. const { options } = meta;
  28882. const preprocessorOutput = preprocess('javascript', preprocessorName, meta, {
  28883. ...sourceNode,
  28884. text: javascriptNode
  28885. });
  28886. const inputSourceMap = sourcemapAsJSON(preprocessorOutput.map);
  28887. const generatedAst = generateAST(preprocessorOutput.code, {
  28888. sourceFileName: options.file,
  28889. inputSourceMap: isEmptySourcemap(inputSourceMap) ? null : inputSourceMap
  28890. });
  28891. const generatedAstBody = getProgramBody(generatedAst);
  28892. const bodyWithoutExportDefault = filterNonExportDefaultStatements(generatedAstBody);
  28893. const exportDefaultNode = findExportDefaultStatement(generatedAstBody);
  28894. const outputBody = getProgramBody(ast);
  28895. // add to the ast the "private" javascript content of our tag script node
  28896. outputBody.unshift(...bodyWithoutExportDefault);
  28897. // convert the export default adding its content to the "tag" property exported
  28898. if (exportDefaultNode) extendTagProperty(ast, exportDefaultNode);
  28899. return ast
  28900. }
  28901. const JAVASCRIPT_OUTPUT_NAME = 'javascript';
  28902. const CSS_OUTPUT_NAME = 'css';
  28903. const TEMPLATE_OUTPUT_NAME = 'template';
  28904. // Tag names
  28905. const JAVASCRIPT_TAG = 'script';
  28906. const STYLE_TAG = 'style';
  28907. const TEXTAREA_TAG = 'textarea';
  28908. // Boolean attributes
  28909. const IS_RAW = 'isRaw';
  28910. const IS_SELF_CLOSING = 'isSelfClosing';
  28911. const IS_VOID = 'isVoid';
  28912. const IS_BOOLEAN = 'isBoolean';
  28913. const IS_CUSTOM = 'isCustom';
  28914. const IS_SPREAD = 'isSpread';
  28915. var c = /*#__PURE__*/Object.freeze({
  28916. __proto__: null,
  28917. JAVASCRIPT_OUTPUT_NAME: JAVASCRIPT_OUTPUT_NAME,
  28918. CSS_OUTPUT_NAME: CSS_OUTPUT_NAME,
  28919. TEMPLATE_OUTPUT_NAME: TEMPLATE_OUTPUT_NAME,
  28920. JAVASCRIPT_TAG: JAVASCRIPT_TAG,
  28921. STYLE_TAG: STYLE_TAG,
  28922. TEXTAREA_TAG: TEXTAREA_TAG,
  28923. IS_RAW: IS_RAW,
  28924. IS_SELF_CLOSING: IS_SELF_CLOSING,
  28925. IS_VOID: IS_VOID,
  28926. IS_BOOLEAN: IS_BOOLEAN,
  28927. IS_CUSTOM: IS_CUSTOM,
  28928. IS_SPREAD: IS_SPREAD
  28929. });
  28930. /**
  28931. * Not all the types are handled in this module.
  28932. *
  28933. * @enum {number}
  28934. * @readonly
  28935. */
  28936. const TAG = 1; /* TAG */
  28937. const ATTR = 2; /* ATTR */
  28938. const TEXT = 3; /* TEXT */
  28939. const CDATA = 4; /* CDATA */
  28940. const COMMENT = 8; /* COMMENT */
  28941. const DOCUMENT = 9; /* DOCUMENT */
  28942. const DOCTYPE = 10; /* DOCTYPE */
  28943. const DOCUMENT_FRAGMENT = 11; /* DOCUMENT_FRAGMENT */
  28944. var types$3 = /*#__PURE__*/Object.freeze({
  28945. __proto__: null,
  28946. TAG: TAG,
  28947. ATTR: ATTR,
  28948. TEXT: TEXT,
  28949. CDATA: CDATA,
  28950. COMMENT: COMMENT,
  28951. DOCUMENT: DOCUMENT,
  28952. DOCTYPE: DOCTYPE,
  28953. DOCUMENT_FRAGMENT: DOCUMENT_FRAGMENT
  28954. });
  28955. const rootTagNotFound = 'Root tag not found.';
  28956. const unclosedTemplateLiteral = 'Unclosed ES6 template literal.';
  28957. const unexpectedEndOfFile = 'Unexpected end of file.';
  28958. const unclosedComment = 'Unclosed comment.';
  28959. const unclosedNamedBlock = 'Unclosed "%1" block.';
  28960. const duplicatedNamedTag = 'Duplicate tag "<%1>".';
  28961. const unexpectedCharInExpression = 'Unexpected character %1.';
  28962. const unclosedExpression = 'Unclosed expression.';
  28963. /**
  28964. * Matches the start of valid tags names; used with the first 2 chars after the `'<'`.
  28965. * @const
  28966. * @private
  28967. */
  28968. const TAG_2C = /^(?:\/[a-zA-Z]|[a-zA-Z][^\s>/]?)/;
  28969. /**
  28970. * Matches valid tags names AFTER the validation with `TAG_2C`.
  28971. * $1: tag name including any `'/'`, $2: non self-closing brace (`>`) w/o attributes.
  28972. * @const
  28973. * @private
  28974. */
  28975. const TAG_NAME = /(\/?[^\s>/]+)\s*(>)?/g;
  28976. /**
  28977. * Matches an attribute name-value pair (both can be empty).
  28978. * $1: attribute name, $2: value including any quotes.
  28979. * @const
  28980. * @private
  28981. */
  28982. const ATTR_START = /(\S[^>/=\s]*)(?:\s*=\s*([^>/])?)?/g;
  28983. /**
  28984. * Matches the spread operator
  28985. * it will be used for the spread attributes
  28986. * @type {RegExp}
  28987. */
  28988. const SPREAD_OPERATOR = /\.\.\./;
  28989. /**
  28990. * Matches the closing tag of a `script` and `style` block.
  28991. * Used by parseText fo find the end of the block.
  28992. * @const
  28993. * @private
  28994. */
  28995. const RE_SCRYLE = {
  28996. script: /<\/script\s*>/gi,
  28997. style: /<\/style\s*>/gi,
  28998. textarea: /<\/textarea\s*>/gi
  28999. };
  29000. // Do not touch text content inside this tags
  29001. const RAW_TAGS = /^\/?(?:pre|textarea)$/;
  29002. /**
  29003. * Add an item into a collection, if the collection is not an array
  29004. * we create one and add the item to it
  29005. * @param {Array} collection - target collection
  29006. * @param {*} item - item to add to the collection
  29007. * @returns {Array} array containing the new item added to it
  29008. */
  29009. function addToCollection(collection = [], item) {
  29010. collection.push(item);
  29011. return collection
  29012. }
  29013. /**
  29014. * Run RegExp.exec starting from a specific position
  29015. * @param {RegExp} re - regex
  29016. * @param {number} pos - last index position
  29017. * @param {string} string - regex target
  29018. * @returns {Array} regex result
  29019. */
  29020. function execFromPos(re, pos, string) {
  29021. re.lastIndex = pos;
  29022. return re.exec(string)
  29023. }
  29024. /**
  29025. * Escape special characters in a given string, in preparation to create a regex.
  29026. *
  29027. * @param {string} str - Raw string
  29028. * @returns {string} Escaped string.
  29029. */
  29030. var escapeStr = (str) => str.replace(/(?=[-[\](){^*+?.$|\\])/g, '\\');
  29031. function formatError$1(data, message, pos) {
  29032. if (!pos) {
  29033. pos = data.length;
  29034. }
  29035. // count unix/mac/win eols
  29036. const line = (data.slice(0, pos).match(/\r\n?|\n/g) || '').length + 1;
  29037. let col = 0;
  29038. while (--pos >= 0 && !/[\r\n]/.test(data[pos])) {
  29039. ++col;
  29040. }
  29041. return `[${line},${col}]: ${message}`
  29042. }
  29043. const $_ES6_BQ = '`';
  29044. /**
  29045. * Searches the next backquote that signals the end of the ES6 Template Literal
  29046. * or the "${" sequence that starts a JS expression, skipping any escaped
  29047. * character.
  29048. *
  29049. * @param {string} code - Whole code
  29050. * @param {number} pos - The start position of the template
  29051. * @param {string[]} stack - To save nested ES6 TL count
  29052. * @returns {number} The end of the string (-1 if not found)
  29053. */
  29054. function skipES6TL(code, pos, stack) {
  29055. // we are in the char following the backquote (`),
  29056. // find the next unescaped backquote or the sequence "${"
  29057. const re = /[`$\\]/g;
  29058. let c;
  29059. while (re.lastIndex = pos, re.exec(code)) {
  29060. pos = re.lastIndex;
  29061. c = code[pos - 1];
  29062. if (c === '`') {
  29063. return pos
  29064. }
  29065. if (c === '$' && code[pos++] === '{') {
  29066. stack.push($_ES6_BQ, '}');
  29067. return pos
  29068. }
  29069. // else this is an escaped char
  29070. }
  29071. throw formatError$1(code, unclosedTemplateLiteral, pos)
  29072. }
  29073. /**
  29074. * Custom error handler can be implemented replacing this method.
  29075. * The `state` object includes the buffer (`data`)
  29076. * The error position (`loc`) contains line (base 1) and col (base 0).
  29077. * @param {string} data - string containing the error
  29078. * @param {string} msg - Error message
  29079. * @param {number} pos - Position of the error
  29080. * @returns {undefined} throw an exception error
  29081. */
  29082. function panic$1(data, msg, pos) {
  29083. const message = formatError$1(data, msg, pos);
  29084. throw new Error(message)
  29085. }
  29086. // forked from https://github.com/aMarCruz/skip-regex
  29087. // safe characters to precced a regex (including `=>`, `**`, and `...`)
  29088. const beforeReChars = '[{(,;:?=|&!^~>%*/';
  29089. const beforeReSign = `${beforeReChars}+-`;
  29090. // keyword that can preceed a regex (`in` is handled as special case)
  29091. const beforeReWords = [
  29092. 'case',
  29093. 'default',
  29094. 'do',
  29095. 'else',
  29096. 'in',
  29097. 'instanceof',
  29098. 'prefix',
  29099. 'return',
  29100. 'typeof',
  29101. 'void',
  29102. 'yield'
  29103. ];
  29104. // Last chars of all the beforeReWords elements to speed up the process.
  29105. const wordsEndChar = beforeReWords.reduce((s, w) => s + w.slice(-1), '');
  29106. // Matches literal regex from the start of the buffer.
  29107. // The buffer to search must not include line-endings.
  29108. const RE_LIT_REGEX = /^\/(?=[^*>/])[^[/\\]*(?:(?:\\.|\[(?:\\.|[^\]\\]*)*\])[^[\\/]*)*?\/[gimuy]*/;
  29109. // Valid characters for JavaScript variable names and literal numbers.
  29110. const RE_JS_VCHAR = /[$\w]/;
  29111. // Match dot characters that could be part of tricky regex
  29112. const RE_DOT_CHAR = /.*/g;
  29113. /**
  29114. * Searches the position of the previous non-blank character inside `code`,
  29115. * starting with `pos - 1`.
  29116. *
  29117. * @param {string} code - Buffer to search
  29118. * @param {number} pos - Starting position
  29119. * @returns {number} Position of the first non-blank character to the left.
  29120. * @private
  29121. */
  29122. function _prev(code, pos) {
  29123. while (--pos >= 0 && /\s/.test(code[pos]));
  29124. return pos
  29125. }
  29126. /**
  29127. * Check if the character in the `start` position within `code` can be a regex
  29128. * and returns the position following this regex or `start+1` if this is not
  29129. * one.
  29130. *
  29131. * NOTE: Ensure `start` points to a slash (this is not checked).
  29132. *
  29133. * @function skipRegex
  29134. * @param {string} code - Buffer to test in
  29135. * @param {number} start - Position the first slash inside `code`
  29136. * @returns {number} Position of the char following the regex.
  29137. *
  29138. */
  29139. /* istanbul ignore next */
  29140. function skipRegex(code, start) {
  29141. let pos = RE_DOT_CHAR.lastIndex = start++;
  29142. // `exec()` will extract from the slash to the end of the line
  29143. // and the chained `match()` will match the possible regex.
  29144. const match = (RE_DOT_CHAR.exec(code) || ' ')[0].match(RE_LIT_REGEX);
  29145. if (match) {
  29146. const next = pos + match[0].length; // result comes from `re.match`
  29147. pos = _prev(code, pos);
  29148. let c = code[pos];
  29149. // start of buffer or safe prefix?
  29150. if (pos < 0 || beforeReChars.includes(c)) {
  29151. return next
  29152. }
  29153. // from here, `pos` is >= 0 and `c` is code[pos]
  29154. if (c === '.') {
  29155. // can be `...` or something silly like 5./2
  29156. if (code[pos - 1] === '.') {
  29157. start = next;
  29158. }
  29159. } else {
  29160. if (c === '+' || c === '-') {
  29161. // tricky case
  29162. if (code[--pos] !== c || // if have a single operator or
  29163. (pos = _prev(code, pos)) < 0 || // ...have `++` and no previous token
  29164. beforeReSign.includes(c = code[pos])) {
  29165. return next // ...this is a regex
  29166. }
  29167. }
  29168. if (wordsEndChar.includes(c)) { // looks like a keyword?
  29169. const end = pos + 1;
  29170. // get the complete (previous) keyword
  29171. while (--pos >= 0 && RE_JS_VCHAR.test(code[pos]));
  29172. // it is in the allowed keywords list?
  29173. if (beforeReWords.includes(code.slice(pos + 1, end))) {
  29174. start = next;
  29175. }
  29176. }
  29177. }
  29178. }
  29179. return start
  29180. }
  29181. /*
  29182. * Mini-parser for expressions.
  29183. * The main pourpose of this module is to find the end of an expression
  29184. * and return its text without the enclosing brackets.
  29185. * Does not works with comments, but supports ES6 template strings.
  29186. */
  29187. /**
  29188. * @exports exprExtr
  29189. */
  29190. const S_SQ_STR = /'[^'\n\r\\]*(?:\\(?:\r\n?|[\S\s])[^'\n\r\\]*)*'/.source;
  29191. /**
  29192. * Matches double quoted JS strings taking care about nested quotes
  29193. * and EOLs (escaped EOLs are Ok).
  29194. *
  29195. * @const
  29196. * @private
  29197. */
  29198. const S_STRING = `${S_SQ_STR}|${S_SQ_STR.replace(/'/g, '"')}`;
  29199. /**
  29200. * Regex cache
  29201. *
  29202. * @type {Object.<string, RegExp>}
  29203. * @const
  29204. * @private
  29205. */
  29206. const reBr = {};
  29207. /**
  29208. * Makes an optimal regex that matches quoted strings, brackets, backquotes
  29209. * and the closing brackets of an expression.
  29210. *
  29211. * @param {string} b - Closing brackets
  29212. * @returns {RegExp} - optimized regex
  29213. */
  29214. function _regex(b) {
  29215. let re = reBr[b];
  29216. if (!re) {
  29217. let s = escapeStr(b);
  29218. if (b.length > 1) {
  29219. s = `${s}|[`;
  29220. } else {
  29221. s = /[{}[\]()]/.test(b) ? '[' : `[${s}`;
  29222. }
  29223. reBr[b] = re = new RegExp(`${S_STRING}|${s}\`/\\{}[\\]()]`, 'g');
  29224. }
  29225. return re
  29226. }
  29227. /**
  29228. * Update the scopes stack removing or adding closures to it
  29229. * @param {Array} stack - array stacking the expression closures
  29230. * @param {string} char - current char to add or remove from the stack
  29231. * @param {string} idx - matching index
  29232. * @param {string} code - expression code
  29233. * @returns {Object} result
  29234. * @returns {Object} result.char - either the char received or the closing braces
  29235. * @returns {Object} result.index - either a new index to skip part of the source code,
  29236. * or 0 to keep from parsing from the old position
  29237. */
  29238. function updateStack(stack, char, idx, code) {
  29239. let index = 0;
  29240. switch (char) {
  29241. case '[':
  29242. case '(':
  29243. case '{':
  29244. stack.push(char === '[' ? ']' : char === '(' ? ')' : '}');
  29245. break
  29246. case ')':
  29247. case ']':
  29248. case '}':
  29249. if (char !== stack.pop()) {
  29250. panic$1(code, unexpectedCharInExpression.replace('%1', char), index);
  29251. }
  29252. if (char === '}' && stack[stack.length - 1] === $_ES6_BQ) {
  29253. char = stack.pop();
  29254. }
  29255. index = idx + 1;
  29256. break
  29257. case '/':
  29258. index = skipRegex(code, idx);
  29259. }
  29260. return { char, index }
  29261. }
  29262. /**
  29263. * Parses the code string searching the end of the expression.
  29264. * It skips braces, quoted strings, regexes, and ES6 template literals.
  29265. *
  29266. * @function exprExtr
  29267. * @param {string} code - Buffer to parse
  29268. * @param {number} start - Position of the opening brace
  29269. * @param {[string,string]} bp - Brackets pair
  29270. * @returns {Object} Expression's end (after the closing brace) or -1
  29271. * if it is not an expr.
  29272. */
  29273. function exprExtr(code, start, bp) {
  29274. const [openingBraces, closingBraces] = bp;
  29275. const offset = start + openingBraces.length; // skips the opening brace
  29276. const stack = []; // expected closing braces ('`' for ES6 TL)
  29277. const re = _regex(closingBraces);
  29278. re.lastIndex = offset; // begining of the expression
  29279. let end;
  29280. let match;
  29281. while (match = re.exec(code)) { // eslint-disable-line
  29282. const idx = match.index;
  29283. const str = match[0];
  29284. end = re.lastIndex;
  29285. // end the iteration
  29286. if (str === closingBraces && !stack.length) {
  29287. return {
  29288. text: code.slice(offset, idx),
  29289. start,
  29290. end
  29291. }
  29292. }
  29293. const { char, index } = updateStack(stack, str[0], idx, code);
  29294. // update the end value depending on the new index received
  29295. end = index || end;
  29296. // update the regex last index
  29297. re.lastIndex = char === $_ES6_BQ ? skipES6TL(code, end, stack) : end;
  29298. }
  29299. if (stack.length) {
  29300. panic$1(code, unclosedExpression, end);
  29301. }
  29302. }
  29303. /**
  29304. * Outputs the last parsed node. Can be used with a builder too.
  29305. *
  29306. * @param {ParserStore} store - Parsing store
  29307. * @returns {undefined} void function
  29308. * @private
  29309. */
  29310. function flush(store) {
  29311. const last = store.last;
  29312. store.last = null;
  29313. if (last && store.root) {
  29314. store.builder.push(last);
  29315. }
  29316. }
  29317. /**
  29318. * Get the code chunks from start and end range
  29319. * @param {string} source - source code
  29320. * @param {number} start - Start position of the chunk we want to extract
  29321. * @param {number} end - Ending position of the chunk we need
  29322. * @returns {string} chunk of code extracted from the source code received
  29323. * @private
  29324. */
  29325. function getChunk(source, start, end) {
  29326. return source.slice(start, end)
  29327. }
  29328. /**
  29329. * states text in the last text node, or creates a new one if needed.
  29330. *
  29331. * @param {ParserState} state - Current parser state
  29332. * @param {number} start - Start position of the tag
  29333. * @param {number} end - Ending position (last char of the tag)
  29334. * @param {Object} extra - extra properties to add to the text node
  29335. * @param {RawExpr[]} extra.expressions - Found expressions
  29336. * @param {string} extra.unescape - Brackets to unescape
  29337. * @returns {undefined} - void function
  29338. * @private
  29339. */
  29340. function pushText(state, start, end, extra = {}) {
  29341. const text = getChunk(state.data, start, end);
  29342. const expressions = extra.expressions;
  29343. const unescape = extra.unescape;
  29344. let q = state.last;
  29345. state.pos = end;
  29346. if (q && q.type === TEXT) {
  29347. q.text += text;
  29348. q.end = end;
  29349. } else {
  29350. flush(state);
  29351. state.last = q = { type: TEXT, text, start, end };
  29352. }
  29353. if (expressions && expressions.length) {
  29354. q.expressions = (q.expressions || []).concat(expressions);
  29355. }
  29356. if (unescape) {
  29357. q.unescape = unescape;
  29358. }
  29359. return TEXT
  29360. }
  29361. /**
  29362. * Find the end of the attribute value or text node
  29363. * Extract expressions.
  29364. * Detect if value have escaped brackets.
  29365. *
  29366. * @param {ParserState} state - Parser state
  29367. * @param {HasExpr} node - Node if attr, info if text
  29368. * @param {string} endingChars - Ends the value or text
  29369. * @param {number} start - Starting position
  29370. * @returns {number} Ending position
  29371. * @private
  29372. */
  29373. function expr(state, node, endingChars, start) {
  29374. const re = b0re(state, endingChars);
  29375. re.lastIndex = start; // reset re position
  29376. const { unescape, expressions, end } = parseExpressions(state, re);
  29377. if (node) {
  29378. if (unescape) {
  29379. node.unescape = unescape;
  29380. }
  29381. if (expressions.length) {
  29382. node.expressions = expressions;
  29383. }
  29384. } else {
  29385. pushText(state, start, end, {expressions, unescape});
  29386. }
  29387. return end
  29388. }
  29389. /**
  29390. * Parse a text chunk finding all the expressions in it
  29391. * @param {ParserState} state - Parser state
  29392. * @param {RegExp} re - regex to match the expressions contents
  29393. * @returns {Object} result containing the expression found, the string to unescape and the end position
  29394. */
  29395. function parseExpressions(state, re) {
  29396. const { data, options } = state;
  29397. const { brackets } = options;
  29398. const expressions = [];
  29399. let unescape, pos, match;
  29400. // Anything captured in $1 (closing quote or character) ends the loop...
  29401. while ((match = re.exec(data)) && !match[1]) {
  29402. // ...else, we have an opening bracket and maybe an expression.
  29403. pos = match.index;
  29404. if (data[pos - 1] === '\\') {
  29405. unescape = match[0]; // it is an escaped opening brace
  29406. } else {
  29407. const tmpExpr = exprExtr(data, pos, brackets);
  29408. if (tmpExpr) {
  29409. expressions.push(tmpExpr);
  29410. re.lastIndex = tmpExpr.end;
  29411. }
  29412. }
  29413. }
  29414. // Even for text, the parser needs match a closing char
  29415. if (!match) {
  29416. panic$1(data, unexpectedEndOfFile, pos);
  29417. }
  29418. return {
  29419. unescape,
  29420. expressions,
  29421. end: match.index
  29422. }
  29423. }
  29424. /**
  29425. * Creates a regex for the given string and the left bracket.
  29426. * The string is captured in $1.
  29427. *
  29428. * @param {ParserState} state - Parser state
  29429. * @param {string} str - String to search
  29430. * @returns {RegExp} Resulting regex.
  29431. * @private
  29432. */
  29433. function b0re(state, str) {
  29434. const { brackets } = state.options;
  29435. const re = state.regexCache[str];
  29436. if (re) return re
  29437. const b0 = escapeStr(brackets[0]);
  29438. // cache the regex extending the regexCache object
  29439. Object.assign(state.regexCache, { [str]: new RegExp(`(${str})|${b0}`, 'g') });
  29440. return state.regexCache[str]
  29441. }
  29442. // similar to _.uniq
  29443. const uniq = l => l.filter((x, i, a) => a.indexOf(x) === i);
  29444. /**
  29445. * SVG void elements that cannot be auto-closed and shouldn't contain child nodes.
  29446. * @const {Array}
  29447. */
  29448. const VOID_SVG_TAGS_LIST = [
  29449. 'circle',
  29450. 'ellipse',
  29451. 'line',
  29452. 'path',
  29453. 'polygon',
  29454. 'polyline',
  29455. 'rect',
  29456. 'stop',
  29457. 'use'
  29458. ];
  29459. /**
  29460. * List of html elements where the value attribute is allowed
  29461. * @type {Array}
  29462. */
  29463. const HTML_ELEMENTS_HAVING_VALUE_ATTRIBUTE_LIST = [
  29464. 'button',
  29465. 'data',
  29466. 'input',
  29467. 'select',
  29468. 'li',
  29469. 'meter',
  29470. 'option',
  29471. 'output',
  29472. 'progress',
  29473. 'textarea',
  29474. 'param'
  29475. ];
  29476. /**
  29477. * List of all the available svg tags
  29478. * @const {Array}
  29479. * @see {@link https://github.com/wooorm/svg-tag-names}
  29480. */
  29481. const SVG_TAGS_LIST = uniq([
  29482. 'a',
  29483. 'altGlyph',
  29484. 'altGlyphDef',
  29485. 'altGlyphItem',
  29486. 'animate',
  29487. 'animateColor',
  29488. 'animateMotion',
  29489. 'animateTransform',
  29490. 'animation',
  29491. 'audio',
  29492. 'canvas',
  29493. 'clipPath',
  29494. 'color-profile',
  29495. 'cursor',
  29496. 'defs',
  29497. 'desc',
  29498. 'discard',
  29499. 'feBlend',
  29500. 'feColorMatrix',
  29501. 'feComponentTransfer',
  29502. 'feComposite',
  29503. 'feConvolveMatrix',
  29504. 'feDiffuseLighting',
  29505. 'feDisplacementMap',
  29506. 'feDistantLight',
  29507. 'feDropShadow',
  29508. 'feFlood',
  29509. 'feFuncA',
  29510. 'feFuncB',
  29511. 'feFuncG',
  29512. 'feFuncR',
  29513. 'feGaussianBlur',
  29514. 'feImage',
  29515. 'feMerge',
  29516. 'feMergeNode',
  29517. 'feMorphology',
  29518. 'feOffset',
  29519. 'fePointLight',
  29520. 'feSpecularLighting',
  29521. 'feSpotLight',
  29522. 'feTile',
  29523. 'feTurbulence',
  29524. 'filter',
  29525. 'font',
  29526. 'font-face',
  29527. 'font-face-format',
  29528. 'font-face-name',
  29529. 'font-face-src',
  29530. 'font-face-uri',
  29531. 'foreignObject',
  29532. 'g',
  29533. 'glyph',
  29534. 'glyphRef',
  29535. 'handler',
  29536. 'hatch',
  29537. 'hatchpath',
  29538. 'hkern',
  29539. 'iframe',
  29540. 'image',
  29541. 'linearGradient',
  29542. 'listener',
  29543. 'marker',
  29544. 'mask',
  29545. 'mesh',
  29546. 'meshgradient',
  29547. 'meshpatch',
  29548. 'meshrow',
  29549. 'metadata',
  29550. 'missing-glyph',
  29551. 'mpath',
  29552. 'pattern',
  29553. 'prefetch',
  29554. 'radialGradient',
  29555. 'script',
  29556. 'set',
  29557. 'solidColor',
  29558. 'solidcolor',
  29559. 'style',
  29560. 'svg',
  29561. 'switch',
  29562. 'symbol',
  29563. 'tbreak',
  29564. 'text',
  29565. 'textArea',
  29566. 'textPath',
  29567. 'title',
  29568. 'tref',
  29569. 'tspan',
  29570. 'unknown',
  29571. 'video',
  29572. 'view',
  29573. 'vkern'
  29574. ].concat(VOID_SVG_TAGS_LIST)).sort();
  29575. /**
  29576. * HTML void elements that cannot be auto-closed and shouldn't contain child nodes.
  29577. * @type {Array}
  29578. * @see {@link http://www.w3.org/TR/html-markup/syntax.html#syntax-elements}
  29579. * @see {@link http://www.w3.org/TR/html5/syntax.html#void-elements}
  29580. */
  29581. const VOID_HTML_TAGS_LIST = [
  29582. 'area',
  29583. 'base',
  29584. 'br',
  29585. 'col',
  29586. 'embed',
  29587. 'hr',
  29588. 'img',
  29589. 'input',
  29590. 'keygen',
  29591. 'link',
  29592. 'menuitem',
  29593. 'meta',
  29594. 'param',
  29595. 'source',
  29596. 'track',
  29597. 'wbr'
  29598. ];
  29599. /**
  29600. * List of all the html tags
  29601. * @const {Array}
  29602. * @see {@link https://github.com/sindresorhus/html-tags}
  29603. */
  29604. const HTML_TAGS_LIST = uniq([
  29605. 'a',
  29606. 'abbr',
  29607. 'address',
  29608. 'article',
  29609. 'aside',
  29610. 'audio',
  29611. 'b',
  29612. 'bdi',
  29613. 'bdo',
  29614. 'blockquote',
  29615. 'body',
  29616. 'canvas',
  29617. 'caption',
  29618. 'cite',
  29619. 'code',
  29620. 'colgroup',
  29621. 'datalist',
  29622. 'dd',
  29623. 'del',
  29624. 'details',
  29625. 'dfn',
  29626. 'dialog',
  29627. 'div',
  29628. 'dl',
  29629. 'dt',
  29630. 'em',
  29631. 'fieldset',
  29632. 'figcaption',
  29633. 'figure',
  29634. 'footer',
  29635. 'form',
  29636. 'h1',
  29637. 'h2',
  29638. 'h3',
  29639. 'h4',
  29640. 'h5',
  29641. 'h6',
  29642. 'head',
  29643. 'header',
  29644. 'hgroup',
  29645. 'html',
  29646. 'i',
  29647. 'iframe',
  29648. 'ins',
  29649. 'kbd',
  29650. 'label',
  29651. 'legend',
  29652. 'main',
  29653. 'map',
  29654. 'mark',
  29655. 'math',
  29656. 'menu',
  29657. 'nav',
  29658. 'noscript',
  29659. 'object',
  29660. 'ol',
  29661. 'optgroup',
  29662. 'p',
  29663. 'picture',
  29664. 'pre',
  29665. 'q',
  29666. 'rb',
  29667. 'rp',
  29668. 'rt',
  29669. 'rtc',
  29670. 'ruby',
  29671. 's',
  29672. 'samp',
  29673. 'script',
  29674. 'section',
  29675. 'select',
  29676. 'slot',
  29677. 'small',
  29678. 'span',
  29679. 'strong',
  29680. 'style',
  29681. 'sub',
  29682. 'summary',
  29683. 'sup',
  29684. 'svg',
  29685. 'table',
  29686. 'tbody',
  29687. 'td',
  29688. 'template',
  29689. 'tfoot',
  29690. 'th',
  29691. 'thead',
  29692. 'time',
  29693. 'title',
  29694. 'tr',
  29695. 'u',
  29696. 'ul',
  29697. 'var',
  29698. 'video'
  29699. ]
  29700. .concat(VOID_HTML_TAGS_LIST)
  29701. .concat(HTML_ELEMENTS_HAVING_VALUE_ATTRIBUTE_LIST)
  29702. ).sort();
  29703. /**
  29704. * List of all boolean HTML attributes
  29705. * @const {RegExp}
  29706. * @see {@link https://www.w3.org/TR/html5/infrastructure.html#sec-boolean-attributes}
  29707. */
  29708. const BOOLEAN_ATTRIBUTES_LIST = [
  29709. 'disabled',
  29710. 'visible',
  29711. 'checked',
  29712. 'readonly',
  29713. 'required',
  29714. 'allowfullscreen',
  29715. 'autofocus',
  29716. 'autoplay',
  29717. 'compact',
  29718. 'controls',
  29719. 'default',
  29720. 'formnovalidate',
  29721. 'hidden',
  29722. 'ismap',
  29723. 'itemscope',
  29724. 'loop',
  29725. 'multiple',
  29726. 'muted',
  29727. 'noresize',
  29728. 'noshade',
  29729. 'novalidate',
  29730. 'nowrap',
  29731. 'open',
  29732. 'reversed',
  29733. 'seamless',
  29734. 'selected',
  29735. 'sortable',
  29736. 'truespeed',
  29737. 'typemustmatch'
  29738. ];
  29739. /**
  29740. * Join a list of items with the pipe symbol (usefull for regex list concatenation)
  29741. * @private
  29742. * @param {Array} list - list of strings
  29743. * @returns {string} the list received joined with pipes
  29744. */
  29745. function joinWithPipe(list) {
  29746. return list.join('|')
  29747. }
  29748. /**
  29749. * Convert list of strings to regex in order to test against it ignoring the cases
  29750. * @private
  29751. * @param {...Array} lists - array of strings
  29752. * @returns {RegExp} regex that will match all the strings in the array received ignoring the cases
  29753. */
  29754. function listsToRegex(...lists) {
  29755. return new RegExp(`^/?(?:${joinWithPipe(lists.map(joinWithPipe))})$`, 'i')
  29756. }
  29757. /**
  29758. * Regex matching all the html tags ignoring the cases
  29759. * @const {RegExp}
  29760. */
  29761. const HTML_TAGS_RE = listsToRegex(HTML_TAGS_LIST);
  29762. /**
  29763. * Regex matching all the svg tags ignoring the cases
  29764. * @const {RegExp}
  29765. */
  29766. const SVG_TAGS_RE = listsToRegex(SVG_TAGS_LIST);
  29767. /**
  29768. * Regex matching all the void html tags ignoring the cases
  29769. * @const {RegExp}
  29770. */
  29771. const VOID_HTML_TAGS_RE = listsToRegex(VOID_HTML_TAGS_LIST);
  29772. /**
  29773. * Regex matching all the void svg tags ignoring the cases
  29774. * @const {RegExp}
  29775. */
  29776. const VOID_SVG_TAGS_RE = listsToRegex(VOID_SVG_TAGS_LIST);
  29777. /**
  29778. * Regex matching all the html tags where the value tag is allowed
  29779. * @const {RegExp}
  29780. */
  29781. const HTML_ELEMENTS_HAVING_VALUE_ATTRIBUTE_RE = listsToRegex(HTML_ELEMENTS_HAVING_VALUE_ATTRIBUTE_LIST);
  29782. /**
  29783. * Regex matching all the boolean attributes
  29784. * @const {RegExp}
  29785. */
  29786. const BOOLEAN_ATTRIBUTES_RE = listsToRegex(BOOLEAN_ATTRIBUTES_LIST);
  29787. /**
  29788. * True if it's a self closing tag
  29789. * @param {string} tag - test tag
  29790. * @returns {boolean} true if void
  29791. * @example
  29792. * isVoid('meta') // true
  29793. * isVoid('circle') // true
  29794. * isVoid('IMG') // true
  29795. * isVoid('div') // false
  29796. * isVoid('mask') // false
  29797. */
  29798. function isVoid(tag) {
  29799. return [
  29800. VOID_HTML_TAGS_RE,
  29801. VOID_SVG_TAGS_RE
  29802. ].some(r => r.test(tag))
  29803. }
  29804. /**
  29805. * True if it's not SVG nor a HTML known tag
  29806. * @param {string} tag - test tag
  29807. * @returns {boolean} true if custom element
  29808. * @example
  29809. * isCustom('my-component') // true
  29810. * isCustom('div') // false
  29811. */
  29812. function isCustom(tag) {
  29813. return [
  29814. HTML_TAGS_RE,
  29815. SVG_TAGS_RE
  29816. ].every(l => !l.test(tag))
  29817. }
  29818. /**
  29819. * True if the value attribute is allowed on this tag
  29820. * @param {string} tag - test tag
  29821. * @returns {boolean} true if the value attribute is allowed
  29822. * @example
  29823. * hasValueAttribute('input') // true
  29824. * hasValueAttribute('div') // false
  29825. */
  29826. function hasValueAttribute(tag) {
  29827. return HTML_ELEMENTS_HAVING_VALUE_ATTRIBUTE_RE.test(tag)
  29828. }
  29829. /**
  29830. * True if it's a boolean attribute
  29831. * @param {string} attribute - test attribute
  29832. * @returns {boolean} true if the attribute is a boolean type
  29833. * @example
  29834. * isBoolAttribute('selected') // true
  29835. * isBoolAttribute('class') // false
  29836. */
  29837. function isBoolAttribute(attribute) {
  29838. return BOOLEAN_ATTRIBUTES_RE.test(attribute)
  29839. }
  29840. /**
  29841. * Memoization function
  29842. * @param {Function} fn - function to memoize
  29843. * @returns {*} return of the function to memoize
  29844. */
  29845. function memoize(fn) {
  29846. const cache = new WeakMap();
  29847. return (...args) => {
  29848. if (cache.has(args[0])) return cache.get(args[0])
  29849. const ret = fn(...args);
  29850. cache.set(args[0], ret);
  29851. return ret
  29852. }
  29853. }
  29854. const expressionsContentRe = memoize(brackets => RegExp(`(${brackets[0]}[^${brackets[1]}]*?${brackets[1]})`, 'g'));
  29855. const isSpreadAttribute = name => SPREAD_OPERATOR.test(name);
  29856. const isAttributeExpression = (name, brackets) => name[0] === brackets[0];
  29857. const getAttributeEnd = (state, attr) => expr(state, attr, '[>/\\s]', attr.start);
  29858. /**
  29859. * The more complex parsing is for attributes as it can contain quoted or
  29860. * unquoted values or expressions.
  29861. *
  29862. * @param {ParserStore} state - Parser state
  29863. * @returns {number} New parser mode.
  29864. * @private
  29865. */
  29866. function attr(state) {
  29867. const { data, last, pos, root } = state;
  29868. const tag = last; // the last (current) tag in the output
  29869. const _CH = /\S/g; // matches the first non-space char
  29870. const ch = execFromPos(_CH, pos, data);
  29871. switch (true) {
  29872. case !ch:
  29873. state.pos = data.length; // reaching the end of the buffer with
  29874. // NodeTypes.ATTR will generate error
  29875. break
  29876. case ch[0] === '>':
  29877. // closing char found. If this is a self-closing tag with the name of the
  29878. // Root tag, we need decrement the counter as we are changing mode.
  29879. state.pos = tag.end = _CH.lastIndex;
  29880. if (tag[IS_SELF_CLOSING]) {
  29881. state.scryle = null; // allow selfClosing script/style tags
  29882. if (root && root.name === tag.name) {
  29883. state.count--; // "pop" root tag
  29884. }
  29885. }
  29886. return TEXT
  29887. case ch[0] === '/':
  29888. state.pos = _CH.lastIndex; // maybe. delegate the validation
  29889. tag[IS_SELF_CLOSING] = true; // the next loop
  29890. break
  29891. default:
  29892. delete tag[IS_SELF_CLOSING]; // ensure unmark as selfclosing tag
  29893. setAttribute(state, ch.index, tag);
  29894. }
  29895. return ATTR
  29896. }
  29897. /**
  29898. * Parses an attribute and its expressions.
  29899. *
  29900. * @param {ParserStore} state - Parser state
  29901. * @param {number} pos - Starting position of the attribute
  29902. * @param {Object} tag - Current parent tag
  29903. * @returns {undefined} void function
  29904. * @private
  29905. */
  29906. function setAttribute(state, pos, tag) {
  29907. const { data } = state;
  29908. const expressionContent = expressionsContentRe(state.options.brackets);
  29909. const re = ATTR_START; // (\S[^>/=\s]*)(?:\s*=\s*([^>/])?)? g
  29910. const start = re.lastIndex = expressionContent.lastIndex = pos; // first non-whitespace
  29911. const attrMatches = re.exec(data);
  29912. const isExpressionName = isAttributeExpression(attrMatches[1], state.options.brackets);
  29913. const match = isExpressionName ? [null, expressionContent.exec(data)[1], null] : attrMatches;
  29914. if (match) {
  29915. const end = re.lastIndex;
  29916. const attr = parseAttribute(state, match, start, end, isExpressionName);
  29917. //assert(q && q.type === Mode.TAG, 'no previous tag for the attr!')
  29918. // Pushes the attribute and shifts the `end` position of the tag (`last`).
  29919. state.pos = tag.end = attr.end;
  29920. tag.attributes = addToCollection(tag.attributes, attr);
  29921. }
  29922. }
  29923. function parseNomalAttribute(state, attr, quote) {
  29924. const { data } = state;
  29925. let { end } = attr;
  29926. if (isBoolAttribute(attr.name)) {
  29927. attr[IS_BOOLEAN] = true;
  29928. }
  29929. // parse the whole value (if any) and get any expressions on it
  29930. if (quote) {
  29931. // Usually, the value's first char (`quote`) is a quote and the lastIndex
  29932. // (`end`) is the start of the value.
  29933. let valueStart = end;
  29934. // If it not, this is an unquoted value and we need adjust the start.
  29935. if (quote !== '"' && quote !== '\'') {
  29936. quote = ''; // first char of value is not a quote
  29937. valueStart--; // adjust the starting position
  29938. }
  29939. end = expr(state, attr, quote || '[>/\\s]', valueStart);
  29940. // adjust the bounds of the value and save its content
  29941. return Object.assign(attr, {
  29942. value: getChunk(data, valueStart, end),
  29943. valueStart,
  29944. end: quote ? ++end : end
  29945. })
  29946. }
  29947. return attr
  29948. }
  29949. /**
  29950. * Parse expression names <a {href}>
  29951. * @param {ParserStore} state - Parser state
  29952. * @param {Object} attr - attribute object parsed
  29953. * @returns {Object} normalized attribute object
  29954. */
  29955. function parseSpreadAttribute(state, attr) {
  29956. const end = getAttributeEnd(state, attr);
  29957. return {
  29958. [IS_SPREAD]: true,
  29959. start: attr.start,
  29960. expressions: attr.expressions.map(expr => Object.assign(expr, {
  29961. text: expr.text.replace(SPREAD_OPERATOR, '').trim()
  29962. })),
  29963. end: end
  29964. }
  29965. }
  29966. /**
  29967. * Parse expression names <a {href}>
  29968. * @param {ParserStore} state - Parser state
  29969. * @param {Object} attr - attribute object parsed
  29970. * @returns {Object} normalized attribute object
  29971. */
  29972. function parseExpressionNameAttribute(state, attr) {
  29973. const end = getAttributeEnd(state, attr);
  29974. return {
  29975. start: attr.start,
  29976. name: attr.expressions[0].text.trim(),
  29977. expressions: attr.expressions,
  29978. end: end
  29979. }
  29980. }
  29981. /**
  29982. * Parse the attribute values normalising the quotes
  29983. * @param {ParserStore} state - Parser state
  29984. * @param {Array} match - results of the attributes regex
  29985. * @param {number} start - attribute start position
  29986. * @param {number} end - attribute end position
  29987. * @param {boolean} isExpressionName - true if the attribute name is an expression
  29988. * @returns {Object} attribute object
  29989. */
  29990. function parseAttribute(state, match, start, end, isExpressionName) {
  29991. const attr = {
  29992. name: match[1],
  29993. value: '',
  29994. start,
  29995. end
  29996. };
  29997. const quote = match[2]; // first letter of value or nothing
  29998. switch (true) {
  29999. case isSpreadAttribute(attr.name):
  30000. return parseSpreadAttribute(state, attr)
  30001. case isExpressionName === true:
  30002. return parseExpressionNameAttribute(state, attr)
  30003. default:
  30004. return parseNomalAttribute(state, attr, quote)
  30005. }
  30006. }
  30007. /**
  30008. * Parses comments in long or short form
  30009. * (any DOCTYPE & CDATA blocks are parsed as comments).
  30010. *
  30011. * @param {ParserState} state - Parser state
  30012. * @param {string} data - Buffer to parse
  30013. * @param {number} start - Position of the '<!' sequence
  30014. * @returns {number} node type id
  30015. * @private
  30016. */
  30017. function comment(state, data, start) {
  30018. const pos = start + 2; // skip '<!'
  30019. const str = data.substr(pos, 2) === '--' ? '-->' : '>';
  30020. const end = data.indexOf(str, pos);
  30021. if (end < 0) {
  30022. panic$1(data, unclosedComment, start);
  30023. }
  30024. pushComment$1(state, start, end + str.length);
  30025. return TEXT
  30026. }
  30027. /**
  30028. * Parse a comment.
  30029. *
  30030. * @param {ParserState} state - Current parser state
  30031. * @param {number} start - Start position of the tag
  30032. * @param {number} end - Ending position (last char of the tag)
  30033. * @returns {undefined} void function
  30034. * @private
  30035. */
  30036. function pushComment$1(state, start, end) {
  30037. flush(state);
  30038. state.pos = end;
  30039. if (state.options.comments === true) {
  30040. state.last = { type: COMMENT, start, end };
  30041. }
  30042. }
  30043. /**
  30044. * Pushes a new *tag* and set `last` to this, so any attributes
  30045. * will be included on this and shifts the `end`.
  30046. *
  30047. * @param {ParserState} state - Current parser state
  30048. * @param {string} name - Name of the node including any slash
  30049. * @param {number} start - Start position of the tag
  30050. * @param {number} end - Ending position (last char of the tag + 1)
  30051. * @returns {undefined} - void function
  30052. * @private
  30053. */
  30054. function pushTag(state, name, start, end) {
  30055. const root = state.root;
  30056. const last = { type: TAG, name, start, end };
  30057. if (isCustom(name)) {
  30058. last[IS_CUSTOM] = true;
  30059. }
  30060. if (isVoid(name)) {
  30061. last[IS_VOID] = true;
  30062. }
  30063. state.pos = end;
  30064. if (root) {
  30065. if (name === root.name) {
  30066. state.count++;
  30067. } else if (name === root.close) {
  30068. state.count--;
  30069. }
  30070. flush(state);
  30071. } else {
  30072. // start with root (keep ref to output)
  30073. state.root = { name: last.name, close: `/${name}` };
  30074. state.count = 1;
  30075. }
  30076. state.last = last;
  30077. }
  30078. /**
  30079. * Parse the tag following a '<' character, or delegate to other parser
  30080. * if an invalid tag name is found.
  30081. *
  30082. * @param {ParserState} state - Parser state
  30083. * @returns {number} New parser mode
  30084. * @private
  30085. */
  30086. function tag(state) {
  30087. const { pos, data } = state; // pos of the char following '<'
  30088. const start = pos - 1; // pos of '<'
  30089. const str = data.substr(pos, 2); // first two chars following '<'
  30090. switch (true) {
  30091. case str[0] === '!':
  30092. return comment(state, data, start)
  30093. case TAG_2C.test(str):
  30094. return parseTag(state, start)
  30095. default:
  30096. return pushText(state, start, pos) // pushes the '<' as text
  30097. }
  30098. }
  30099. function parseTag(state, start) {
  30100. const { data, pos } = state;
  30101. const re = TAG_NAME; // (\/?[^\s>/]+)\s*(>)? g
  30102. const match = execFromPos(re, pos, data);
  30103. const end = re.lastIndex;
  30104. const name = match[1].toLowerCase(); // $1: tag name including any '/'
  30105. // script/style block is parsed as another tag to extract attributes
  30106. if (name in RE_SCRYLE) {
  30107. state.scryle = name; // used by parseText
  30108. }
  30109. pushTag(state, name, start, end);
  30110. // only '>' can ends the tag here, the '/' is handled in parseAttribute
  30111. if (!match[2]) {
  30112. return ATTR
  30113. }
  30114. return TEXT
  30115. }
  30116. /**
  30117. * Parses regular text and script/style blocks ...scryle for short :-)
  30118. * (the content of script and style is text as well)
  30119. *
  30120. * @param {ParserState} state - Parser state
  30121. * @returns {number} New parser mode.
  30122. * @private
  30123. */
  30124. function text(state) {
  30125. const { pos, data, scryle } = state;
  30126. switch (true) {
  30127. case typeof scryle === 'string': {
  30128. const name = scryle;
  30129. const re = RE_SCRYLE[name];
  30130. const match = execFromPos(re, pos, data);
  30131. if (!match) {
  30132. panic$1(data, unclosedNamedBlock.replace('%1', name), pos - 1);
  30133. }
  30134. const start = match.index;
  30135. const end = re.lastIndex;
  30136. state.scryle = null; // reset the script/style flag now
  30137. // write the tag content, if any
  30138. if (start > pos) {
  30139. parseSpecialTagsContent(state, name, match);
  30140. }
  30141. // now the closing tag, either </script> or </style>
  30142. pushTag(state, `/${name}`, start, end);
  30143. break
  30144. }
  30145. case data[pos] === '<':
  30146. state.pos++;
  30147. return TAG
  30148. default:
  30149. expr(state, null, '<', pos);
  30150. }
  30151. return TEXT
  30152. }
  30153. /**
  30154. * Parse the text content depending on the name
  30155. * @param {ParserState} state - Parser state
  30156. * @param {string} name - one of the tags matched by the RE_SCRYLE regex
  30157. * @param {Array} match - result of the regex matching the content of the parsed tag
  30158. * @returns {undefined} void function
  30159. */
  30160. function parseSpecialTagsContent(state, name, match) {
  30161. const { pos } = state;
  30162. const start = match.index;
  30163. if (name === TEXTAREA_TAG) {
  30164. expr(state, null, match[0], pos);
  30165. } else {
  30166. pushText(state, pos, start);
  30167. }
  30168. }
  30169. /*---------------------------------------------------------------------
  30170. * Tree builder for the riot tag parser.
  30171. *
  30172. * The output has a root property and separate arrays for `html`, `css`,
  30173. * and `js` tags.
  30174. *
  30175. * The root tag is included as first element in the `html` array.
  30176. * Script tags marked with "defer" are included in `html` instead `js`.
  30177. *
  30178. * - Mark SVG tags
  30179. * - Mark raw tags
  30180. * - Mark void tags
  30181. * - Split prefixes from expressions
  30182. * - Unescape escaped brackets and escape EOLs and backslashes
  30183. * - Compact whitespace (option `compact`) for non-raw tags
  30184. * - Create an array `parts` for text nodes and attributes
  30185. *
  30186. * Throws on unclosed tags or closing tags without start tag.
  30187. * Selfclosing and void tags has no nodes[] property.
  30188. */
  30189. /**
  30190. * Escape the carriage return and the line feed from a string
  30191. * @param {string} string - input string
  30192. * @returns {string} output string escaped
  30193. */
  30194. function escapeReturn(string) {
  30195. return string
  30196. .replace(/\r/g, '\\r')
  30197. .replace(/\n/g, '\\n')
  30198. }
  30199. /**
  30200. * Escape double slashes in a string
  30201. * @param {string} string - input string
  30202. * @returns {string} output string escaped
  30203. */
  30204. function escapeSlashes(string) {
  30205. return string.replace(/\\/g, '\\\\')
  30206. }
  30207. /**
  30208. * Replace the multiple spaces with only one
  30209. * @param {string} string - input string
  30210. * @returns {string} string without trailing spaces
  30211. */
  30212. function cleanSpaces(string) {
  30213. return string.replace(/\s+/g, ' ')
  30214. }
  30215. const TREE_BUILDER_STRUCT = Object.seal({
  30216. get() {
  30217. const store = this.store;
  30218. // The real root tag is in store.root.nodes[0]
  30219. return {
  30220. [TEMPLATE_OUTPUT_NAME]: store.root.nodes[0],
  30221. [CSS_OUTPUT_NAME]: store[STYLE_TAG],
  30222. [JAVASCRIPT_OUTPUT_NAME]: store[JAVASCRIPT_TAG]
  30223. }
  30224. },
  30225. /**
  30226. * Process the current tag or text.
  30227. * @param {Object} node - Raw pseudo-node from the parser
  30228. * @returns {undefined} void function
  30229. */
  30230. push(node) {
  30231. const store = this.store;
  30232. switch (node.type) {
  30233. case TEXT:
  30234. this.pushText(store, node);
  30235. break
  30236. case TAG: {
  30237. const name = node.name;
  30238. const closingTagChar = '/';
  30239. const [firstChar] = name;
  30240. if (firstChar === closingTagChar && !node.isVoid) {
  30241. this.closeTag(store, node, name);
  30242. } else if (firstChar !== closingTagChar) {
  30243. this.openTag(store, node);
  30244. }
  30245. break
  30246. }
  30247. }
  30248. },
  30249. closeTag(store, node) {
  30250. const last = store.scryle || store.last;
  30251. last.end = node.end;
  30252. if (store.scryle) {
  30253. store.scryle = null;
  30254. } else {
  30255. store.last = store.stack.pop();
  30256. }
  30257. },
  30258. openTag(store, node) {
  30259. const name = node.name;
  30260. const attrs = node.attributes;
  30261. if ([JAVASCRIPT_TAG, STYLE_TAG].includes(name)) {
  30262. // Only accept one of each
  30263. if (store[name]) {
  30264. panic$1(this.store.data, duplicatedNamedTag.replace('%1', name), node.start);
  30265. }
  30266. store[name] = node;
  30267. store.scryle = store[name];
  30268. } else {
  30269. // store.last holds the last tag pushed in the stack and this are
  30270. // non-void, non-empty tags, so we are sure the `lastTag` here
  30271. // have a `nodes` property.
  30272. const lastTag = store.last;
  30273. const newNode = node;
  30274. lastTag.nodes.push(newNode);
  30275. if (lastTag[IS_RAW] || RAW_TAGS.test(name)) {
  30276. node[IS_RAW] = true;
  30277. }
  30278. if (!node[IS_SELF_CLOSING] && !node[IS_VOID]) {
  30279. store.stack.push(lastTag);
  30280. newNode.nodes = [];
  30281. store.last = newNode;
  30282. }
  30283. }
  30284. if (attrs) {
  30285. this.attrs(attrs);
  30286. }
  30287. },
  30288. attrs(attributes) {
  30289. attributes.forEach(attr => {
  30290. if (attr.value) {
  30291. this.split(attr, attr.value, attr.valueStart, true);
  30292. }
  30293. });
  30294. },
  30295. pushText(store, node) {
  30296. const text = node.text;
  30297. const empty = !/\S/.test(text);
  30298. const scryle = store.scryle;
  30299. if (!scryle) {
  30300. // store.last always have a nodes property
  30301. const parent = store.last;
  30302. const pack = this.compact && !parent[IS_RAW];
  30303. if (pack && empty) {
  30304. return
  30305. }
  30306. this.split(node, text, node.start, pack);
  30307. parent.nodes.push(node);
  30308. } else if (!empty) {
  30309. scryle.text = node;
  30310. }
  30311. },
  30312. split(node, source, start, pack) {
  30313. const expressions = node.expressions;
  30314. const parts = [];
  30315. if (expressions) {
  30316. let pos = 0;
  30317. expressions.forEach(expr => {
  30318. const text = source.slice(pos, expr.start - start);
  30319. const code = expr.text;
  30320. parts.push(this.sanitise(node, text, pack), escapeReturn(escapeSlashes(code).trim()));
  30321. pos = expr.end - start;
  30322. });
  30323. if (pos < node.end) {
  30324. parts.push(this.sanitise(node, source.slice(pos), pack));
  30325. }
  30326. } else {
  30327. parts[0] = this.sanitise(node, source, pack);
  30328. }
  30329. node.parts = parts.filter(p => p); // remove the empty strings
  30330. },
  30331. // unescape escaped brackets and split prefixes of expressions
  30332. sanitise(node, text, pack) {
  30333. let rep = node.unescape;
  30334. if (rep) {
  30335. let idx = 0;
  30336. rep = `\\${rep}`;
  30337. while ((idx = text.indexOf(rep, idx)) !== -1) {
  30338. text = text.substr(0, idx) + text.substr(idx + 1);
  30339. idx++;
  30340. }
  30341. }
  30342. text = escapeSlashes(text);
  30343. return pack ? cleanSpaces(text) : escapeReturn(text)
  30344. }
  30345. });
  30346. function createTreeBuilder(data, options) {
  30347. const root = {
  30348. type: TAG,
  30349. name: '',
  30350. start: 0,
  30351. end: 0,
  30352. nodes: []
  30353. };
  30354. return Object.assign(Object.create(TREE_BUILDER_STRUCT), {
  30355. compact: options.compact !== false,
  30356. store: {
  30357. last: root,
  30358. stack: [],
  30359. scryle: null,
  30360. root,
  30361. style: null,
  30362. script: null,
  30363. data
  30364. }
  30365. })
  30366. }
  30367. /**
  30368. * Factory for the Parser class, exposing only the `parse` method.
  30369. * The export adds the Parser class as property.
  30370. *
  30371. * @param {Object} options - User Options
  30372. * @param {Function} customBuilder - Tree builder factory
  30373. * @returns {Function} Public Parser implementation.
  30374. */
  30375. function parser$1(options, customBuilder) {
  30376. const state = curry(createParserState)(options, customBuilder || createTreeBuilder);
  30377. return {
  30378. parse: (data) => parse(state(data))
  30379. }
  30380. }
  30381. /**
  30382. * Create a new state object
  30383. * @param {Object} userOptions - parser options
  30384. * @param {Function} builder - Tree builder factory
  30385. * @param {string} data - data to parse
  30386. * @returns {ParserState} it represents the current parser state
  30387. */
  30388. function createParserState(userOptions, builder, data) {
  30389. const options = Object.assign({
  30390. brackets: ['{', '}']
  30391. }, userOptions);
  30392. return {
  30393. options,
  30394. regexCache: {},
  30395. pos: 0,
  30396. count: -1,
  30397. root: null,
  30398. last: null,
  30399. scryle: null,
  30400. builder: builder(data, options),
  30401. data
  30402. }
  30403. }
  30404. /**
  30405. * It creates a raw output of pseudo-nodes with one of three different types,
  30406. * all of them having a start/end position:
  30407. *
  30408. * - TAG -- Opening or closing tags
  30409. * - TEXT -- Raw text
  30410. * - COMMENT -- Comments
  30411. *
  30412. * @param {ParserState} state - Current parser state
  30413. * @returns {ParserResult} Result, contains data and output properties.
  30414. */
  30415. function parse(state) {
  30416. const { data } = state;
  30417. walk(state);
  30418. flush(state);
  30419. if (state.count) {
  30420. panic$1(data, state.count > 0 ? unexpectedEndOfFile : rootTagNotFound, state.pos);
  30421. }
  30422. return {
  30423. data,
  30424. output: state.builder.get()
  30425. }
  30426. }
  30427. /**
  30428. * Parser walking recursive function
  30429. * @param {ParserState} state - Current parser state
  30430. * @param {string} type - current parsing context
  30431. * @returns {undefined} void function
  30432. */
  30433. function walk(state, type) {
  30434. const { data } = state;
  30435. // extend the state adding the tree builder instance and the initial data
  30436. const length = data.length;
  30437. // The "count" property is set to 1 when the first tag is found.
  30438. // This becomes the root and precedent text or comments are discarded.
  30439. // So, at the end of the parsing count must be zero.
  30440. if (state.pos < length && state.count) {
  30441. walk(state, eat(state, type));
  30442. }
  30443. }
  30444. /**
  30445. * Function to help iterating on the current parser state
  30446. * @param {ParserState} state - Current parser state
  30447. * @param {string} type - current parsing context
  30448. * @returns {string} parsing context
  30449. */
  30450. function eat(state, type) {
  30451. switch (type) {
  30452. case TAG:
  30453. return tag(state)
  30454. case ATTR:
  30455. return attr(state)
  30456. default:
  30457. return text(state)
  30458. }
  30459. }
  30460. /**
  30461. * Expose the internal constants
  30462. */
  30463. const constants = c;
  30464. /**
  30465. * The nodeTypes definition
  30466. */
  30467. const nodeTypes = types$3;
  30468. const BINDING_TYPES = 'bindingTypes';
  30469. const EACH_BINDING_TYPE = 'EACH';
  30470. const IF_BINDING_TYPE = 'IF';
  30471. const TAG_BINDING_TYPE = 'TAG';
  30472. const SLOT_BINDING_TYPE = 'SLOT';
  30473. const EXPRESSION_TYPES = 'expressionTypes';
  30474. const ATTRIBUTE_EXPRESSION_TYPE = 'ATTRIBUTE';
  30475. const VALUE_EXPRESSION_TYPE = 'VALUE';
  30476. const TEXT_EXPRESSION_TYPE = 'TEXT';
  30477. const EVENT_EXPRESSION_TYPE = 'EVENT';
  30478. const TEMPLATE_FN = 'template';
  30479. const SCOPE = 'scope';
  30480. const GET_COMPONENT_FN = 'getComponent';
  30481. // keys needed to create the DOM bindings
  30482. const BINDING_SELECTOR_KEY = 'selector';
  30483. const BINDING_GET_COMPONENT_KEY = 'getComponent';
  30484. const BINDING_TEMPLATE_KEY = 'template';
  30485. const BINDING_TYPE_KEY = 'type';
  30486. const BINDING_REDUNDANT_ATTRIBUTE_KEY = 'redundantAttribute';
  30487. const BINDING_CONDITION_KEY = 'condition';
  30488. const BINDING_ITEM_NAME_KEY = 'itemName';
  30489. const BINDING_GET_KEY_KEY = 'getKey';
  30490. const BINDING_INDEX_NAME_KEY = 'indexName';
  30491. const BINDING_EVALUATE_KEY = 'evaluate';
  30492. const BINDING_NAME_KEY = 'name';
  30493. const BINDING_SLOTS_KEY = 'slots';
  30494. const BINDING_EXPRESSIONS_KEY = 'expressions';
  30495. const BINDING_CHILD_NODE_INDEX_KEY = 'childNodeIndex';
  30496. // slots keys
  30497. const BINDING_BINDINGS_KEY = 'bindings';
  30498. const BINDING_ID_KEY = 'id';
  30499. const BINDING_HTML_KEY = 'html';
  30500. const BINDING_ATTRIBUTES_KEY = 'attributes';
  30501. // DOM directives
  30502. const IF_DIRECTIVE = 'if';
  30503. const EACH_DIRECTIVE = 'each';
  30504. const KEY_ATTRIBUTE = 'key';
  30505. const SLOT_ATTRIBUTE = 'slot';
  30506. const NAME_ATTRIBUTE = 'name';
  30507. const IS_DIRECTIVE = 'is';
  30508. // Misc
  30509. const DEFAULT_SLOT_NAME = 'default';
  30510. const TEXT_NODE_EXPRESSION_PLACEHOLDER = ' ';
  30511. const BINDING_SELECTOR_PREFIX = 'expr';
  30512. const SLOT_TAG_NODE_NAME = 'slot';
  30513. const PROGRESS_TAG_NODE_NAME = 'progress';
  30514. // Riot Parser constants
  30515. const IS_RAW_NODE = constants.IS_RAW;
  30516. const IS_VOID_NODE = constants.IS_VOID;
  30517. const IS_CUSTOM_NODE = constants.IS_CUSTOM;
  30518. const IS_BOOLEAN_ATTRIBUTE = constants.IS_BOOLEAN;
  30519. const IS_SPREAD_ATTRIBUTE = constants.IS_SPREAD;
  30520. /**
  30521. * True if the node has not expression set nor bindings directives
  30522. * @param {RiotParser.Node} node - riot parser node
  30523. * @returns {boolean} true only if it's a static node that doesn't need bindings or expressions
  30524. */
  30525. function isStaticNode(node) {
  30526. return [
  30527. hasExpressions,
  30528. findEachAttribute,
  30529. findIfAttribute,
  30530. isCustomNode,
  30531. isSlotNode
  30532. ].every(test => !test(node))
  30533. }
  30534. /**
  30535. * Check if a node name is part of the browser or builtin javascript api or it belongs to the current scope
  30536. * @param { types.NodePath } path - containing the current node visited
  30537. * @returns {boolean} true if it's a global api variable
  30538. */
  30539. function isGlobal({ scope, node }) {
  30540. // recursively find the identifier of this AST path
  30541. if (node.object) {
  30542. return isGlobal({ node: node.object, scope })
  30543. }
  30544. return Boolean(
  30545. isRaw(node) ||
  30546. isBuiltinAPI(node) ||
  30547. isBrowserAPI(node) ||
  30548. isNewExpression(node) ||
  30549. isNodeInScope(scope, node)
  30550. )
  30551. }
  30552. /**
  30553. * Checks if the identifier of a given node exists in a scope
  30554. * @param {Scope} scope - scope where to search for the identifier
  30555. * @param {types.Node} node - node to search for the identifier
  30556. * @returns {boolean} true if the node identifier is defined in the given scope
  30557. */
  30558. function isNodeInScope(scope, node) {
  30559. const traverse = (isInScope = false) => {
  30560. types$1.visit(node, {
  30561. visitIdentifier(path) {
  30562. if (scope.lookup(getName$1(path.node))) {
  30563. isInScope = true;
  30564. }
  30565. this.abort();
  30566. }
  30567. });
  30568. return isInScope
  30569. };
  30570. return traverse()
  30571. }
  30572. /**
  30573. * True if the node has the isCustom attribute set
  30574. * @param {RiotParser.Node} node - riot parser node
  30575. * @returns {boolean} true if either it's a riot component or a custom element
  30576. */
  30577. function isCustomNode(node) {
  30578. return !!(node[IS_CUSTOM_NODE] || hasIsAttribute(node))
  30579. }
  30580. /**
  30581. * True the node is <slot>
  30582. * @param {RiotParser.Node} node - riot parser node
  30583. * @returns {boolean} true if it's a slot node
  30584. */
  30585. function isSlotNode(node) {
  30586. return node.name === SLOT_TAG_NODE_NAME
  30587. }
  30588. /**
  30589. * True if the node has the isVoid attribute set
  30590. * @param {RiotParser.Node} node - riot parser node
  30591. * @returns {boolean} true if the node is self closing
  30592. */
  30593. function isVoidNode(node) {
  30594. return !!node[IS_VOID_NODE]
  30595. }
  30596. /**
  30597. * True if the riot parser did find a tag node
  30598. * @param {RiotParser.Node} node - riot parser node
  30599. * @returns {boolean} true only for the tag nodes
  30600. */
  30601. function isTagNode(node) {
  30602. return node.type === nodeTypes.TAG
  30603. }
  30604. /**
  30605. * True if the riot parser did find a text node
  30606. * @param {RiotParser.Node} node - riot parser node
  30607. * @returns {boolean} true only for the text nodes
  30608. */
  30609. function isTextNode(node) {
  30610. return node.type === nodeTypes.TEXT
  30611. }
  30612. /**
  30613. * True if the node parsed is the root one
  30614. * @param {RiotParser.Node} node - riot parser node
  30615. * @returns {boolean} true only for the root nodes
  30616. */
  30617. function isRootNode(node) {
  30618. return node.isRoot
  30619. }
  30620. /**
  30621. * True if the attribute parsed is of type spread one
  30622. * @param {RiotParser.Node} node - riot parser node
  30623. * @returns {boolean} true if the attribute node is of type spread
  30624. */
  30625. function isSpreadAttribute$1(node) {
  30626. return node[IS_SPREAD_ATTRIBUTE]
  30627. }
  30628. /**
  30629. * True if the node is an attribute and its name is "value"
  30630. * @param {RiotParser.Node} node - riot parser node
  30631. * @returns {boolean} true only for value attribute nodes
  30632. */
  30633. function isValueAttribute(node) {
  30634. return node.name === 'value'
  30635. }
  30636. /**
  30637. * True if the DOM node is a progress tag
  30638. * @param {RiotParser.Node} node - riot parser node
  30639. * @returns {boolean} true for the progress tags
  30640. */
  30641. function isProgressNode(node) {
  30642. return node.name === PROGRESS_TAG_NODE_NAME
  30643. }
  30644. /**
  30645. * True if the node is an attribute and a DOM handler
  30646. * @param {RiotParser.Node} node - riot parser node
  30647. * @returns {boolean} true only for dom listener attribute nodes
  30648. */
  30649. const isEventAttribute = (() => {
  30650. const EVENT_ATTR_RE = /^on/;
  30651. return node => EVENT_ATTR_RE.test(node.name)
  30652. })();
  30653. /**
  30654. * True if the node has expressions or expression attributes
  30655. * @param {RiotParser.Node} node - riot parser node
  30656. * @returns {boolean} ditto
  30657. */
  30658. function hasExpressions(node) {
  30659. return !!(
  30660. node.expressions ||
  30661. // has expression attributes
  30662. (getNodeAttributes(node).some(attribute => hasExpressions(attribute))) ||
  30663. // has child text nodes with expressions
  30664. (node.nodes && node.nodes.some(node => isTextNode(node) && hasExpressions(node)))
  30665. )
  30666. }
  30667. /**
  30668. * True if the node is a directive having its own template
  30669. * @param {RiotParser.Node} node - riot parser node
  30670. * @returns {boolean} true only for the IF EACH and TAG bindings
  30671. */
  30672. function hasItsOwnTemplate(node) {
  30673. return [
  30674. findEachAttribute,
  30675. findIfAttribute,
  30676. isCustomNode
  30677. ].some(test => test(node))
  30678. }
  30679. const hasIfAttribute = compose(Boolean, findIfAttribute);
  30680. const hasEachAttribute = compose(Boolean, findEachAttribute);
  30681. const hasIsAttribute = compose(Boolean, findIsAttribute);
  30682. const hasKeyAttribute = compose(Boolean, findKeyAttribute);
  30683. /**
  30684. * Find the attribute node
  30685. * @param { string } name - name of the attribute we want to find
  30686. * @param { riotParser.nodeTypes.TAG } node - a tag node
  30687. * @returns { riotParser.nodeTypes.ATTR } attribute node
  30688. */
  30689. function findAttribute(name, node) {
  30690. return node.attributes && node.attributes.find(attr => getName$1(attr) === name)
  30691. }
  30692. function findIfAttribute(node) {
  30693. return findAttribute(IF_DIRECTIVE, node)
  30694. }
  30695. function findEachAttribute(node) {
  30696. return findAttribute(EACH_DIRECTIVE, node)
  30697. }
  30698. function findKeyAttribute(node) {
  30699. return findAttribute(KEY_ATTRIBUTE, node)
  30700. }
  30701. function findIsAttribute(node) {
  30702. return findAttribute(IS_DIRECTIVE, node)
  30703. }
  30704. /**
  30705. * Find all the node attributes that are not expressions
  30706. * @param {RiotParser.Node} node - riot parser node
  30707. * @returns {Array} list of all the static attributes
  30708. */
  30709. function findStaticAttributes(node) {
  30710. return getNodeAttributes(node).filter(attribute => !hasExpressions(attribute))
  30711. }
  30712. /**
  30713. * Find all the node attributes that have expressions
  30714. * @param {RiotParser.Node} node - riot parser node
  30715. * @returns {Array} list of all the dynamic attributes
  30716. */
  30717. function findDynamicAttributes(node) {
  30718. return getNodeAttributes(node).filter(hasExpressions)
  30719. }
  30720. /**
  30721. * Create a simple attribute expression
  30722. * @param {RiotParser.Node.Attr} sourceNode - the custom tag
  30723. * @param {string} sourceFile - source file path
  30724. * @param {string} sourceCode - original source
  30725. * @returns {AST.Node} object containing the expression binding keys
  30726. */
  30727. function createAttributeExpression(sourceNode, sourceFile, sourceCode) {
  30728. return builders.objectExpression([
  30729. simplePropertyNode(BINDING_TYPE_KEY,
  30730. builders.memberExpression(
  30731. builders.identifier(EXPRESSION_TYPES),
  30732. builders.identifier(ATTRIBUTE_EXPRESSION_TYPE),
  30733. false
  30734. )
  30735. ),
  30736. simplePropertyNode(BINDING_NAME_KEY, isSpreadAttribute$1(sourceNode) ? nullNode() : builders.literal(sourceNode.name)),
  30737. simplePropertyNode(
  30738. BINDING_EVALUATE_KEY,
  30739. createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
  30740. )
  30741. ])
  30742. }
  30743. /**
  30744. * Create a simple event expression
  30745. * @param {RiotParser.Node.Attr} sourceNode - attribute containing the event handlers
  30746. * @param {string} sourceFile - source file path
  30747. * @param {string} sourceCode - original source
  30748. * @returns {AST.Node} object containing the expression binding keys
  30749. */
  30750. function createEventExpression(sourceNode, sourceFile, sourceCode) {
  30751. return builders.objectExpression([
  30752. simplePropertyNode(BINDING_TYPE_KEY,
  30753. builders.memberExpression(
  30754. builders.identifier(EXPRESSION_TYPES),
  30755. builders.identifier(EVENT_EXPRESSION_TYPE),
  30756. false
  30757. )
  30758. ),
  30759. simplePropertyNode(BINDING_NAME_KEY, builders.literal(sourceNode.name)),
  30760. simplePropertyNode(
  30761. BINDING_EVALUATE_KEY,
  30762. createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
  30763. )
  30764. ])
  30765. }
  30766. /**
  30767. * Unescape the user escaped chars
  30768. * @param {string} string - input string
  30769. * @param {string} char - probably a '{' or anything the user want's to escape
  30770. * @returns {string} cleaned up string
  30771. */
  30772. function unescapeChar(string, char) {
  30773. return string.replace(RegExp(`\\\\${char}`, 'gm'), char)
  30774. }
  30775. /**
  30776. * Generate the pure immutable string chunks from a RiotParser.Node.Text
  30777. * @param {RiotParser.Node.Text} node - riot parser text node
  30778. * @param {string} sourceCode sourceCode - source code
  30779. * @returns {Array} array containing the immutable string chunks
  30780. */
  30781. function generateLiteralStringChunksFromNode(node, sourceCode) {
  30782. return node.expressions.reduce((chunks, expression, index) => {
  30783. const start = index ? node.expressions[index - 1].end : node.start;
  30784. const string = sourceCode.substring(start, expression.start);
  30785. // trimStart the first string
  30786. chunks.push(index === 0 ? string.trimStart() : string);
  30787. // add the tail to the string
  30788. if (index === node.expressions.length - 1)
  30789. chunks.push(sourceCode.substring(expression.end, node.end).trimEnd());
  30790. return chunks
  30791. }, [])
  30792. .map(str => node.unescape ? unescapeChar(str, node.unescape) : str)
  30793. }
  30794. /**
  30795. * Simple bindings might contain multiple expressions like for example: "{foo} and {bar}"
  30796. * This helper aims to merge them in a template literal if it's necessary
  30797. * @param {RiotParser.Node} node - riot parser node
  30798. * @param {string} sourceFile - original tag file
  30799. * @param {string} sourceCode - original tag source code
  30800. * @returns { Object } a template literal expression object
  30801. */
  30802. function mergeNodeExpressions(node, sourceFile, sourceCode) {
  30803. if (node.parts.length === 1)
  30804. return transformExpression(node.expressions[0], sourceFile, sourceCode)
  30805. const pureStringChunks = generateLiteralStringChunksFromNode(node, sourceCode);
  30806. const stringsArray = pureStringChunks.reduce((acc, str, index) => {
  30807. const expr = node.expressions[index];
  30808. return [
  30809. ...acc,
  30810. builders.literal(str),
  30811. expr ? transformExpression(expr, sourceFile, sourceCode) : nullNode()
  30812. ]
  30813. }, [])
  30814. // filter the empty literal expressions
  30815. .filter(expr => !isLiteral(expr) || expr.value);
  30816. return createArrayString(stringsArray)
  30817. }
  30818. /**
  30819. * Create a text expression
  30820. * @param {RiotParser.Node.Text} sourceNode - text node to parse
  30821. * @param {string} sourceFile - source file path
  30822. * @param {string} sourceCode - original source
  30823. * @param {number} childNodeIndex - position of the child text node in its parent children nodes
  30824. * @returns {AST.Node} object containing the expression binding keys
  30825. */
  30826. function createTextExpression(sourceNode, sourceFile, sourceCode, childNodeIndex) {
  30827. return builders.objectExpression([
  30828. simplePropertyNode(BINDING_TYPE_KEY,
  30829. builders.memberExpression(
  30830. builders.identifier(EXPRESSION_TYPES),
  30831. builders.identifier(TEXT_EXPRESSION_TYPE),
  30832. false
  30833. )
  30834. ),
  30835. simplePropertyNode(
  30836. BINDING_CHILD_NODE_INDEX_KEY,
  30837. builders.literal(childNodeIndex)
  30838. ),
  30839. simplePropertyNode(
  30840. BINDING_EVALUATE_KEY,
  30841. wrapASTInFunctionWithScope(
  30842. mergeNodeExpressions(sourceNode, sourceFile, sourceCode)
  30843. )
  30844. )
  30845. ])
  30846. }
  30847. function createValueExpression(sourceNode, sourceFile, sourceCode) {
  30848. return builders.objectExpression([
  30849. simplePropertyNode(BINDING_TYPE_KEY,
  30850. builders.memberExpression(
  30851. builders.identifier(EXPRESSION_TYPES),
  30852. builders.identifier(VALUE_EXPRESSION_TYPE),
  30853. false
  30854. )
  30855. ),
  30856. simplePropertyNode(
  30857. BINDING_EVALUATE_KEY,
  30858. createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode)
  30859. )
  30860. ])
  30861. }
  30862. function createExpression(sourceNode, sourceFile, sourceCode, childNodeIndex, parentNode) {
  30863. switch (true) {
  30864. case isTextNode(sourceNode):
  30865. return createTextExpression(sourceNode, sourceFile, sourceCode, childNodeIndex)
  30866. // progress nodes value attributes will be rendered as attributes
  30867. // see https://github.com/riot/compiler/issues/122
  30868. case isValueAttribute(sourceNode) && hasValueAttribute(parentNode.name) && !isProgressNode(parentNode):
  30869. return createValueExpression(sourceNode, sourceFile, sourceCode)
  30870. case isEventAttribute(sourceNode):
  30871. return createEventExpression(sourceNode, sourceFile, sourceCode)
  30872. default:
  30873. return createAttributeExpression(sourceNode, sourceFile, sourceCode)
  30874. }
  30875. }
  30876. /**
  30877. * Create the attribute expressions
  30878. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  30879. * @param {string} sourceFile - source file path
  30880. * @param {string} sourceCode - original source
  30881. * @returns {Array} array containing all the attribute expressions
  30882. */
  30883. function createAttributeExpressions(sourceNode, sourceFile, sourceCode) {
  30884. return findDynamicAttributes(sourceNode)
  30885. .map(attribute => createExpression(attribute, sourceFile, sourceCode, 0, sourceNode))
  30886. }
  30887. const scope$1 = builders.identifier(SCOPE);
  30888. const getName$1 = node => node && node.name ? node.name : node;
  30889. /**
  30890. * Replace the path scope with a member Expression
  30891. * @param { types.NodePath } path - containing the current node visited
  30892. * @param { types.Node } property - node we want to prefix with the scope identifier
  30893. * @returns {undefined} this is a void function
  30894. */
  30895. function replacePathScope(path, property) {
  30896. path.replace(builders.memberExpression(
  30897. scope$1,
  30898. property,
  30899. false
  30900. ));
  30901. }
  30902. /**
  30903. * Change the nodes scope adding the `scope` prefix
  30904. * @param { types.NodePath } path - containing the current node visited
  30905. * @returns { boolean } return false if we want to stop the tree traversal
  30906. * @context { types.visit }
  30907. */
  30908. function updateNodeScope(path) {
  30909. if (!isGlobal(path)) {
  30910. replacePathScope(path, path.node);
  30911. return false
  30912. }
  30913. this.traverse(path);
  30914. }
  30915. /**
  30916. * Change the scope of the member expressions
  30917. * @param { types.NodePath } path - containing the current node visited
  30918. * @returns { boolean } return always false because we want to check only the first node object
  30919. */
  30920. function visitMemberExpression(path) {
  30921. if (!isGlobal(path)) {
  30922. if (path.value.computed) {
  30923. this.traverse(path);
  30924. } else if (isBinaryExpression(path.node.object) || path.node.object.computed) {
  30925. this.traverse(path.get('object'));
  30926. } else if (!path.node.object.callee) {
  30927. replacePathScope(path, isThisExpression(path.node.object) ? path.node.property : path.node);
  30928. } else {
  30929. this.traverse(path.get('object'));
  30930. }
  30931. }
  30932. return false
  30933. }
  30934. /**
  30935. * Objects properties should be handled a bit differently from the Identifier
  30936. * @param { types.NodePath } path - containing the current node visited
  30937. * @returns { boolean } return false if we want to stop the tree traversal
  30938. */
  30939. function visitProperty(path) {
  30940. const value = path.node.value;
  30941. if (isIdentifier(value)) {
  30942. updateNodeScope(path.get('value'));
  30943. } else {
  30944. this.traverse(path.get('value'));
  30945. }
  30946. return false
  30947. }
  30948. /**
  30949. * The this expressions should be replaced with the scope
  30950. * @param { types.NodePath } path - containing the current node visited
  30951. * @returns { boolean|undefined } return false if we want to stop the tree traversal
  30952. */
  30953. function visitThisExpression(path) {
  30954. path.replace(scope$1);
  30955. this.traverse(path);
  30956. }
  30957. /**
  30958. * Update the scope of the global nodes
  30959. * @param { Object } ast - ast program
  30960. * @returns { Object } the ast program with all the global nodes updated
  30961. */
  30962. function updateNodesScope(ast) {
  30963. const ignorePath = () => false;
  30964. types$1.visit(ast, {
  30965. visitIdentifier: updateNodeScope,
  30966. visitMemberExpression,
  30967. visitProperty,
  30968. visitThisExpression,
  30969. visitClassExpression: ignorePath
  30970. });
  30971. return ast
  30972. }
  30973. /**
  30974. * Convert any expression to an AST tree
  30975. * @param { Object } expression - expression parsed by the riot parser
  30976. * @param { string } sourceFile - original tag file
  30977. * @param { string } sourceCode - original tag source code
  30978. * @returns { Object } the ast generated
  30979. */
  30980. function createASTFromExpression(expression, sourceFile, sourceCode) {
  30981. const code = sourceFile ?
  30982. addLineOffset(expression.text, sourceCode, expression) :
  30983. expression.text;
  30984. return generateAST(`(${code})`, {
  30985. sourceFileName: sourceFile
  30986. })
  30987. }
  30988. /**
  30989. * Create the bindings template property
  30990. * @param {Array} args - arguments to pass to the template function
  30991. * @returns {ASTNode} a binding template key
  30992. */
  30993. function createTemplateProperty(args) {
  30994. return simplePropertyNode(
  30995. BINDING_TEMPLATE_KEY,
  30996. args ? callTemplateFunction(...args) : nullNode()
  30997. )
  30998. }
  30999. /**
  31000. * Try to get the expression of an attribute node
  31001. * @param { RiotParser.Node.Attribute } attribute - riot parser attribute node
  31002. * @returns { RiotParser.Node.Expression } attribute expression value
  31003. */
  31004. function getAttributeExpression(attribute) {
  31005. return attribute.expressions ? attribute.expressions[0] : {
  31006. // if no expression was found try to typecast the attribute value
  31007. ...attribute,
  31008. text: attribute.value
  31009. }
  31010. }
  31011. /**
  31012. * Wrap the ast generated in a function call providing the scope argument
  31013. * @param {Object} ast - function body
  31014. * @returns {FunctionExpresion} function having the scope argument injected
  31015. */
  31016. function wrapASTInFunctionWithScope(ast) {
  31017. return builders.functionExpression(
  31018. null,
  31019. [scope$1],
  31020. builders.blockStatement([builders.returnStatement(
  31021. ast
  31022. )])
  31023. )
  31024. }
  31025. /**
  31026. * Convert any parser option to a valid template one
  31027. * @param { RiotParser.Node.Expression } expression - expression parsed by the riot parser
  31028. * @param { string } sourceFile - original tag file
  31029. * @param { string } sourceCode - original tag source code
  31030. * @returns { Object } a FunctionExpression object
  31031. *
  31032. * @example
  31033. * toScopedFunction('foo + bar') // scope.foo + scope.bar
  31034. *
  31035. * @example
  31036. * toScopedFunction('foo.baz + bar') // scope.foo.baz + scope.bar
  31037. */
  31038. function toScopedFunction(expression, sourceFile, sourceCode) {
  31039. return compose(
  31040. wrapASTInFunctionWithScope,
  31041. transformExpression
  31042. )(expression, sourceFile, sourceCode)
  31043. }
  31044. /**
  31045. * Transform an expression node updating its global scope
  31046. * @param {RiotParser.Node.Expr} expression - riot parser expression node
  31047. * @param {string} sourceFile - source file
  31048. * @param {string} sourceCode - source code
  31049. * @returns {ASTExpression} ast expression generated from the riot parser expression node
  31050. */
  31051. function transformExpression(expression, sourceFile, sourceCode) {
  31052. return compose(
  31053. getExpressionAST,
  31054. updateNodesScope,
  31055. createASTFromExpression
  31056. )(expression, sourceFile, sourceCode)
  31057. }
  31058. /**
  31059. * Get the parsed AST expression of riot expression node
  31060. * @param {AST.Program} sourceAST - raw node parsed
  31061. * @returns {AST.Expression} program expression output
  31062. */
  31063. function getExpressionAST(sourceAST) {
  31064. const astBody = sourceAST.program.body;
  31065. return astBody[0] ? astBody[0].expression : astBody
  31066. }
  31067. /**
  31068. * Create the template call function
  31069. * @param {Array|string|Node.Literal} template - template string
  31070. * @param {Array<AST.Nodes>} bindings - template bindings provided as AST nodes
  31071. * @returns {Node.CallExpression} template call expression
  31072. */
  31073. function callTemplateFunction(template, bindings) {
  31074. return builders.callExpression(builders.identifier(TEMPLATE_FN), [
  31075. template ? builders.literal(template) : nullNode(),
  31076. bindings ? builders.arrayExpression(bindings) : nullNode()
  31077. ])
  31078. }
  31079. /**
  31080. * Convert any DOM attribute into a valid DOM selector useful for the querySelector API
  31081. * @param { string } attributeName - name of the attribute to query
  31082. * @returns { string } the attribute transformed to a query selector
  31083. */
  31084. const attributeNameToDOMQuerySelector = attributeName => `[${attributeName}]`;
  31085. /**
  31086. * Create the properties to query a DOM node
  31087. * @param { string } attributeName - attribute name needed to identify a DOM node
  31088. * @returns { Array<AST.Node> } array containing the selector properties needed for the binding
  31089. */
  31090. function createSelectorProperties(attributeName) {
  31091. return attributeName ? [
  31092. simplePropertyNode(BINDING_REDUNDANT_ATTRIBUTE_KEY, builders.literal(attributeName)),
  31093. simplePropertyNode(BINDING_SELECTOR_KEY,
  31094. compose(builders.literal, attributeNameToDOMQuerySelector)(attributeName)
  31095. )
  31096. ] : []
  31097. }
  31098. /**
  31099. * Clone the node filtering out the selector attribute from the attributes list
  31100. * @param {RiotParser.Node} node - riot parser node
  31101. * @param {string} selectorAttribute - name of the selector attribute to filter out
  31102. * @returns {RiotParser.Node} the node with the attribute cleaned up
  31103. */
  31104. function cloneNodeWithoutSelectorAttribute(node, selectorAttribute) {
  31105. return {
  31106. ...node,
  31107. attributes: getAttributesWithoutSelector(getNodeAttributes(node), selectorAttribute)
  31108. }
  31109. }
  31110. /**
  31111. * Get the node attributes without the selector one
  31112. * @param {Array<RiotParser.Attr>} attributes - attributes list
  31113. * @param {string} selectorAttribute - name of the selector attribute to filter out
  31114. * @returns {Array<RiotParser.Attr>} filtered attributes
  31115. */
  31116. function getAttributesWithoutSelector(attributes, selectorAttribute) {
  31117. if (selectorAttribute)
  31118. return attributes.filter(attribute => attribute.name !== selectorAttribute)
  31119. return attributes
  31120. }
  31121. /**
  31122. * Clean binding or custom attributes
  31123. * @param {RiotParser.Node} node - riot parser node
  31124. * @returns {Array<RiotParser.Node.Attr>} only the attributes that are not bindings or directives
  31125. */
  31126. function cleanAttributes(node) {
  31127. return getNodeAttributes(node).filter(attribute => ![
  31128. IF_DIRECTIVE,
  31129. EACH_DIRECTIVE,
  31130. KEY_ATTRIBUTE,
  31131. SLOT_ATTRIBUTE,
  31132. IS_DIRECTIVE
  31133. ].includes(attribute.name))
  31134. }
  31135. /**
  31136. * Create a root node proxing only its nodes and attributes
  31137. * @param {RiotParser.Node} node - riot parser node
  31138. * @returns {RiotParser.Node} root node
  31139. */
  31140. function createRootNode(node) {
  31141. return {
  31142. nodes: getChildrenNodes(node),
  31143. isRoot: true,
  31144. attributes: compose(
  31145. // root nodes should always have attribute expressions
  31146. transformStatiAttributesIntoExpressions,
  31147. // root nodes shuold't have directives
  31148. cleanAttributes
  31149. )(node)
  31150. }
  31151. }
  31152. /**
  31153. * Transform the static node attributes into expressions, useful for the root nodes
  31154. * @param {Array<RiotParser.Node.Attr>} attributes - riot parser node
  31155. * @returns {Array<RiotParser.Node.Attr>} all the attributes received as attribute expressions
  31156. */
  31157. function transformStatiAttributesIntoExpressions(attributes) {
  31158. return attributes.map(attribute => {
  31159. if (attribute.expressions) return attribute
  31160. return {
  31161. ...attribute,
  31162. expressions: [{
  31163. start: attribute.valueStart,
  31164. end: attribute.end,
  31165. text: `'${attribute.value}'`
  31166. }]
  31167. }
  31168. })
  31169. }
  31170. /**
  31171. * Get all the child nodes of a RiotParser.Node
  31172. * @param {RiotParser.Node} node - riot parser node
  31173. * @returns {Array<RiotParser.Node>} all the child nodes found
  31174. */
  31175. function getChildrenNodes(node) {
  31176. return node && node.nodes ? node.nodes : []
  31177. }
  31178. /**
  31179. * Get all the attributes of a riot parser node
  31180. * @param {RiotParser.Node} node - riot parser node
  31181. * @returns {Array<RiotParser.Node.Attribute>} all the attributes find
  31182. */
  31183. function getNodeAttributes(node) {
  31184. return node.attributes ? node.attributes : []
  31185. }
  31186. /**
  31187. * Get the name of a custom node transforming it into an expression node
  31188. * @param {RiotParser.Node} node - riot parser node
  31189. * @returns {RiotParser.Node.Attr} the node name as expression attribute
  31190. */
  31191. function getCustomNodeNameAsExpression(node) {
  31192. const isAttribute = findIsAttribute(node);
  31193. const toRawString = val => `'${val}'`;
  31194. if (isAttribute) {
  31195. return isAttribute.expressions ? isAttribute.expressions[0] : {
  31196. ...isAttribute,
  31197. text: toRawString(isAttribute.value)
  31198. }
  31199. }
  31200. return { ...node, text: toRawString(getName$1(node)) }
  31201. }
  31202. /**
  31203. * Convert all the node static attributes to strings
  31204. * @param {RiotParser.Node} node - riot parser node
  31205. * @returns {string} all the node static concatenated as string
  31206. */
  31207. function staticAttributesToString(node) {
  31208. return findStaticAttributes(node)
  31209. .map(attribute => attribute[IS_BOOLEAN_ATTRIBUTE] || !attribute.value ?
  31210. attribute.name :
  31211. `${attribute.name}="${unescapeNode(attribute, 'value').value}"`
  31212. ).join(' ')
  31213. }
  31214. /**
  31215. * Make sure that node escaped chars will be unescaped
  31216. * @param {RiotParser.Node} node - riot parser node
  31217. * @param {string} key - key property to unescape
  31218. * @returns {RiotParser.Node} node with the text property unescaped
  31219. */
  31220. function unescapeNode(node, key) {
  31221. if (node.unescape) {
  31222. return {
  31223. ...node,
  31224. [key]: unescapeChar(node[key], node.unescape)
  31225. }
  31226. }
  31227. return node
  31228. }
  31229. /**
  31230. * Convert a riot parser opening node into a string
  31231. * @param {RiotParser.Node} node - riot parser node
  31232. * @returns {string} the node as string
  31233. */
  31234. function nodeToString(node) {
  31235. const attributes = staticAttributesToString(node);
  31236. switch(true) {
  31237. case isTagNode(node):
  31238. return `<${node.name}${attributes ? ` ${attributes}` : ''}${isVoidNode(node) ? '/' : ''}>`
  31239. case isTextNode(node):
  31240. return hasExpressions(node) ? TEXT_NODE_EXPRESSION_PLACEHOLDER : unescapeNode(node, 'text').text
  31241. default:
  31242. return ''
  31243. }
  31244. }
  31245. /**
  31246. * Close an html node
  31247. * @param {RiotParser.Node} node - riot parser node
  31248. * @returns {string} the closing tag of the html tag node passed to this function
  31249. */
  31250. function closeTag(node) {
  31251. return node.name ? `</${node.name}>` : ''
  31252. }
  31253. /**
  31254. * Create a strings array with the `join` call to transform it into a string
  31255. * @param {Array} stringsArray - array containing all the strings to concatenate
  31256. * @returns {AST.CallExpression} array with a `join` call
  31257. */
  31258. function createArrayString(stringsArray) {
  31259. return builders.callExpression(
  31260. builders.memberExpression(
  31261. builders.arrayExpression(stringsArray),
  31262. builders.identifier('join'),
  31263. false
  31264. ),
  31265. [builders.literal('')]
  31266. )
  31267. }
  31268. /**
  31269. * Simple expression bindings might contain multiple expressions like for example: "class="{foo} red {bar}""
  31270. * This helper aims to merge them in a template literal if it's necessary
  31271. * @param {RiotParser.Attr} node - riot parser node
  31272. * @param {string} sourceFile - original tag file
  31273. * @param {string} sourceCode - original tag source code
  31274. * @returns { Object } a template literal expression object
  31275. */
  31276. function mergeAttributeExpressions(node, sourceFile, sourceCode) {
  31277. if (!node.parts || node.parts.length === 1) {
  31278. return transformExpression(node.expressions[0], sourceFile, sourceCode)
  31279. }
  31280. const stringsArray = [
  31281. ...node.parts.reduce((acc, str) => {
  31282. const expression = node.expressions.find(e => e.text.trim() === str);
  31283. return [
  31284. ...acc,
  31285. expression ? transformExpression(expression, sourceFile, sourceCode) : builders.literal(str)
  31286. ]
  31287. }, [])
  31288. ].filter(expr => !isLiteral(expr) || expr.value);
  31289. return createArrayString(stringsArray)
  31290. }
  31291. /**
  31292. * Create a selector that will be used to find the node via dom-bindings
  31293. * @param {number} id - temporary variable that will be increased anytime this function will be called
  31294. * @returns {string} selector attribute needed to bind a riot expression
  31295. */
  31296. const createBindingSelector = (function createSelector(id = 0) {
  31297. return () => `${BINDING_SELECTOR_PREFIX}${id++}`
  31298. }());
  31299. /**
  31300. * Create the AST array containing the attributes to bind to this node
  31301. * @param { RiotParser.Node.Tag } sourceNode - the custom tag
  31302. * @param { string } selectorAttribute - attribute needed to select the target node
  31303. * @param { string } sourceFile - source file path
  31304. * @param { string } sourceCode - original source
  31305. * @returns {AST.ArrayExpression} array containing the slot objects
  31306. */
  31307. function createBindingAttributes(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31308. return builders.arrayExpression([
  31309. ...compose(
  31310. attributes => attributes.map(attribute => createExpression(attribute, sourceFile, sourceCode, 0, sourceNode)),
  31311. attributes => getAttributesWithoutSelector(attributes, selectorAttribute),
  31312. cleanAttributes
  31313. )(sourceNode)
  31314. ])
  31315. }
  31316. /**
  31317. * Create an attribute evaluation function
  31318. * @param {RiotParser.Attr} sourceNode - riot parser node
  31319. * @param {string} sourceFile - original tag file
  31320. * @param {string} sourceCode - original tag source code
  31321. * @returns { AST.Node } an AST function expression to evaluate the attribute value
  31322. */
  31323. function createAttributeEvaluationFunction(sourceNode, sourceFile, sourceCode) {
  31324. return hasExpressions(sourceNode) ?
  31325. // dynamic attribute
  31326. wrapASTInFunctionWithScope(mergeAttributeExpressions(sourceNode, sourceFile, sourceCode)) :
  31327. // static attribute
  31328. builders.functionExpression(
  31329. null,
  31330. [],
  31331. builders.blockStatement([
  31332. builders.returnStatement(builders.literal(sourceNode.value || true))
  31333. ])
  31334. )
  31335. }
  31336. /**
  31337. * Simple clone deep function, do not use it for classes or recursive objects!
  31338. * @param {*} source - possibily an object to clone
  31339. * @returns {*} the object we wanted to clone
  31340. */
  31341. function cloneDeep(source) {
  31342. return JSON.parse(JSON.stringify(source))
  31343. }
  31344. const getEachItemName = expression => isSequenceExpression(expression.left) ? expression.left.expressions[0] : expression.left;
  31345. const getEachIndexName = expression => isSequenceExpression(expression.left) ? expression.left.expressions[1] : null;
  31346. const getEachValue = expression => expression.right;
  31347. const nameToliteral = compose(builders.literal, getName$1);
  31348. const generateEachItemNameKey = expression => simplePropertyNode(
  31349. BINDING_ITEM_NAME_KEY,
  31350. compose(nameToliteral, getEachItemName)(expression)
  31351. );
  31352. const generateEachIndexNameKey = expression => simplePropertyNode(
  31353. BINDING_INDEX_NAME_KEY,
  31354. compose(nameToliteral, getEachIndexName)(expression)
  31355. );
  31356. const generateEachEvaluateKey = (expression, eachExpression, sourceFile, sourceCode) => simplePropertyNode(
  31357. BINDING_EVALUATE_KEY,
  31358. compose(
  31359. e => toScopedFunction(e, sourceFile, sourceCode),
  31360. e => ({
  31361. ...eachExpression,
  31362. text: generateJavascript(e).code
  31363. }),
  31364. getEachValue
  31365. )(expression)
  31366. );
  31367. /**
  31368. * Get the each expression properties to create properly the template binding
  31369. * @param { DomBinding.Expression } eachExpression - original each expression data
  31370. * @param { string } sourceFile - original tag file
  31371. * @param { string } sourceCode - original tag source code
  31372. * @returns { Array } AST nodes that are needed to build an each binding
  31373. */
  31374. function generateEachExpressionProperties(eachExpression, sourceFile, sourceCode) {
  31375. const ast = createASTFromExpression(eachExpression, sourceFile, sourceCode);
  31376. const body = ast.program.body;
  31377. const firstNode = body[0];
  31378. if (!isExpressionStatement(firstNode)) {
  31379. panic(`The each directives supported should be of type "ExpressionStatement",you have provided a "${firstNode.type}"`);
  31380. }
  31381. const { expression } = firstNode;
  31382. return [
  31383. generateEachItemNameKey(expression),
  31384. generateEachIndexNameKey(expression),
  31385. generateEachEvaluateKey(expression, eachExpression, sourceFile, sourceCode)
  31386. ]
  31387. }
  31388. /**
  31389. * Transform a RiotParser.Node.Tag into an each binding
  31390. * @param { RiotParser.Node.Tag } sourceNode - tag containing the each attribute
  31391. * @param { string } selectorAttribute - attribute needed to select the target node
  31392. * @param { string } sourceFile - source file path
  31393. * @param { string } sourceCode - original source
  31394. * @returns { AST.Node } an each binding node
  31395. */
  31396. function createEachBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31397. const [ifAttribute, eachAttribute, keyAttribute] = [
  31398. findIfAttribute,
  31399. findEachAttribute,
  31400. findKeyAttribute
  31401. ].map(f => f(sourceNode));
  31402. const attributeOrNull = attribute => attribute ? toScopedFunction(getAttributeExpression(attribute), sourceFile, sourceCode) : nullNode();
  31403. return builders.objectExpression([
  31404. simplePropertyNode(BINDING_TYPE_KEY,
  31405. builders.memberExpression(
  31406. builders.identifier(BINDING_TYPES),
  31407. builders.identifier(EACH_BINDING_TYPE),
  31408. false
  31409. )
  31410. ),
  31411. simplePropertyNode(BINDING_GET_KEY_KEY, attributeOrNull(keyAttribute)),
  31412. simplePropertyNode(BINDING_CONDITION_KEY, attributeOrNull(ifAttribute)),
  31413. createTemplateProperty(createNestedBindings(sourceNode, sourceFile, sourceCode, selectorAttribute)),
  31414. ...createSelectorProperties(selectorAttribute),
  31415. ...compose(generateEachExpressionProperties, getAttributeExpression)(eachAttribute)
  31416. ])
  31417. }
  31418. /**
  31419. * Transform a RiotParser.Node.Tag into an if binding
  31420. * @param { RiotParser.Node.Tag } sourceNode - tag containing the if attribute
  31421. * @param { string } selectorAttribute - attribute needed to select the target node
  31422. * @param { stiring } sourceFile - source file path
  31423. * @param { string } sourceCode - original source
  31424. * @returns { AST.Node } an if binding node
  31425. */
  31426. function createIfBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31427. const ifAttribute = findIfAttribute(sourceNode);
  31428. return builders.objectExpression([
  31429. simplePropertyNode(BINDING_TYPE_KEY,
  31430. builders.memberExpression(
  31431. builders.identifier(BINDING_TYPES),
  31432. builders.identifier(IF_BINDING_TYPE),
  31433. false
  31434. )
  31435. ),
  31436. simplePropertyNode(
  31437. BINDING_EVALUATE_KEY,
  31438. toScopedFunction(ifAttribute.expressions[0], sourceFile, sourceCode)
  31439. ),
  31440. ...createSelectorProperties(selectorAttribute),
  31441. createTemplateProperty(createNestedBindings(sourceNode, sourceFile, sourceCode, selectorAttribute))
  31442. ])
  31443. }
  31444. /**
  31445. * Create the text node expressions
  31446. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31447. * @param {string} sourceFile - source file path
  31448. * @param {string} sourceCode - original source
  31449. * @returns {Array} array containing all the text node expressions
  31450. */
  31451. function createTextNodeExpressions(sourceNode, sourceFile, sourceCode) {
  31452. const childrenNodes = getChildrenNodes(sourceNode);
  31453. return childrenNodes
  31454. .filter(isTextNode)
  31455. .filter(hasExpressions)
  31456. .map(node => createExpression(
  31457. node,
  31458. sourceFile,
  31459. sourceCode,
  31460. childrenNodes.indexOf(node),
  31461. sourceNode
  31462. ))
  31463. }
  31464. /**
  31465. * Add a simple binding to a riot parser node
  31466. * @param { RiotParser.Node.Tag } sourceNode - tag containing the if attribute
  31467. * @param { string } selectorAttribute - attribute needed to select the target node
  31468. * @param { string } sourceFile - source file path
  31469. * @param { string } sourceCode - original source
  31470. * @returns { AST.Node } an each binding node
  31471. */
  31472. function createSimpleBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31473. return builders.objectExpression([
  31474. ...createSelectorProperties(selectorAttribute),
  31475. simplePropertyNode(
  31476. BINDING_EXPRESSIONS_KEY,
  31477. builders.arrayExpression([
  31478. ...createTextNodeExpressions(sourceNode, sourceFile, sourceCode),
  31479. ...createAttributeExpressions(sourceNode, sourceFile, sourceCode)
  31480. ])
  31481. )
  31482. ])
  31483. }
  31484. /**
  31485. * Transform a RiotParser.Node.Tag of type slot into a slot binding
  31486. * @param { RiotParser.Node.Tag } sourceNode - slot node
  31487. * @param { string } selectorAttribute - attribute needed to select the target node
  31488. * @param { string } sourceFile - source file path
  31489. * @param { string } sourceCode - original source
  31490. * @returns { AST.Node } a slot binding node
  31491. */
  31492. function createSlotBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31493. const slotNameAttribute = findAttribute(NAME_ATTRIBUTE, sourceNode);
  31494. const slotName = slotNameAttribute ? slotNameAttribute.value : DEFAULT_SLOT_NAME;
  31495. return builders.objectExpression([
  31496. simplePropertyNode(BINDING_TYPE_KEY,
  31497. builders.memberExpression(
  31498. builders.identifier(BINDING_TYPES),
  31499. builders.identifier(SLOT_BINDING_TYPE),
  31500. false
  31501. )
  31502. ),
  31503. simplePropertyNode(
  31504. BINDING_ATTRIBUTES_KEY,
  31505. createBindingAttributes({
  31506. ...sourceNode,
  31507. // filter the name attribute
  31508. attributes: getNodeAttributes(sourceNode)
  31509. .filter(attribute => getName$1(attribute) !== NAME_ATTRIBUTE)
  31510. },
  31511. selectorAttribute,
  31512. sourceFile,
  31513. sourceCode)
  31514. ),
  31515. simplePropertyNode(
  31516. BINDING_NAME_KEY,
  31517. builders.literal(slotName)
  31518. ),
  31519. ...createSelectorProperties(selectorAttribute)
  31520. ])
  31521. }
  31522. /**
  31523. * Find the slots in the current component and group them under the same id
  31524. * @param {RiotParser.Node.Tag} sourceNode - the custom tag
  31525. * @returns {Object} object containing all the slots grouped by name
  31526. */
  31527. function groupSlots(sourceNode) {
  31528. return getChildrenNodes(sourceNode).reduce((acc, node) => {
  31529. const slotAttribute = findSlotAttribute(node);
  31530. if (slotAttribute) {
  31531. acc[slotAttribute.value] = node;
  31532. } else {
  31533. acc.default = createRootNode({
  31534. nodes: [...getChildrenNodes(acc.default), node]
  31535. });
  31536. }
  31537. return acc
  31538. }, {
  31539. default: null
  31540. })
  31541. }
  31542. /**
  31543. * Create the slot entity to pass to the riot-dom bindings
  31544. * @param {string} id - slot id
  31545. * @param {RiotParser.Node.Tag} sourceNode - slot root node
  31546. * @param {string} sourceFile - source file path
  31547. * @param {string} sourceCode - original source
  31548. * @returns {AST.Node} ast node containing the slot object properties
  31549. */
  31550. function buildSlot(id, sourceNode, sourceFile, sourceCode) {
  31551. const cloneNode = {
  31552. ...sourceNode,
  31553. // avoid to render the slot attribute
  31554. attributes: getNodeAttributes(sourceNode).filter(attribute => attribute.name !== SLOT_ATTRIBUTE)
  31555. };
  31556. const [html, bindings] = build(cloneNode, sourceFile, sourceCode);
  31557. return builders.objectExpression([
  31558. simplePropertyNode(BINDING_ID_KEY, builders.literal(id)),
  31559. simplePropertyNode(BINDING_HTML_KEY, builders.literal(html)),
  31560. simplePropertyNode(BINDING_BINDINGS_KEY, builders.arrayExpression(bindings))
  31561. ])
  31562. }
  31563. /**
  31564. * Create the AST array containing the slots
  31565. * @param { RiotParser.Node.Tag } sourceNode - the custom tag
  31566. * @param { string } sourceFile - source file path
  31567. * @param { string } sourceCode - original source
  31568. * @returns {AST.ArrayExpression} array containing the attributes to bind
  31569. */
  31570. function createSlotsArray(sourceNode, sourceFile, sourceCode) {
  31571. return builders.arrayExpression([
  31572. ...compose(
  31573. slots => slots.map(([key, value]) => buildSlot(key, value, sourceFile, sourceCode)),
  31574. slots => slots.filter(([,value]) => value),
  31575. Object.entries,
  31576. groupSlots
  31577. )(sourceNode)
  31578. ])
  31579. }
  31580. /**
  31581. * Find the slot attribute if it exists
  31582. * @param {RiotParser.Node.Tag} sourceNode - the custom tag
  31583. * @returns {RiotParser.Node.Attr|undefined} the slot attribute found
  31584. */
  31585. function findSlotAttribute(sourceNode) {
  31586. return getNodeAttributes(sourceNode).find(attribute => attribute.name === SLOT_ATTRIBUTE)
  31587. }
  31588. /**
  31589. * Transform a RiotParser.Node.Tag into a tag binding
  31590. * @param { RiotParser.Node.Tag } sourceNode - the custom tag
  31591. * @param { string } selectorAttribute - attribute needed to select the target node
  31592. * @param { string } sourceFile - source file path
  31593. * @param { string } sourceCode - original source
  31594. * @returns { AST.Node } tag binding node
  31595. */
  31596. function createTagBinding(sourceNode, selectorAttribute, sourceFile, sourceCode) {
  31597. return builders.objectExpression([
  31598. simplePropertyNode(BINDING_TYPE_KEY,
  31599. builders.memberExpression(
  31600. builders.identifier(BINDING_TYPES),
  31601. builders.identifier(TAG_BINDING_TYPE),
  31602. false
  31603. )
  31604. ),
  31605. simplePropertyNode(BINDING_GET_COMPONENT_KEY, builders.identifier(GET_COMPONENT_FN)),
  31606. simplePropertyNode(
  31607. BINDING_EVALUATE_KEY,
  31608. toScopedFunction(getCustomNodeNameAsExpression(sourceNode), sourceFile, sourceCode)
  31609. ),
  31610. simplePropertyNode(BINDING_SLOTS_KEY, createSlotsArray(sourceNode, sourceFile, sourceCode)),
  31611. simplePropertyNode(
  31612. BINDING_ATTRIBUTES_KEY,
  31613. createBindingAttributes(sourceNode, selectorAttribute, sourceFile, sourceCode)
  31614. ),
  31615. ...createSelectorProperties(selectorAttribute)
  31616. ])
  31617. }
  31618. const BuildingState = Object.freeze({
  31619. html: [],
  31620. bindings: [],
  31621. parent: null
  31622. });
  31623. /**
  31624. * Nodes having bindings should be cloned and new selector properties should be added to them
  31625. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31626. * @param {string} bindingsSelector - temporary string to identify the current node
  31627. * @returns {RiotParser.Node} the original node parsed having the new binding selector attribute
  31628. */
  31629. function createBindingsTag(sourceNode, bindingsSelector) {
  31630. if (!bindingsSelector) return sourceNode
  31631. return {
  31632. ...sourceNode,
  31633. // inject the selector bindings into the node attributes
  31634. attributes: [{
  31635. name: bindingsSelector,
  31636. value: bindingsSelector
  31637. }, ...getNodeAttributes(sourceNode)]
  31638. }
  31639. }
  31640. /**
  31641. * Create a generic dynamic node (text or tag) and generate its bindings
  31642. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31643. * @param {string} sourceFile - source file path
  31644. * @param {string} sourceCode - original source
  31645. * @param {BuildingState} state - state representing the current building tree state during the recursion
  31646. * @returns {Array} array containing the html output and bindings for the current node
  31647. */
  31648. function createDynamicNode(sourceNode, sourceFile, sourceCode, state) {
  31649. switch (true) {
  31650. case isTextNode(sourceNode):
  31651. // text nodes will not have any bindings
  31652. return [nodeToString(sourceNode), []]
  31653. default:
  31654. return createTagWithBindings(sourceNode, sourceFile, sourceCode)
  31655. }
  31656. }
  31657. /**
  31658. * Create only a dynamic tag node with generating a custom selector and its bindings
  31659. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31660. * @param {string} sourceFile - source file path
  31661. * @param {string} sourceCode - original source
  31662. * @param {BuildingState} state - state representing the current building tree state during the recursion
  31663. * @returns {Array} array containing the html output and bindings for the current node
  31664. */
  31665. function createTagWithBindings(sourceNode, sourceFile, sourceCode) {
  31666. const bindingsSelector = isRootNode(sourceNode) ? null : createBindingSelector();
  31667. const cloneNode = createBindingsTag(sourceNode, bindingsSelector);
  31668. const tagOpeningHTML = nodeToString(cloneNode);
  31669. switch(true) {
  31670. // EACH bindings have prio 1
  31671. case hasEachAttribute(cloneNode):
  31672. return [tagOpeningHTML, [createEachBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
  31673. // IF bindings have prio 2
  31674. case hasIfAttribute(cloneNode):
  31675. return [tagOpeningHTML, [createIfBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
  31676. // TAG bindings have prio 3
  31677. case isCustomNode(cloneNode):
  31678. return [tagOpeningHTML, [createTagBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
  31679. // slot tag
  31680. case isSlotNode(cloneNode):
  31681. return [tagOpeningHTML, [createSlotBinding(cloneNode, bindingsSelector)]]
  31682. // this node has expressions bound to it
  31683. default:
  31684. return [tagOpeningHTML, [createSimpleBinding(cloneNode, bindingsSelector, sourceFile, sourceCode)]]
  31685. }
  31686. }
  31687. /**
  31688. * Parse a node trying to extract its template and bindings
  31689. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31690. * @param {string} sourceFile - source file path
  31691. * @param {string} sourceCode - original source
  31692. * @param {BuildingState} state - state representing the current building tree state during the recursion
  31693. * @returns {Array} array containing the html output and bindings for the current node
  31694. */
  31695. function parseNode(sourceNode, sourceFile, sourceCode, state) {
  31696. // static nodes have no bindings
  31697. if (isStaticNode(sourceNode)) return [nodeToString(sourceNode), []]
  31698. return createDynamicNode(sourceNode, sourceFile, sourceCode)
  31699. }
  31700. /**
  31701. * Create the tag binding
  31702. * @param { RiotParser.Node.Tag } sourceNode - tag containing the each attribute
  31703. * @param { string } sourceFile - source file path
  31704. * @param { string } sourceCode - original source
  31705. * @param { string } selector - binding selector
  31706. * @returns { Array } array with only the tag binding AST
  31707. */
  31708. function createNestedBindings(sourceNode, sourceFile, sourceCode, selector) {
  31709. const mightBeARiotComponent = isCustomNode(sourceNode);
  31710. const node = cloneNodeWithoutSelectorAttribute(sourceNode, selector);
  31711. return mightBeARiotComponent ? [null, [
  31712. createTagBinding(
  31713. node,
  31714. null,
  31715. sourceFile,
  31716. sourceCode
  31717. )]
  31718. ] : build(createRootNode(node), sourceFile, sourceCode)
  31719. }
  31720. /**
  31721. * Build the template and the bindings
  31722. * @param {RiotParser.Node} sourceNode - any kind of node parsed via riot parser
  31723. * @param {string} sourceFile - source file path
  31724. * @param {string} sourceCode - original source
  31725. * @param {BuildingState} state - state representing the current building tree state during the recursion
  31726. * @returns {Array} array containing the html output and the dom bindings
  31727. */
  31728. function build(
  31729. sourceNode,
  31730. sourceFile,
  31731. sourceCode,
  31732. state
  31733. ) {
  31734. if (!sourceNode) panic('Something went wrong with your tag DOM parsing, your tag template can\'t be created');
  31735. const [nodeHTML, nodeBindings] = parseNode(sourceNode, sourceFile, sourceCode);
  31736. const childrenNodes = getChildrenNodes(sourceNode);
  31737. const currentState = { ...cloneDeep(BuildingState), ...state };
  31738. // mutate the original arrays
  31739. currentState.html.push(...nodeHTML);
  31740. currentState.bindings.push(...nodeBindings);
  31741. // do recursion if
  31742. // this tag has children and it has no special directives bound to it
  31743. if (childrenNodes.length && !hasItsOwnTemplate(sourceNode)) {
  31744. childrenNodes.forEach(node => build(node, sourceFile, sourceCode, { parent: sourceNode, ...currentState }));
  31745. }
  31746. // close the tag if it's not a void one
  31747. if (isTagNode(sourceNode) && !isVoidNode(sourceNode)) {
  31748. currentState.html.push(closeTag(sourceNode));
  31749. }
  31750. return [
  31751. currentState.html.join(''),
  31752. currentState.bindings
  31753. ]
  31754. }
  31755. const templateFunctionArguments = [
  31756. TEMPLATE_FN,
  31757. EXPRESSION_TYPES,
  31758. BINDING_TYPES,
  31759. GET_COMPONENT_FN
  31760. ].map(builders.identifier);
  31761. /**
  31762. * Create the content of the template function
  31763. * @param { RiotParser.Node } sourceNode - node generated by the riot compiler
  31764. * @param { string } sourceFile - source file path
  31765. * @param { string } sourceCode - original source
  31766. * @returns {AST.BlockStatement} the content of the template function
  31767. */
  31768. function createTemplateFunctionContent(sourceNode, sourceFile, sourceCode) {
  31769. return builders.blockStatement([
  31770. builders.returnStatement(
  31771. callTemplateFunction(
  31772. ...build(
  31773. createRootNode(sourceNode),
  31774. sourceFile,
  31775. sourceCode
  31776. )
  31777. )
  31778. )
  31779. ])
  31780. }
  31781. /**
  31782. * Extend the AST adding the new template property containing our template call to render the component
  31783. * @param { Object } ast - current output ast
  31784. * @param { string } sourceFile - source file path
  31785. * @param { string } sourceCode - original source
  31786. * @param { RiotParser.Node } sourceNode - node generated by the riot compiler
  31787. * @returns { Object } the output ast having the "template" key
  31788. */
  31789. function extendTemplateProperty(ast, sourceFile, sourceCode, sourceNode) {
  31790. types$1.visit(ast, {
  31791. visitProperty(path) {
  31792. if (path.value.key.value === TAG_TEMPLATE_PROPERTY) {
  31793. path.value.value = builders.functionExpression(
  31794. null,
  31795. templateFunctionArguments,
  31796. createTemplateFunctionContent(sourceNode, sourceFile, sourceCode)
  31797. );
  31798. return false
  31799. }
  31800. this.traverse(path);
  31801. }
  31802. });
  31803. return ast
  31804. }
  31805. /**
  31806. * Generate the component template logic
  31807. * @param { RiotParser.Node } sourceNode - node generated by the riot compiler
  31808. * @param { string } source - original component source code
  31809. * @param { Object } meta - compilation meta information
  31810. * @param { AST } ast - current AST output
  31811. * @returns { AST } the AST generated
  31812. */
  31813. function template(sourceNode, source, meta, ast) {
  31814. const { options } = meta;
  31815. return extendTemplateProperty(ast, options.file, source, sourceNode)
  31816. }
  31817. const DEFAULT_OPTIONS = {
  31818. template: 'default',
  31819. file: '[unknown-source-file]',
  31820. scopedCss: true
  31821. };
  31822. /**
  31823. * Create the initial AST
  31824. * @param {string} tagName - the name of the component we have compiled
  31825. * @returns { AST } the initial AST
  31826. *
  31827. * @example
  31828. * // the output represents the following string in AST
  31829. */
  31830. function createInitialInput({tagName}) {
  31831. /*
  31832. generates
  31833. export default {
  31834. ${TAG_CSS_PROPERTY}: null,
  31835. ${TAG_LOGIC_PROPERTY}: null,
  31836. ${TAG_TEMPLATE_PROPERTY}: null
  31837. }
  31838. */
  31839. return builders.program([
  31840. builders.exportDefaultDeclaration(
  31841. builders.objectExpression([
  31842. simplePropertyNode(TAG_CSS_PROPERTY, nullNode()),
  31843. simplePropertyNode(TAG_LOGIC_PROPERTY, nullNode()),
  31844. simplePropertyNode(TAG_TEMPLATE_PROPERTY, nullNode()),
  31845. simplePropertyNode(TAG_NAME_PROPERTY, builders.literal(tagName))
  31846. ])
  31847. )]
  31848. )
  31849. }
  31850. /**
  31851. * Make sure the input sourcemap is valid otherwise we ignore it
  31852. * @param {SourceMapGenerator} map - preprocessor source map
  31853. * @returns {Object} sourcemap as json or nothing
  31854. */
  31855. function normaliseInputSourceMap(map) {
  31856. const inputSourceMap = sourcemapAsJSON(map);
  31857. return isEmptySourcemap(inputSourceMap) ? null : inputSourceMap
  31858. }
  31859. /**
  31860. * Override the sourcemap content making sure it will always contain the tag source code
  31861. * @param {Object} map - sourcemap as json
  31862. * @param {string} source - component source code
  31863. * @returns {Object} original source map with the "sourcesContent" property overriden
  31864. */
  31865. function overrideSourcemapContent(map, source) {
  31866. return {
  31867. ...map,
  31868. sourcesContent: [source]
  31869. }
  31870. }
  31871. /**
  31872. * Create the compilation meta object
  31873. * @param { string } source - source code of the tag we will need to compile
  31874. * @param { string } options - compiling options
  31875. * @returns {Object} meta object
  31876. */
  31877. function createMeta(source, options) {
  31878. return {
  31879. tagName: null,
  31880. fragments: null,
  31881. options: {
  31882. ...DEFAULT_OPTIONS,
  31883. ...options
  31884. },
  31885. source
  31886. }
  31887. }
  31888. /**
  31889. * Generate the output code source together with the sourcemap
  31890. * @param { string } source - source code of the tag we will need to compile
  31891. * @param { Object } opts - compiling options
  31892. * @returns { Output } object containing output code and source map
  31893. */
  31894. function compile(source, opts = {}) {
  31895. const meta = createMeta(source, opts);
  31896. const {options} = meta;
  31897. const { code, map } = execute$1('template', options.template, meta, source);
  31898. const { template: template$1, css: css$1, javascript: javascript$1 } = parser$1(options).parse(code).output;
  31899. // extend the meta object with the result of the parsing
  31900. Object.assign(meta, {
  31901. tagName: template$1.name,
  31902. fragments: { template: template$1, css: css$1, javascript: javascript$1 }
  31903. });
  31904. return compose(
  31905. result => ({ ...result, meta }),
  31906. result => execute(result, meta),
  31907. result => ({
  31908. ...result,
  31909. map: overrideSourcemapContent(result.map, source)
  31910. }),
  31911. ast => meta.ast = ast && generateJavascript(ast, {
  31912. sourceMapName: `${options.file}.map`,
  31913. inputSourceMap: normaliseInputSourceMap(map)
  31914. }),
  31915. hookGenerator(template, template$1, code, meta),
  31916. hookGenerator(javascript, javascript$1, code, meta),
  31917. hookGenerator(css, css$1, code, meta)
  31918. )(createInitialInput(meta))
  31919. }
  31920. /**
  31921. * Prepare the riot parser node transformers
  31922. * @param { Function } transformer - transformer function
  31923. * @param { Object } sourceNode - riot parser node
  31924. * @param { string } source - component source code
  31925. * @param { Object } meta - compilation meta information
  31926. * @returns { Promise<Output> } object containing output code and source map
  31927. */
  31928. function hookGenerator(transformer, sourceNode, source, meta) {
  31929. if (
  31930. // filter missing nodes
  31931. !sourceNode ||
  31932. // filter nodes without children
  31933. (sourceNode.nodes && !sourceNode.nodes.length) ||
  31934. // filter empty javascript and css nodes
  31935. (!sourceNode.nodes && !sourceNode.text)) {
  31936. return result => result
  31937. }
  31938. return curry(transformer)(sourceNode, source, meta)
  31939. }
  31940. // This function can be used to register new preprocessors
  31941. // a preprocessor can target either only the css or javascript nodes
  31942. // or the complete tag source file ('template')
  31943. const registerPreprocessor = register$1;
  31944. // This function can allow you to register postprocessors that will parse the output code
  31945. // here we can run prettifiers, eslint fixes...
  31946. const registerPostprocessor = register;
  31947. exports.compile = compile;
  31948. exports.createInitialInput = createInitialInput;
  31949. exports.registerPostprocessor = registerPostprocessor;
  31950. exports.registerPreprocessor = registerPreprocessor;
  31951. Object.defineProperty(exports, '__esModule', { value: true });
  31952. })));