UNPKG

260 kBJavaScriptView Raw
1import { builtinModules, createRequire } from 'node:module';
2import path, { dirname } from 'node:path';
3import { pathToFileURL, fileURLToPath } from 'node:url';
4import vm from 'node:vm';
5import fs, { existsSync } from 'node:fs';
6import assert from 'node:assert';
7import process$1 from 'node:process';
8import v8 from 'node:v8';
9import { format, inspect } from 'node:util';
10import require$$0 from 'tty';
11import require$$1 from 'util';
12
13// This file was generated. Do not modify manually!
14var 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, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 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, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 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, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
15
16// This file was generated. Do not modify manually!
17var 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 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, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 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, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 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, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
18
19// This file was generated. Do not modify manually!
20var 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\u0898-\u089f\u08ca-\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\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\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\u0d81-\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\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\ua82c\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";
21
22// This file was generated. Do not modify manually!
23var 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\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-\u1711\u171f-\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-\u1b4c\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-\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-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\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-\uab69\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\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
24
25// These are a run-length and offset encoded representation of the
26
27// Reserved word lists for various dialects of the language
28
29var reservedWords = {
30 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",
31 5: "class enum extends super const export import",
32 6: "enum",
33 strict: "implements interface let package private protected public static yield",
34 strictBind: "eval arguments"
35};
36
37// And the keywords
38
39var 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";
40
41var keywords$1 = {
42 5: ecma5AndLessKeywords,
43 "5module": ecma5AndLessKeywords + " export import",
44 6: ecma5AndLessKeywords + " const class extends export import super"
45};
46
47var keywordRelationalOperator = /^in(stanceof)?$/;
48
49// ## Character categories
50
51var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
52var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
53
54// This has a complexity linear to the value of the code. The
55// assumption is that looking up astral identifier characters is
56// rare.
57function isInAstralSet(code, set) {
58 var pos = 0x10000;
59 for (var i = 0; i < set.length; i += 2) {
60 pos += set[i];
61 if (pos > code) { return false }
62 pos += set[i + 1];
63 if (pos >= code) { return true }
64 }
65}
66
67// Test whether a given character code starts an identifier.
68
69function isIdentifierStart(code, astral) {
70 if (code < 65) { return code === 36 }
71 if (code < 91) { return true }
72 if (code < 97) { return code === 95 }
73 if (code < 123) { return true }
74 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
75 if (astral === false) { return false }
76 return isInAstralSet(code, astralIdentifierStartCodes)
77}
78
79// Test whether a given character is part of an identifier.
80
81function isIdentifierChar(code, astral) {
82 if (code < 48) { return code === 36 }
83 if (code < 58) { return true }
84 if (code < 65) { return false }
85 if (code < 91) { return true }
86 if (code < 97) { return code === 95 }
87 if (code < 123) { return true }
88 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
89 if (astral === false) { return false }
90 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
91}
92
93// ## Token types
94
95// The assignment of fine-grained, information-carrying type objects
96// allows the tokenizer to store the information it has about a
97// token in a way that is very cheap for the parser to look up.
98
99// All token type variables start with an underscore, to make them
100// easy to recognize.
101
102// The `beforeExpr` property is used to disambiguate between regular
103// expressions and divisions. It is set on all token types that can
104// be followed by an expression (thus, a slash after them would be a
105// regular expression).
106//
107// The `startsExpr` property is used to check if the token ends a
108// `yield` expression. It is set on all token types that either can
109// directly start an expression (like a quotation mark) or can
110// continue an expression (like the body of a string).
111//
112// `isLoop` marks a keyword as starting a loop, which is important
113// to know when parsing a label, in order to allow or disallow
114// continue jumps to that label.
115
116var TokenType = function TokenType(label, conf) {
117 if ( conf === void 0 ) conf = {};
118
119 this.label = label;
120 this.keyword = conf.keyword;
121 this.beforeExpr = !!conf.beforeExpr;
122 this.startsExpr = !!conf.startsExpr;
123 this.isLoop = !!conf.isLoop;
124 this.isAssign = !!conf.isAssign;
125 this.prefix = !!conf.prefix;
126 this.postfix = !!conf.postfix;
127 this.binop = conf.binop || null;
128 this.updateContext = null;
129};
130
131function binop(name, prec) {
132 return new TokenType(name, {beforeExpr: true, binop: prec})
133}
134var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
135
136// Map keyword names to token types.
137
138var keywords = {};
139
140// Succinct definitions of keyword token types
141function kw(name, options) {
142 if ( options === void 0 ) options = {};
143
144 options.keyword = name;
145 return keywords[name] = new TokenType(name, options)
146}
147
148var types$1 = {
149 num: new TokenType("num", startsExpr),
150 regexp: new TokenType("regexp", startsExpr),
151 string: new TokenType("string", startsExpr),
152 name: new TokenType("name", startsExpr),
153 privateId: new TokenType("privateId", startsExpr),
154 eof: new TokenType("eof"),
155
156 // Punctuation token types.
157 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
158 bracketR: new TokenType("]"),
159 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
160 braceR: new TokenType("}"),
161 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
162 parenR: new TokenType(")"),
163 comma: new TokenType(",", beforeExpr),
164 semi: new TokenType(";", beforeExpr),
165 colon: new TokenType(":", beforeExpr),
166 dot: new TokenType("."),
167 question: new TokenType("?", beforeExpr),
168 questionDot: new TokenType("?."),
169 arrow: new TokenType("=>", beforeExpr),
170 template: new TokenType("template"),
171 invalidTemplate: new TokenType("invalidTemplate"),
172 ellipsis: new TokenType("...", beforeExpr),
173 backQuote: new TokenType("`", startsExpr),
174 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
175
176 // Operators. These carry several kinds of properties to help the
177 // parser use them properly (the presence of these properties is
178 // what categorizes them as operators).
179 //
180 // `binop`, when present, specifies that this operator is a binary
181 // operator, and will refer to its precedence.
182 //
183 // `prefix` and `postfix` mark the operator as a prefix or postfix
184 // unary operator.
185 //
186 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
187 // binary operators with a very low precedence, that should result
188 // in AssignmentExpression nodes.
189
190 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
191 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
192 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
193 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
194 logicalOR: binop("||", 1),
195 logicalAND: binop("&&", 2),
196 bitwiseOR: binop("|", 3),
197 bitwiseXOR: binop("^", 4),
198 bitwiseAND: binop("&", 5),
199 equality: binop("==/!=/===/!==", 6),
200 relational: binop("</>/<=/>=", 7),
201 bitShift: binop("<</>>/>>>", 8),
202 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
203 modulo: binop("%", 10),
204 star: binop("*", 10),
205 slash: binop("/", 10),
206 starstar: new TokenType("**", {beforeExpr: true}),
207 coalesce: binop("??", 1),
208
209 // Keyword token types.
210 _break: kw("break"),
211 _case: kw("case", beforeExpr),
212 _catch: kw("catch"),
213 _continue: kw("continue"),
214 _debugger: kw("debugger"),
215 _default: kw("default", beforeExpr),
216 _do: kw("do", {isLoop: true, beforeExpr: true}),
217 _else: kw("else", beforeExpr),
218 _finally: kw("finally"),
219 _for: kw("for", {isLoop: true}),
220 _function: kw("function", startsExpr),
221 _if: kw("if"),
222 _return: kw("return", beforeExpr),
223 _switch: kw("switch"),
224 _throw: kw("throw", beforeExpr),
225 _try: kw("try"),
226 _var: kw("var"),
227 _const: kw("const"),
228 _while: kw("while", {isLoop: true}),
229 _with: kw("with"),
230 _new: kw("new", {beforeExpr: true, startsExpr: true}),
231 _this: kw("this", startsExpr),
232 _super: kw("super", startsExpr),
233 _class: kw("class", startsExpr),
234 _extends: kw("extends", beforeExpr),
235 _export: kw("export"),
236 _import: kw("import", startsExpr),
237 _null: kw("null", startsExpr),
238 _true: kw("true", startsExpr),
239 _false: kw("false", startsExpr),
240 _in: kw("in", {beforeExpr: true, binop: 7}),
241 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
242 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
243 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
244 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
245};
246
247// Matches a whole line break (where CRLF is considered a single
248// line break). Used to count lines.
249
250var lineBreak = /\r\n?|\n|\u2028|\u2029/;
251var lineBreakG = new RegExp(lineBreak.source, "g");
252
253function isNewLine(code) {
254 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
255}
256
257function nextLineBreak(code, from, end) {
258 if ( end === void 0 ) end = code.length;
259
260 for (var i = from; i < end; i++) {
261 var next = code.charCodeAt(i);
262 if (isNewLine(next))
263 { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
264 }
265 return -1
266}
267
268var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
269
270var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
271
272var ref = Object.prototype;
273var hasOwnProperty = ref.hasOwnProperty;
274var toString = ref.toString;
275
276var hasOwn = Object.hasOwn || (function (obj, propName) { return (
277 hasOwnProperty.call(obj, propName)
278); });
279
280var isArray = Array.isArray || (function (obj) { return (
281 toString.call(obj) === "[object Array]"
282); });
283
284function wordsRegexp(words) {
285 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
286}
287
288function codePointToString(code) {
289 // UTF-16 Decoding
290 if (code <= 0xFFFF) { return String.fromCharCode(code) }
291 code -= 0x10000;
292 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
293}
294
295var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
296
297// These are used when `options.locations` is on, for the
298// `startLoc` and `endLoc` properties.
299
300var Position = function Position(line, col) {
301 this.line = line;
302 this.column = col;
303};
304
305Position.prototype.offset = function offset (n) {
306 return new Position(this.line, this.column + n)
307};
308
309var SourceLocation = function SourceLocation(p, start, end) {
310 this.start = start;
311 this.end = end;
312 if (p.sourceFile !== null) { this.source = p.sourceFile; }
313};
314
315// The `getLineInfo` function is mostly useful when the
316// `locations` option is off (for performance reasons) and you
317// want to find the line/column position for a given character
318// offset. `input` should be the code string that the offset refers
319// into.
320
321function getLineInfo(input, offset) {
322 for (var line = 1, cur = 0;;) {
323 var nextBreak = nextLineBreak(input, cur, offset);
324 if (nextBreak < 0) { return new Position(line, offset - cur) }
325 ++line;
326 cur = nextBreak;
327 }
328}
329
330// A second argument must be given to configure the parser process.
331// These options are recognized (only `ecmaVersion` is required):
332
333var defaultOptions = {
334 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
335 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
336 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
337 // (the latest version the library supports). This influences
338 // support for strict mode, the set of reserved words, and support
339 // for new syntax features.
340 ecmaVersion: null,
341 // `sourceType` indicates the mode the code should be parsed in.
342 // Can be either `"script"` or `"module"`. This influences global
343 // strict mode and parsing of `import` and `export` declarations.
344 sourceType: "script",
345 // `onInsertedSemicolon` can be a callback that will be called
346 // when a semicolon is automatically inserted. It will be passed
347 // the position of the comma as an offset, and if `locations` is
348 // enabled, it is given the location as a `{line, column}` object
349 // as second argument.
350 onInsertedSemicolon: null,
351 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
352 // trailing commas.
353 onTrailingComma: null,
354 // By default, reserved words are only enforced if ecmaVersion >= 5.
355 // Set `allowReserved` to a boolean value to explicitly turn this on
356 // an off. When this option has the value "never", reserved words
357 // and keywords can also not be used as property names.
358 allowReserved: null,
359 // When enabled, a return at the top level is not considered an
360 // error.
361 allowReturnOutsideFunction: false,
362 // When enabled, import/export statements are not constrained to
363 // appearing at the top of the program, and an import.meta expression
364 // in a script isn't considered an error.
365 allowImportExportEverywhere: false,
366 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
367 // When enabled, await identifiers are allowed to appear at the top-level scope,
368 // but they are still not allowed in non-async functions.
369 allowAwaitOutsideFunction: null,
370 // When enabled, super identifiers are not constrained to
371 // appearing in methods and do not raise an error when they appear elsewhere.
372 allowSuperOutsideMethod: null,
373 // When enabled, hashbang directive in the beginning of file is
374 // allowed and treated as a line comment. Enabled by default when
375 // `ecmaVersion` >= 2023.
376 allowHashBang: false,
377 // When `locations` is on, `loc` properties holding objects with
378 // `start` and `end` properties in `{line, column}` form (with
379 // line being 1-based and column 0-based) will be attached to the
380 // nodes.
381 locations: false,
382 // A function can be passed as `onToken` option, which will
383 // cause Acorn to call that function with object in the same
384 // format as tokens returned from `tokenizer().getToken()`. Note
385 // that you are not allowed to call the parser from the
386 // callback—that will corrupt its internal state.
387 onToken: null,
388 // A function can be passed as `onComment` option, which will
389 // cause Acorn to call that function with `(block, text, start,
390 // end)` parameters whenever a comment is skipped. `block` is a
391 // boolean indicating whether this is a block (`/* */`) comment,
392 // `text` is the content of the comment, and `start` and `end` are
393 // character offsets that denote the start and end of the comment.
394 // When the `locations` option is on, two more parameters are
395 // passed, the full `{line, column}` locations of the start and
396 // end of the comments. Note that you are not allowed to call the
397 // parser from the callback—that will corrupt its internal state.
398 onComment: null,
399 // Nodes have their start and end characters offsets recorded in
400 // `start` and `end` properties (directly on the node, rather than
401 // the `loc` object, which holds line/column data. To also add a
402 // [semi-standardized][range] `range` property holding a `[start,
403 // end]` array with the same numbers, set the `ranges` option to
404 // `true`.
405 //
406 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
407 ranges: false,
408 // It is possible to parse multiple files into a single AST by
409 // passing the tree produced by parsing the first file as
410 // `program` option in subsequent parses. This will add the
411 // toplevel forms of the parsed file to the `Program` (top) node
412 // of an existing parse tree.
413 program: null,
414 // When `locations` is on, you can pass this to record the source
415 // file in every node's `loc` object.
416 sourceFile: null,
417 // This value, if given, is stored in every node, whether
418 // `locations` is on or off.
419 directSourceFile: null,
420 // When enabled, parenthesized expressions are represented by
421 // (non-standard) ParenthesizedExpression nodes
422 preserveParens: false
423};
424
425// Interpret and default an options object
426
427var warnedAboutEcmaVersion = false;
428
429function getOptions(opts) {
430 var options = {};
431
432 for (var opt in defaultOptions)
433 { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
434
435 if (options.ecmaVersion === "latest") {
436 options.ecmaVersion = 1e8;
437 } else if (options.ecmaVersion == null) {
438 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
439 warnedAboutEcmaVersion = true;
440 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
441 }
442 options.ecmaVersion = 11;
443 } else if (options.ecmaVersion >= 2015) {
444 options.ecmaVersion -= 2009;
445 }
446
447 if (options.allowReserved == null)
448 { options.allowReserved = options.ecmaVersion < 5; }
449
450 if (opts.allowHashBang == null)
451 { options.allowHashBang = options.ecmaVersion >= 14; }
452
453 if (isArray(options.onToken)) {
454 var tokens = options.onToken;
455 options.onToken = function (token) { return tokens.push(token); };
456 }
457 if (isArray(options.onComment))
458 { options.onComment = pushComment(options, options.onComment); }
459
460 return options
461}
462
463function pushComment(options, array) {
464 return function(block, text, start, end, startLoc, endLoc) {
465 var comment = {
466 type: block ? "Block" : "Line",
467 value: text,
468 start: start,
469 end: end
470 };
471 if (options.locations)
472 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
473 if (options.ranges)
474 { comment.range = [start, end]; }
475 array.push(comment);
476 }
477}
478
479// Each scope gets a bitset that may contain these flags
480var
481 SCOPE_TOP = 1,
482 SCOPE_FUNCTION = 2,
483 SCOPE_ASYNC = 4,
484 SCOPE_GENERATOR = 8,
485 SCOPE_ARROW = 16,
486 SCOPE_SIMPLE_CATCH = 32,
487 SCOPE_SUPER = 64,
488 SCOPE_DIRECT_SUPER = 128,
489 SCOPE_CLASS_STATIC_BLOCK = 256,
490 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
491
492function functionFlags(async, generator) {
493 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
494}
495
496// Used in checkLVal* and declareName to determine the type of a binding
497var
498 BIND_NONE = 0, // Not a binding
499 BIND_VAR = 1, // Var-style binding
500 BIND_LEXICAL = 2, // Let- or const-style binding
501 BIND_FUNCTION = 3, // Function declaration
502 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
503 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
504
505var Parser = function Parser(options, input, startPos) {
506 this.options = options = getOptions(options);
507 this.sourceFile = options.sourceFile;
508 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
509 var reserved = "";
510 if (options.allowReserved !== true) {
511 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
512 if (options.sourceType === "module") { reserved += " await"; }
513 }
514 this.reservedWords = wordsRegexp(reserved);
515 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
516 this.reservedWordsStrict = wordsRegexp(reservedStrict);
517 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
518 this.input = String(input);
519
520 // Used to signal to callers of `readWord1` whether the word
521 // contained any escape sequences. This is needed because words with
522 // escape sequences must not be interpreted as keywords.
523 this.containsEsc = false;
524
525 // Set up token state
526
527 // The current position of the tokenizer in the input.
528 if (startPos) {
529 this.pos = startPos;
530 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
531 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
532 } else {
533 this.pos = this.lineStart = 0;
534 this.curLine = 1;
535 }
536
537 // Properties of the current token:
538 // Its type
539 this.type = types$1.eof;
540 // For tokens that include more information than their type, the value
541 this.value = null;
542 // Its start and end offset
543 this.start = this.end = this.pos;
544 // And, if locations are used, the {line, column} object
545 // corresponding to those offsets
546 this.startLoc = this.endLoc = this.curPosition();
547
548 // Position information for the previous token
549 this.lastTokEndLoc = this.lastTokStartLoc = null;
550 this.lastTokStart = this.lastTokEnd = this.pos;
551
552 // The context stack is used to superficially track syntactic
553 // context to predict whether a regular expression is allowed in a
554 // given position.
555 this.context = this.initialContext();
556 this.exprAllowed = true;
557
558 // Figure out if it's a module code.
559 this.inModule = options.sourceType === "module";
560 this.strict = this.inModule || this.strictDirective(this.pos);
561
562 // Used to signify the start of a potential arrow function
563 this.potentialArrowAt = -1;
564 this.potentialArrowInForAwait = false;
565
566 // Positions to delayed-check that yield/await does not exist in default parameters.
567 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
568 // Labels in scope.
569 this.labels = [];
570 // Thus-far undefined exports.
571 this.undefinedExports = Object.create(null);
572
573 // If enabled, skip leading hashbang line.
574 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
575 { this.skipLineComment(2); }
576
577 // Scope tracking for duplicate variable names (see scope.js)
578 this.scopeStack = [];
579 this.enterScope(SCOPE_TOP);
580
581 // For RegExp validation
582 this.regexpState = null;
583
584 // The stack of private names.
585 // Each element has two properties: 'declared' and 'used'.
586 // When it exited from the outermost class definition, all used private names must be declared.
587 this.privateNameStack = [];
588};
589
590var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
591
592Parser.prototype.parse = function parse () {
593 var node = this.options.program || this.startNode();
594 this.nextToken();
595 return this.parseTopLevel(node)
596};
597
598prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
599
600prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
601
602prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
603
604prototypeAccessors.canAwait.get = function () {
605 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
606 var scope = this.scopeStack[i];
607 if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
608 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
609 }
610 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
611};
612
613prototypeAccessors.allowSuper.get = function () {
614 var ref = this.currentThisScope();
615 var flags = ref.flags;
616 var inClassFieldInit = ref.inClassFieldInit;
617 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
618};
619
620prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
621
622prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
623
624prototypeAccessors.allowNewDotTarget.get = function () {
625 var ref = this.currentThisScope();
626 var flags = ref.flags;
627 var inClassFieldInit = ref.inClassFieldInit;
628 return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
629};
630
631prototypeAccessors.inClassStaticBlock.get = function () {
632 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
633};
634
635Parser.extend = function extend () {
636 var plugins = [], len = arguments.length;
637 while ( len-- ) plugins[ len ] = arguments[ len ];
638
639 var cls = this;
640 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
641 return cls
642};
643
644Parser.parse = function parse (input, options) {
645 return new this(options, input).parse()
646};
647
648Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
649 var parser = new this(options, input, pos);
650 parser.nextToken();
651 return parser.parseExpression()
652};
653
654Parser.tokenizer = function tokenizer (input, options) {
655 return new this(options, input)
656};
657
658Object.defineProperties( Parser.prototype, prototypeAccessors );
659
660var pp$9 = Parser.prototype;
661
662// ## Parser utilities
663
664var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
665pp$9.strictDirective = function(start) {
666 if (this.options.ecmaVersion < 5) { return false }
667 for (;;) {
668 // Try to find string literal.
669 skipWhiteSpace.lastIndex = start;
670 start += skipWhiteSpace.exec(this.input)[0].length;
671 var match = literal.exec(this.input.slice(start));
672 if (!match) { return false }
673 if ((match[1] || match[2]) === "use strict") {
674 skipWhiteSpace.lastIndex = start + match[0].length;
675 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
676 var next = this.input.charAt(end);
677 return next === ";" || next === "}" ||
678 (lineBreak.test(spaceAfter[0]) &&
679 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
680 }
681 start += match[0].length;
682
683 // Skip semicolon, if any.
684 skipWhiteSpace.lastIndex = start;
685 start += skipWhiteSpace.exec(this.input)[0].length;
686 if (this.input[start] === ";")
687 { start++; }
688 }
689};
690
691// Predicate that tests whether the next token is of the given
692// type, and if yes, consumes it as a side effect.
693
694pp$9.eat = function(type) {
695 if (this.type === type) {
696 this.next();
697 return true
698 } else {
699 return false
700 }
701};
702
703// Tests whether parsed token is a contextual keyword.
704
705pp$9.isContextual = function(name) {
706 return this.type === types$1.name && this.value === name && !this.containsEsc
707};
708
709// Consumes contextual keyword if possible.
710
711pp$9.eatContextual = function(name) {
712 if (!this.isContextual(name)) { return false }
713 this.next();
714 return true
715};
716
717// Asserts that following token is given contextual keyword.
718
719pp$9.expectContextual = function(name) {
720 if (!this.eatContextual(name)) { this.unexpected(); }
721};
722
723// Test whether a semicolon can be inserted at the current position.
724
725pp$9.canInsertSemicolon = function() {
726 return this.type === types$1.eof ||
727 this.type === types$1.braceR ||
728 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
729};
730
731pp$9.insertSemicolon = function() {
732 if (this.canInsertSemicolon()) {
733 if (this.options.onInsertedSemicolon)
734 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
735 return true
736 }
737};
738
739// Consume a semicolon, or, failing that, see if we are allowed to
740// pretend that there is a semicolon at this position.
741
742pp$9.semicolon = function() {
743 if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
744};
745
746pp$9.afterTrailingComma = function(tokType, notNext) {
747 if (this.type === tokType) {
748 if (this.options.onTrailingComma)
749 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
750 if (!notNext)
751 { this.next(); }
752 return true
753 }
754};
755
756// Expect a token of a given type. If found, consume it, otherwise,
757// raise an unexpected token error.
758
759pp$9.expect = function(type) {
760 this.eat(type) || this.unexpected();
761};
762
763// Raise an unexpected token error.
764
765pp$9.unexpected = function(pos) {
766 this.raise(pos != null ? pos : this.start, "Unexpected token");
767};
768
769var DestructuringErrors = function DestructuringErrors() {
770 this.shorthandAssign =
771 this.trailingComma =
772 this.parenthesizedAssign =
773 this.parenthesizedBind =
774 this.doubleProto =
775 -1;
776};
777
778pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
779 if (!refDestructuringErrors) { return }
780 if (refDestructuringErrors.trailingComma > -1)
781 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
782 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
783 if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
784};
785
786pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
787 if (!refDestructuringErrors) { return false }
788 var shorthandAssign = refDestructuringErrors.shorthandAssign;
789 var doubleProto = refDestructuringErrors.doubleProto;
790 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
791 if (shorthandAssign >= 0)
792 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
793 if (doubleProto >= 0)
794 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
795};
796
797pp$9.checkYieldAwaitInDefaultParams = function() {
798 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
799 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
800 if (this.awaitPos)
801 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
802};
803
804pp$9.isSimpleAssignTarget = function(expr) {
805 if (expr.type === "ParenthesizedExpression")
806 { return this.isSimpleAssignTarget(expr.expression) }
807 return expr.type === "Identifier" || expr.type === "MemberExpression"
808};
809
810var pp$8 = Parser.prototype;
811
812// ### Statement parsing
813
814// Parse a program. Initializes the parser, reads any number of
815// statements, and wraps them in a Program node. Optionally takes a
816// `program` argument. If present, the statements will be appended
817// to its body instead of creating a new node.
818
819pp$8.parseTopLevel = function(node) {
820 var exports = Object.create(null);
821 if (!node.body) { node.body = []; }
822 while (this.type !== types$1.eof) {
823 var stmt = this.parseStatement(null, true, exports);
824 node.body.push(stmt);
825 }
826 if (this.inModule)
827 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
828 {
829 var name = list[i];
830
831 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
832 } }
833 this.adaptDirectivePrologue(node.body);
834 this.next();
835 node.sourceType = this.options.sourceType;
836 return this.finishNode(node, "Program")
837};
838
839var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
840
841pp$8.isLet = function(context) {
842 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
843 skipWhiteSpace.lastIndex = this.pos;
844 var skip = skipWhiteSpace.exec(this.input);
845 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
846 // For ambiguous cases, determine if a LexicalDeclaration (or only a
847 // Statement) is allowed here. If context is not empty then only a Statement
848 // is allowed. However, `let [` is an explicit negative lookahead for
849 // ExpressionStatement, so special-case it first.
850 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
851 if (context) { return false }
852
853 if (nextCh === 123) { return true } // '{'
854 if (isIdentifierStart(nextCh, true)) {
855 var pos = next + 1;
856 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
857 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
858 var ident = this.input.slice(next, pos);
859 if (!keywordRelationalOperator.test(ident)) { return true }
860 }
861 return false
862};
863
864// check 'async [no LineTerminator here] function'
865// - 'async /*foo*/ function' is OK.
866// - 'async /*\n*/ function' is invalid.
867pp$8.isAsyncFunction = function() {
868 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
869 { return false }
870
871 skipWhiteSpace.lastIndex = this.pos;
872 var skip = skipWhiteSpace.exec(this.input);
873 var next = this.pos + skip[0].length, after;
874 return !lineBreak.test(this.input.slice(this.pos, next)) &&
875 this.input.slice(next, next + 8) === "function" &&
876 (next + 8 === this.input.length ||
877 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
878};
879
880// Parse a single statement.
881//
882// If expecting a statement and finding a slash operator, parse a
883// regular expression literal. This is to handle cases like
884// `if (foo) /blah/.exec(foo)`, where looking at the previous token
885// does not help.
886
887pp$8.parseStatement = function(context, topLevel, exports) {
888 var starttype = this.type, node = this.startNode(), kind;
889
890 if (this.isLet(context)) {
891 starttype = types$1._var;
892 kind = "let";
893 }
894
895 // Most types of statements are recognized by the keyword they
896 // start with. Many are trivial to parse, some require a bit of
897 // complexity.
898
899 switch (starttype) {
900 case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
901 case types$1._debugger: return this.parseDebuggerStatement(node)
902 case types$1._do: return this.parseDoStatement(node)
903 case types$1._for: return this.parseForStatement(node)
904 case types$1._function:
905 // Function as sole body of either an if statement or a labeled statement
906 // works, but not when it is part of a labeled statement that is the sole
907 // body of an if statement.
908 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
909 return this.parseFunctionStatement(node, false, !context)
910 case types$1._class:
911 if (context) { this.unexpected(); }
912 return this.parseClass(node, true)
913 case types$1._if: return this.parseIfStatement(node)
914 case types$1._return: return this.parseReturnStatement(node)
915 case types$1._switch: return this.parseSwitchStatement(node)
916 case types$1._throw: return this.parseThrowStatement(node)
917 case types$1._try: return this.parseTryStatement(node)
918 case types$1._const: case types$1._var:
919 kind = kind || this.value;
920 if (context && kind !== "var") { this.unexpected(); }
921 return this.parseVarStatement(node, kind)
922 case types$1._while: return this.parseWhileStatement(node)
923 case types$1._with: return this.parseWithStatement(node)
924 case types$1.braceL: return this.parseBlock(true, node)
925 case types$1.semi: return this.parseEmptyStatement(node)
926 case types$1._export:
927 case types$1._import:
928 if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
929 skipWhiteSpace.lastIndex = this.pos;
930 var skip = skipWhiteSpace.exec(this.input);
931 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
932 if (nextCh === 40 || nextCh === 46) // '(' or '.'
933 { return this.parseExpressionStatement(node, this.parseExpression()) }
934 }
935
936 if (!this.options.allowImportExportEverywhere) {
937 if (!topLevel)
938 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
939 if (!this.inModule)
940 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
941 }
942 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
943
944 // If the statement does not start with a statement keyword or a
945 // brace, it's an ExpressionStatement or LabeledStatement. We
946 // simply start parsing an expression, and afterwards, if the
947 // next token is a colon and the expression was a simple
948 // Identifier node, we switch to interpreting it as a label.
949 default:
950 if (this.isAsyncFunction()) {
951 if (context) { this.unexpected(); }
952 this.next();
953 return this.parseFunctionStatement(node, true, !context)
954 }
955
956 var maybeName = this.value, expr = this.parseExpression();
957 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
958 { return this.parseLabeledStatement(node, maybeName, expr, context) }
959 else { return this.parseExpressionStatement(node, expr) }
960 }
961};
962
963pp$8.parseBreakContinueStatement = function(node, keyword) {
964 var isBreak = keyword === "break";
965 this.next();
966 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
967 else if (this.type !== types$1.name) { this.unexpected(); }
968 else {
969 node.label = this.parseIdent();
970 this.semicolon();
971 }
972
973 // Verify that there is an actual destination to break or
974 // continue to.
975 var i = 0;
976 for (; i < this.labels.length; ++i) {
977 var lab = this.labels[i];
978 if (node.label == null || lab.name === node.label.name) {
979 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
980 if (node.label && isBreak) { break }
981 }
982 }
983 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
984 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
985};
986
987pp$8.parseDebuggerStatement = function(node) {
988 this.next();
989 this.semicolon();
990 return this.finishNode(node, "DebuggerStatement")
991};
992
993pp$8.parseDoStatement = function(node) {
994 this.next();
995 this.labels.push(loopLabel);
996 node.body = this.parseStatement("do");
997 this.labels.pop();
998 this.expect(types$1._while);
999 node.test = this.parseParenExpression();
1000 if (this.options.ecmaVersion >= 6)
1001 { this.eat(types$1.semi); }
1002 else
1003 { this.semicolon(); }
1004 return this.finishNode(node, "DoWhileStatement")
1005};
1006
1007// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
1008// loop is non-trivial. Basically, we have to parse the init `var`
1009// statement or expression, disallowing the `in` operator (see
1010// the second parameter to `parseExpression`), and then check
1011// whether the next token is `in` or `of`. When there is no init
1012// part (semicolon immediately after the opening parenthesis), it
1013// is a regular `for` loop.
1014
1015pp$8.parseForStatement = function(node) {
1016 this.next();
1017 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
1018 this.labels.push(loopLabel);
1019 this.enterScope(0);
1020 this.expect(types$1.parenL);
1021 if (this.type === types$1.semi) {
1022 if (awaitAt > -1) { this.unexpected(awaitAt); }
1023 return this.parseFor(node, null)
1024 }
1025 var isLet = this.isLet();
1026 if (this.type === types$1._var || this.type === types$1._const || isLet) {
1027 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
1028 this.next();
1029 this.parseVar(init$1, true, kind);
1030 this.finishNode(init$1, "VariableDeclaration");
1031 if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
1032 if (this.options.ecmaVersion >= 9) {
1033 if (this.type === types$1._in) {
1034 if (awaitAt > -1) { this.unexpected(awaitAt); }
1035 } else { node.await = awaitAt > -1; }
1036 }
1037 return this.parseForIn(node, init$1)
1038 }
1039 if (awaitAt > -1) { this.unexpected(awaitAt); }
1040 return this.parseFor(node, init$1)
1041 }
1042 var startsWithLet = this.isContextual("let"), isForOf = false;
1043 var refDestructuringErrors = new DestructuringErrors;
1044 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
1045 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
1046 if (this.options.ecmaVersion >= 9) {
1047 if (this.type === types$1._in) {
1048 if (awaitAt > -1) { this.unexpected(awaitAt); }
1049 } else { node.await = awaitAt > -1; }
1050 }
1051 if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
1052 this.toAssignable(init, false, refDestructuringErrors);
1053 this.checkLValPattern(init);
1054 return this.parseForIn(node, init)
1055 } else {
1056 this.checkExpressionErrors(refDestructuringErrors, true);
1057 }
1058 if (awaitAt > -1) { this.unexpected(awaitAt); }
1059 return this.parseFor(node, init)
1060};
1061
1062pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
1063 this.next();
1064 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
1065};
1066
1067pp$8.parseIfStatement = function(node) {
1068 this.next();
1069 node.test = this.parseParenExpression();
1070 // allow function declarations in branches, but only in non-strict mode
1071 node.consequent = this.parseStatement("if");
1072 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
1073 return this.finishNode(node, "IfStatement")
1074};
1075
1076pp$8.parseReturnStatement = function(node) {
1077 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
1078 { this.raise(this.start, "'return' outside of function"); }
1079 this.next();
1080
1081 // In `return` (and `break`/`continue`), the keywords with
1082 // optional arguments, we eagerly look for a semicolon or the
1083 // possibility to insert one.
1084
1085 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
1086 else { node.argument = this.parseExpression(); this.semicolon(); }
1087 return this.finishNode(node, "ReturnStatement")
1088};
1089
1090pp$8.parseSwitchStatement = function(node) {
1091 this.next();
1092 node.discriminant = this.parseParenExpression();
1093 node.cases = [];
1094 this.expect(types$1.braceL);
1095 this.labels.push(switchLabel);
1096 this.enterScope(0);
1097
1098 // Statements under must be grouped (by label) in SwitchCase
1099 // nodes. `cur` is used to keep the node that we are currently
1100 // adding statements to.
1101
1102 var cur;
1103 for (var sawDefault = false; this.type !== types$1.braceR;) {
1104 if (this.type === types$1._case || this.type === types$1._default) {
1105 var isCase = this.type === types$1._case;
1106 if (cur) { this.finishNode(cur, "SwitchCase"); }
1107 node.cases.push(cur = this.startNode());
1108 cur.consequent = [];
1109 this.next();
1110 if (isCase) {
1111 cur.test = this.parseExpression();
1112 } else {
1113 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
1114 sawDefault = true;
1115 cur.test = null;
1116 }
1117 this.expect(types$1.colon);
1118 } else {
1119 if (!cur) { this.unexpected(); }
1120 cur.consequent.push(this.parseStatement(null));
1121 }
1122 }
1123 this.exitScope();
1124 if (cur) { this.finishNode(cur, "SwitchCase"); }
1125 this.next(); // Closing brace
1126 this.labels.pop();
1127 return this.finishNode(node, "SwitchStatement")
1128};
1129
1130pp$8.parseThrowStatement = function(node) {
1131 this.next();
1132 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
1133 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
1134 node.argument = this.parseExpression();
1135 this.semicolon();
1136 return this.finishNode(node, "ThrowStatement")
1137};
1138
1139// Reused empty array added for node fields that are always empty.
1140
1141var empty$1 = [];
1142
1143pp$8.parseTryStatement = function(node) {
1144 this.next();
1145 node.block = this.parseBlock();
1146 node.handler = null;
1147 if (this.type === types$1._catch) {
1148 var clause = this.startNode();
1149 this.next();
1150 if (this.eat(types$1.parenL)) {
1151 clause.param = this.parseBindingAtom();
1152 var simple = clause.param.type === "Identifier";
1153 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
1154 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
1155 this.expect(types$1.parenR);
1156 } else {
1157 if (this.options.ecmaVersion < 10) { this.unexpected(); }
1158 clause.param = null;
1159 this.enterScope(0);
1160 }
1161 clause.body = this.parseBlock(false);
1162 this.exitScope();
1163 node.handler = this.finishNode(clause, "CatchClause");
1164 }
1165 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
1166 if (!node.handler && !node.finalizer)
1167 { this.raise(node.start, "Missing catch or finally clause"); }
1168 return this.finishNode(node, "TryStatement")
1169};
1170
1171pp$8.parseVarStatement = function(node, kind) {
1172 this.next();
1173 this.parseVar(node, false, kind);
1174 this.semicolon();
1175 return this.finishNode(node, "VariableDeclaration")
1176};
1177
1178pp$8.parseWhileStatement = function(node) {
1179 this.next();
1180 node.test = this.parseParenExpression();
1181 this.labels.push(loopLabel);
1182 node.body = this.parseStatement("while");
1183 this.labels.pop();
1184 return this.finishNode(node, "WhileStatement")
1185};
1186
1187pp$8.parseWithStatement = function(node) {
1188 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
1189 this.next();
1190 node.object = this.parseParenExpression();
1191 node.body = this.parseStatement("with");
1192 return this.finishNode(node, "WithStatement")
1193};
1194
1195pp$8.parseEmptyStatement = function(node) {
1196 this.next();
1197 return this.finishNode(node, "EmptyStatement")
1198};
1199
1200pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
1201 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
1202 {
1203 var label = list[i$1];
1204
1205 if (label.name === maybeName)
1206 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
1207 } }
1208 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
1209 for (var i = this.labels.length - 1; i >= 0; i--) {
1210 var label$1 = this.labels[i];
1211 if (label$1.statementStart === node.start) {
1212 // Update information about previous labels on this node
1213 label$1.statementStart = this.start;
1214 label$1.kind = kind;
1215 } else { break }
1216 }
1217 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
1218 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
1219 this.labels.pop();
1220 node.label = expr;
1221 return this.finishNode(node, "LabeledStatement")
1222};
1223
1224pp$8.parseExpressionStatement = function(node, expr) {
1225 node.expression = expr;
1226 this.semicolon();
1227 return this.finishNode(node, "ExpressionStatement")
1228};
1229
1230// Parse a semicolon-enclosed block of statements, handling `"use
1231// strict"` declarations when `allowStrict` is true (used for
1232// function bodies).
1233
1234pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
1235 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
1236 if ( node === void 0 ) node = this.startNode();
1237
1238 node.body = [];
1239 this.expect(types$1.braceL);
1240 if (createNewLexicalScope) { this.enterScope(0); }
1241 while (this.type !== types$1.braceR) {
1242 var stmt = this.parseStatement(null);
1243 node.body.push(stmt);
1244 }
1245 if (exitStrict) { this.strict = false; }
1246 this.next();
1247 if (createNewLexicalScope) { this.exitScope(); }
1248 return this.finishNode(node, "BlockStatement")
1249};
1250
1251// Parse a regular `for` loop. The disambiguation code in
1252// `parseStatement` will already have parsed the init statement or
1253// expression.
1254
1255pp$8.parseFor = function(node, init) {
1256 node.init = init;
1257 this.expect(types$1.semi);
1258 node.test = this.type === types$1.semi ? null : this.parseExpression();
1259 this.expect(types$1.semi);
1260 node.update = this.type === types$1.parenR ? null : this.parseExpression();
1261 this.expect(types$1.parenR);
1262 node.body = this.parseStatement("for");
1263 this.exitScope();
1264 this.labels.pop();
1265 return this.finishNode(node, "ForStatement")
1266};
1267
1268// Parse a `for`/`in` and `for`/`of` loop, which are almost
1269// same from parser's perspective.
1270
1271pp$8.parseForIn = function(node, init) {
1272 var isForIn = this.type === types$1._in;
1273 this.next();
1274
1275 if (
1276 init.type === "VariableDeclaration" &&
1277 init.declarations[0].init != null &&
1278 (
1279 !isForIn ||
1280 this.options.ecmaVersion < 8 ||
1281 this.strict ||
1282 init.kind !== "var" ||
1283 init.declarations[0].id.type !== "Identifier"
1284 )
1285 ) {
1286 this.raise(
1287 init.start,
1288 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
1289 );
1290 }
1291 node.left = init;
1292 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
1293 this.expect(types$1.parenR);
1294 node.body = this.parseStatement("for");
1295 this.exitScope();
1296 this.labels.pop();
1297 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
1298};
1299
1300// Parse a list of variable declarations.
1301
1302pp$8.parseVar = function(node, isFor, kind) {
1303 node.declarations = [];
1304 node.kind = kind;
1305 for (;;) {
1306 var decl = this.startNode();
1307 this.parseVarId(decl, kind);
1308 if (this.eat(types$1.eq)) {
1309 decl.init = this.parseMaybeAssign(isFor);
1310 } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
1311 this.unexpected();
1312 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
1313 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
1314 } else {
1315 decl.init = null;
1316 }
1317 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
1318 if (!this.eat(types$1.comma)) { break }
1319 }
1320 return node
1321};
1322
1323pp$8.parseVarId = function(decl, kind) {
1324 decl.id = this.parseBindingAtom();
1325 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
1326};
1327
1328var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
1329
1330// Parse a function declaration or literal (depending on the
1331// `statement & FUNC_STATEMENT`).
1332
1333// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
1334pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
1335 this.initFunction(node);
1336 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
1337 if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
1338 { this.unexpected(); }
1339 node.generator = this.eat(types$1.star);
1340 }
1341 if (this.options.ecmaVersion >= 8)
1342 { node.async = !!isAsync; }
1343
1344 if (statement & FUNC_STATEMENT) {
1345 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
1346 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
1347 // If it is a regular function declaration in sloppy mode, then it is
1348 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
1349 // mode depends on properties of the current scope (see
1350 // treatFunctionsAsVar).
1351 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
1352 }
1353
1354 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
1355 this.yieldPos = 0;
1356 this.awaitPos = 0;
1357 this.awaitIdentPos = 0;
1358 this.enterScope(functionFlags(node.async, node.generator));
1359
1360 if (!(statement & FUNC_STATEMENT))
1361 { node.id = this.type === types$1.name ? this.parseIdent() : null; }
1362
1363 this.parseFunctionParams(node);
1364 this.parseFunctionBody(node, allowExpressionBody, false, forInit);
1365
1366 this.yieldPos = oldYieldPos;
1367 this.awaitPos = oldAwaitPos;
1368 this.awaitIdentPos = oldAwaitIdentPos;
1369 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
1370};
1371
1372pp$8.parseFunctionParams = function(node) {
1373 this.expect(types$1.parenL);
1374 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
1375 this.checkYieldAwaitInDefaultParams();
1376};
1377
1378// Parse a class declaration or literal (depending on the
1379// `isStatement` parameter).
1380
1381pp$8.parseClass = function(node, isStatement) {
1382 this.next();
1383
1384 // ecma-262 14.6 Class Definitions
1385 // A class definition is always strict mode code.
1386 var oldStrict = this.strict;
1387 this.strict = true;
1388
1389 this.parseClassId(node, isStatement);
1390 this.parseClassSuper(node);
1391 var privateNameMap = this.enterClassBody();
1392 var classBody = this.startNode();
1393 var hadConstructor = false;
1394 classBody.body = [];
1395 this.expect(types$1.braceL);
1396 while (this.type !== types$1.braceR) {
1397 var element = this.parseClassElement(node.superClass !== null);
1398 if (element) {
1399 classBody.body.push(element);
1400 if (element.type === "MethodDefinition" && element.kind === "constructor") {
1401 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
1402 hadConstructor = true;
1403 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
1404 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
1405 }
1406 }
1407 }
1408 this.strict = oldStrict;
1409 this.next();
1410 node.body = this.finishNode(classBody, "ClassBody");
1411 this.exitClassBody();
1412 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
1413};
1414
1415pp$8.parseClassElement = function(constructorAllowsSuper) {
1416 if (this.eat(types$1.semi)) { return null }
1417
1418 var ecmaVersion = this.options.ecmaVersion;
1419 var node = this.startNode();
1420 var keyName = "";
1421 var isGenerator = false;
1422 var isAsync = false;
1423 var kind = "method";
1424 var isStatic = false;
1425
1426 if (this.eatContextual("static")) {
1427 // Parse static init block
1428 if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
1429 this.parseClassStaticBlock(node);
1430 return node
1431 }
1432 if (this.isClassElementNameStart() || this.type === types$1.star) {
1433 isStatic = true;
1434 } else {
1435 keyName = "static";
1436 }
1437 }
1438 node.static = isStatic;
1439 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
1440 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
1441 isAsync = true;
1442 } else {
1443 keyName = "async";
1444 }
1445 }
1446 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
1447 isGenerator = true;
1448 }
1449 if (!keyName && !isAsync && !isGenerator) {
1450 var lastValue = this.value;
1451 if (this.eatContextual("get") || this.eatContextual("set")) {
1452 if (this.isClassElementNameStart()) {
1453 kind = lastValue;
1454 } else {
1455 keyName = lastValue;
1456 }
1457 }
1458 }
1459
1460 // Parse element name
1461 if (keyName) {
1462 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
1463 // The last token is any of those. Make it the element name.
1464 node.computed = false;
1465 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
1466 node.key.name = keyName;
1467 this.finishNode(node.key, "Identifier");
1468 } else {
1469 this.parseClassElementName(node);
1470 }
1471
1472 // Parse element value
1473 if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
1474 var isConstructor = !node.static && checkKeyName(node, "constructor");
1475 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
1476 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
1477 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
1478 node.kind = isConstructor ? "constructor" : kind;
1479 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
1480 } else {
1481 this.parseClassField(node);
1482 }
1483
1484 return node
1485};
1486
1487pp$8.isClassElementNameStart = function() {
1488 return (
1489 this.type === types$1.name ||
1490 this.type === types$1.privateId ||
1491 this.type === types$1.num ||
1492 this.type === types$1.string ||
1493 this.type === types$1.bracketL ||
1494 this.type.keyword
1495 )
1496};
1497
1498pp$8.parseClassElementName = function(element) {
1499 if (this.type === types$1.privateId) {
1500 if (this.value === "constructor") {
1501 this.raise(this.start, "Classes can't have an element named '#constructor'");
1502 }
1503 element.computed = false;
1504 element.key = this.parsePrivateIdent();
1505 } else {
1506 this.parsePropertyName(element);
1507 }
1508};
1509
1510pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
1511 // Check key and flags
1512 var key = method.key;
1513 if (method.kind === "constructor") {
1514 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
1515 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
1516 } else if (method.static && checkKeyName(method, "prototype")) {
1517 this.raise(key.start, "Classes may not have a static property named prototype");
1518 }
1519
1520 // Parse value
1521 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
1522
1523 // Check value
1524 if (method.kind === "get" && value.params.length !== 0)
1525 { this.raiseRecoverable(value.start, "getter should have no params"); }
1526 if (method.kind === "set" && value.params.length !== 1)
1527 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
1528 if (method.kind === "set" && value.params[0].type === "RestElement")
1529 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
1530
1531 return this.finishNode(method, "MethodDefinition")
1532};
1533
1534pp$8.parseClassField = function(field) {
1535 if (checkKeyName(field, "constructor")) {
1536 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
1537 } else if (field.static && checkKeyName(field, "prototype")) {
1538 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
1539 }
1540
1541 if (this.eat(types$1.eq)) {
1542 // To raise SyntaxError if 'arguments' exists in the initializer.
1543 var scope = this.currentThisScope();
1544 var inClassFieldInit = scope.inClassFieldInit;
1545 scope.inClassFieldInit = true;
1546 field.value = this.parseMaybeAssign();
1547 scope.inClassFieldInit = inClassFieldInit;
1548 } else {
1549 field.value = null;
1550 }
1551 this.semicolon();
1552
1553 return this.finishNode(field, "PropertyDefinition")
1554};
1555
1556pp$8.parseClassStaticBlock = function(node) {
1557 node.body = [];
1558
1559 var oldLabels = this.labels;
1560 this.labels = [];
1561 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
1562 while (this.type !== types$1.braceR) {
1563 var stmt = this.parseStatement(null);
1564 node.body.push(stmt);
1565 }
1566 this.next();
1567 this.exitScope();
1568 this.labels = oldLabels;
1569
1570 return this.finishNode(node, "StaticBlock")
1571};
1572
1573pp$8.parseClassId = function(node, isStatement) {
1574 if (this.type === types$1.name) {
1575 node.id = this.parseIdent();
1576 if (isStatement)
1577 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
1578 } else {
1579 if (isStatement === true)
1580 { this.unexpected(); }
1581 node.id = null;
1582 }
1583};
1584
1585pp$8.parseClassSuper = function(node) {
1586 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
1587};
1588
1589pp$8.enterClassBody = function() {
1590 var element = {declared: Object.create(null), used: []};
1591 this.privateNameStack.push(element);
1592 return element.declared
1593};
1594
1595pp$8.exitClassBody = function() {
1596 var ref = this.privateNameStack.pop();
1597 var declared = ref.declared;
1598 var used = ref.used;
1599 var len = this.privateNameStack.length;
1600 var parent = len === 0 ? null : this.privateNameStack[len - 1];
1601 for (var i = 0; i < used.length; ++i) {
1602 var id = used[i];
1603 if (!hasOwn(declared, id.name)) {
1604 if (parent) {
1605 parent.used.push(id);
1606 } else {
1607 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
1608 }
1609 }
1610 }
1611};
1612
1613function isPrivateNameConflicted(privateNameMap, element) {
1614 var name = element.key.name;
1615 var curr = privateNameMap[name];
1616
1617 var next = "true";
1618 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
1619 next = (element.static ? "s" : "i") + element.kind;
1620 }
1621
1622 // `class { get #a(){}; static set #a(_){} }` is also conflict.
1623 if (
1624 curr === "iget" && next === "iset" ||
1625 curr === "iset" && next === "iget" ||
1626 curr === "sget" && next === "sset" ||
1627 curr === "sset" && next === "sget"
1628 ) {
1629 privateNameMap[name] = "true";
1630 return false
1631 } else if (!curr) {
1632 privateNameMap[name] = next;
1633 return false
1634 } else {
1635 return true
1636 }
1637}
1638
1639function checkKeyName(node, name) {
1640 var computed = node.computed;
1641 var key = node.key;
1642 return !computed && (
1643 key.type === "Identifier" && key.name === name ||
1644 key.type === "Literal" && key.value === name
1645 )
1646}
1647
1648// Parses module export declaration.
1649
1650pp$8.parseExport = function(node, exports) {
1651 this.next();
1652 // export * from '...'
1653 if (this.eat(types$1.star)) {
1654 if (this.options.ecmaVersion >= 11) {
1655 if (this.eatContextual("as")) {
1656 node.exported = this.parseModuleExportName();
1657 this.checkExport(exports, node.exported, this.lastTokStart);
1658 } else {
1659 node.exported = null;
1660 }
1661 }
1662 this.expectContextual("from");
1663 if (this.type !== types$1.string) { this.unexpected(); }
1664 node.source = this.parseExprAtom();
1665 this.semicolon();
1666 return this.finishNode(node, "ExportAllDeclaration")
1667 }
1668 if (this.eat(types$1._default)) { // export default ...
1669 this.checkExport(exports, "default", this.lastTokStart);
1670 var isAsync;
1671 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
1672 var fNode = this.startNode();
1673 this.next();
1674 if (isAsync) { this.next(); }
1675 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
1676 } else if (this.type === types$1._class) {
1677 var cNode = this.startNode();
1678 node.declaration = this.parseClass(cNode, "nullableID");
1679 } else {
1680 node.declaration = this.parseMaybeAssign();
1681 this.semicolon();
1682 }
1683 return this.finishNode(node, "ExportDefaultDeclaration")
1684 }
1685 // export var|const|let|function|class ...
1686 if (this.shouldParseExportStatement()) {
1687 node.declaration = this.parseStatement(null);
1688 if (node.declaration.type === "VariableDeclaration")
1689 { this.checkVariableExport(exports, node.declaration.declarations); }
1690 else
1691 { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
1692 node.specifiers = [];
1693 node.source = null;
1694 } else { // export { x, y as z } [from '...']
1695 node.declaration = null;
1696 node.specifiers = this.parseExportSpecifiers(exports);
1697 if (this.eatContextual("from")) {
1698 if (this.type !== types$1.string) { this.unexpected(); }
1699 node.source = this.parseExprAtom();
1700 } else {
1701 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
1702 // check for keywords used as local names
1703 var spec = list[i];
1704
1705 this.checkUnreserved(spec.local);
1706 // check if export is defined
1707 this.checkLocalExport(spec.local);
1708
1709 if (spec.local.type === "Literal") {
1710 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
1711 }
1712 }
1713
1714 node.source = null;
1715 }
1716 this.semicolon();
1717 }
1718 return this.finishNode(node, "ExportNamedDeclaration")
1719};
1720
1721pp$8.checkExport = function(exports, name, pos) {
1722 if (!exports) { return }
1723 if (typeof name !== "string")
1724 { name = name.type === "Identifier" ? name.name : name.value; }
1725 if (hasOwn(exports, name))
1726 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
1727 exports[name] = true;
1728};
1729
1730pp$8.checkPatternExport = function(exports, pat) {
1731 var type = pat.type;
1732 if (type === "Identifier")
1733 { this.checkExport(exports, pat, pat.start); }
1734 else if (type === "ObjectPattern")
1735 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
1736 {
1737 var prop = list[i];
1738
1739 this.checkPatternExport(exports, prop);
1740 } }
1741 else if (type === "ArrayPattern")
1742 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
1743 var elt = list$1[i$1];
1744
1745 if (elt) { this.checkPatternExport(exports, elt); }
1746 } }
1747 else if (type === "Property")
1748 { this.checkPatternExport(exports, pat.value); }
1749 else if (type === "AssignmentPattern")
1750 { this.checkPatternExport(exports, pat.left); }
1751 else if (type === "RestElement")
1752 { this.checkPatternExport(exports, pat.argument); }
1753 else if (type === "ParenthesizedExpression")
1754 { this.checkPatternExport(exports, pat.expression); }
1755};
1756
1757pp$8.checkVariableExport = function(exports, decls) {
1758 if (!exports) { return }
1759 for (var i = 0, list = decls; i < list.length; i += 1)
1760 {
1761 var decl = list[i];
1762
1763 this.checkPatternExport(exports, decl.id);
1764 }
1765};
1766
1767pp$8.shouldParseExportStatement = function() {
1768 return this.type.keyword === "var" ||
1769 this.type.keyword === "const" ||
1770 this.type.keyword === "class" ||
1771 this.type.keyword === "function" ||
1772 this.isLet() ||
1773 this.isAsyncFunction()
1774};
1775
1776// Parses a comma-separated list of module exports.
1777
1778pp$8.parseExportSpecifiers = function(exports) {
1779 var nodes = [], first = true;
1780 // export { x, y as z } [from '...']
1781 this.expect(types$1.braceL);
1782 while (!this.eat(types$1.braceR)) {
1783 if (!first) {
1784 this.expect(types$1.comma);
1785 if (this.afterTrailingComma(types$1.braceR)) { break }
1786 } else { first = false; }
1787
1788 var node = this.startNode();
1789 node.local = this.parseModuleExportName();
1790 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
1791 this.checkExport(
1792 exports,
1793 node.exported,
1794 node.exported.start
1795 );
1796 nodes.push(this.finishNode(node, "ExportSpecifier"));
1797 }
1798 return nodes
1799};
1800
1801// Parses import declaration.
1802
1803pp$8.parseImport = function(node) {
1804 this.next();
1805 // import '...'
1806 if (this.type === types$1.string) {
1807 node.specifiers = empty$1;
1808 node.source = this.parseExprAtom();
1809 } else {
1810 node.specifiers = this.parseImportSpecifiers();
1811 this.expectContextual("from");
1812 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
1813 }
1814 this.semicolon();
1815 return this.finishNode(node, "ImportDeclaration")
1816};
1817
1818// Parses a comma-separated list of module imports.
1819
1820pp$8.parseImportSpecifiers = function() {
1821 var nodes = [], first = true;
1822 if (this.type === types$1.name) {
1823 // import defaultObj, { x, y as z } from '...'
1824 var node = this.startNode();
1825 node.local = this.parseIdent();
1826 this.checkLValSimple(node.local, BIND_LEXICAL);
1827 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
1828 if (!this.eat(types$1.comma)) { return nodes }
1829 }
1830 if (this.type === types$1.star) {
1831 var node$1 = this.startNode();
1832 this.next();
1833 this.expectContextual("as");
1834 node$1.local = this.parseIdent();
1835 this.checkLValSimple(node$1.local, BIND_LEXICAL);
1836 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
1837 return nodes
1838 }
1839 this.expect(types$1.braceL);
1840 while (!this.eat(types$1.braceR)) {
1841 if (!first) {
1842 this.expect(types$1.comma);
1843 if (this.afterTrailingComma(types$1.braceR)) { break }
1844 } else { first = false; }
1845
1846 var node$2 = this.startNode();
1847 node$2.imported = this.parseModuleExportName();
1848 if (this.eatContextual("as")) {
1849 node$2.local = this.parseIdent();
1850 } else {
1851 this.checkUnreserved(node$2.imported);
1852 node$2.local = node$2.imported;
1853 }
1854 this.checkLValSimple(node$2.local, BIND_LEXICAL);
1855 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
1856 }
1857 return nodes
1858};
1859
1860pp$8.parseModuleExportName = function() {
1861 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
1862 var stringLiteral = this.parseLiteral(this.value);
1863 if (loneSurrogate.test(stringLiteral.value)) {
1864 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
1865 }
1866 return stringLiteral
1867 }
1868 return this.parseIdent(true)
1869};
1870
1871// Set `ExpressionStatement#directive` property for directive prologues.
1872pp$8.adaptDirectivePrologue = function(statements) {
1873 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
1874 statements[i].directive = statements[i].expression.raw.slice(1, -1);
1875 }
1876};
1877pp$8.isDirectiveCandidate = function(statement) {
1878 return (
1879 this.options.ecmaVersion >= 5 &&
1880 statement.type === "ExpressionStatement" &&
1881 statement.expression.type === "Literal" &&
1882 typeof statement.expression.value === "string" &&
1883 // Reject parenthesized strings.
1884 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
1885 )
1886};
1887
1888var pp$7 = Parser.prototype;
1889
1890// Convert existing expression atom to assignable pattern
1891// if possible.
1892
1893pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
1894 if (this.options.ecmaVersion >= 6 && node) {
1895 switch (node.type) {
1896 case "Identifier":
1897 if (this.inAsync && node.name === "await")
1898 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
1899 break
1900
1901 case "ObjectPattern":
1902 case "ArrayPattern":
1903 case "AssignmentPattern":
1904 case "RestElement":
1905 break
1906
1907 case "ObjectExpression":
1908 node.type = "ObjectPattern";
1909 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
1910 for (var i = 0, list = node.properties; i < list.length; i += 1) {
1911 var prop = list[i];
1912
1913 this.toAssignable(prop, isBinding);
1914 // Early error:
1915 // AssignmentRestProperty[Yield, Await] :
1916 // `...` DestructuringAssignmentTarget[Yield, Await]
1917 //
1918 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
1919 if (
1920 prop.type === "RestElement" &&
1921 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
1922 ) {
1923 this.raise(prop.argument.start, "Unexpected token");
1924 }
1925 }
1926 break
1927
1928 case "Property":
1929 // AssignmentProperty has type === "Property"
1930 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
1931 this.toAssignable(node.value, isBinding);
1932 break
1933
1934 case "ArrayExpression":
1935 node.type = "ArrayPattern";
1936 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
1937 this.toAssignableList(node.elements, isBinding);
1938 break
1939
1940 case "SpreadElement":
1941 node.type = "RestElement";
1942 this.toAssignable(node.argument, isBinding);
1943 if (node.argument.type === "AssignmentPattern")
1944 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
1945 break
1946
1947 case "AssignmentExpression":
1948 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
1949 node.type = "AssignmentPattern";
1950 delete node.operator;
1951 this.toAssignable(node.left, isBinding);
1952 break
1953
1954 case "ParenthesizedExpression":
1955 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
1956 break
1957
1958 case "ChainExpression":
1959 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
1960 break
1961
1962 case "MemberExpression":
1963 if (!isBinding) { break }
1964
1965 default:
1966 this.raise(node.start, "Assigning to rvalue");
1967 }
1968 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
1969 return node
1970};
1971
1972// Convert list of expression atoms to binding list.
1973
1974pp$7.toAssignableList = function(exprList, isBinding) {
1975 var end = exprList.length;
1976 for (var i = 0; i < end; i++) {
1977 var elt = exprList[i];
1978 if (elt) { this.toAssignable(elt, isBinding); }
1979 }
1980 if (end) {
1981 var last = exprList[end - 1];
1982 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
1983 { this.unexpected(last.argument.start); }
1984 }
1985 return exprList
1986};
1987
1988// Parses spread element.
1989
1990pp$7.parseSpread = function(refDestructuringErrors) {
1991 var node = this.startNode();
1992 this.next();
1993 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
1994 return this.finishNode(node, "SpreadElement")
1995};
1996
1997pp$7.parseRestBinding = function() {
1998 var node = this.startNode();
1999 this.next();
2000
2001 // RestElement inside of a function parameter must be an identifier
2002 if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
2003 { this.unexpected(); }
2004
2005 node.argument = this.parseBindingAtom();
2006
2007 return this.finishNode(node, "RestElement")
2008};
2009
2010// Parses lvalue (assignable) atom.
2011
2012pp$7.parseBindingAtom = function() {
2013 if (this.options.ecmaVersion >= 6) {
2014 switch (this.type) {
2015 case types$1.bracketL:
2016 var node = this.startNode();
2017 this.next();
2018 node.elements = this.parseBindingList(types$1.bracketR, true, true);
2019 return this.finishNode(node, "ArrayPattern")
2020
2021 case types$1.braceL:
2022 return this.parseObj(true)
2023 }
2024 }
2025 return this.parseIdent()
2026};
2027
2028pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
2029 var elts = [], first = true;
2030 while (!this.eat(close)) {
2031 if (first) { first = false; }
2032 else { this.expect(types$1.comma); }
2033 if (allowEmpty && this.type === types$1.comma) {
2034 elts.push(null);
2035 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
2036 break
2037 } else if (this.type === types$1.ellipsis) {
2038 var rest = this.parseRestBinding();
2039 this.parseBindingListItem(rest);
2040 elts.push(rest);
2041 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
2042 this.expect(close);
2043 break
2044 } else {
2045 var elem = this.parseMaybeDefault(this.start, this.startLoc);
2046 this.parseBindingListItem(elem);
2047 elts.push(elem);
2048 }
2049 }
2050 return elts
2051};
2052
2053pp$7.parseBindingListItem = function(param) {
2054 return param
2055};
2056
2057// Parses assignment pattern around given atom if possible.
2058
2059pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
2060 left = left || this.parseBindingAtom();
2061 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
2062 var node = this.startNodeAt(startPos, startLoc);
2063 node.left = left;
2064 node.right = this.parseMaybeAssign();
2065 return this.finishNode(node, "AssignmentPattern")
2066};
2067
2068// The following three functions all verify that a node is an lvalue —
2069// something that can be bound, or assigned to. In order to do so, they perform
2070// a variety of checks:
2071//
2072// - Check that none of the bound/assigned-to identifiers are reserved words.
2073// - Record name declarations for bindings in the appropriate scope.
2074// - Check duplicate argument names, if checkClashes is set.
2075//
2076// If a complex binding pattern is encountered (e.g., object and array
2077// destructuring), the entire pattern is recursively checked.
2078//
2079// There are three versions of checkLVal*() appropriate for different
2080// circumstances:
2081//
2082// - checkLValSimple() shall be used if the syntactic construct supports
2083// nothing other than identifiers and member expressions. Parenthesized
2084// expressions are also correctly handled. This is generally appropriate for
2085// constructs for which the spec says
2086//
2087// > It is a Syntax Error if AssignmentTargetType of [the production] is not
2088// > simple.
2089//
2090// It is also appropriate for checking if an identifier is valid and not
2091// defined elsewhere, like import declarations or function/class identifiers.
2092//
2093// Examples where this is used include:
2094// a += …;
2095// import a from '…';
2096// where a is the node to be checked.
2097//
2098// - checkLValPattern() shall be used if the syntactic construct supports
2099// anything checkLValSimple() supports, as well as object and array
2100// destructuring patterns. This is generally appropriate for constructs for
2101// which the spec says
2102//
2103// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
2104// > an ArrayLiteral and AssignmentTargetType of [the production] is not
2105// > simple.
2106//
2107// Examples where this is used include:
2108// (a = …);
2109// const a = …;
2110// try { … } catch (a) { … }
2111// where a is the node to be checked.
2112//
2113// - checkLValInnerPattern() shall be used if the syntactic construct supports
2114// anything checkLValPattern() supports, as well as default assignment
2115// patterns, rest elements, and other constructs that may appear within an
2116// object or array destructuring pattern.
2117//
2118// As a special case, function parameters also use checkLValInnerPattern(),
2119// as they also support defaults and rest constructs.
2120//
2121// These functions deliberately support both assignment and binding constructs,
2122// as the logic for both is exceedingly similar. If the node is the target of
2123// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
2124// should be set to the appropriate BIND_* constant, like BIND_VAR or
2125// BIND_LEXICAL.
2126//
2127// If the function is called with a non-BIND_NONE bindingType, then
2128// additionally a checkClashes object may be specified to allow checking for
2129// duplicate argument names. checkClashes is ignored if the provided construct
2130// is an assignment (i.e., bindingType is BIND_NONE).
2131
2132pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
2133 if ( bindingType === void 0 ) bindingType = BIND_NONE;
2134
2135 var isBind = bindingType !== BIND_NONE;
2136
2137 switch (expr.type) {
2138 case "Identifier":
2139 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
2140 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
2141 if (isBind) {
2142 if (bindingType === BIND_LEXICAL && expr.name === "let")
2143 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
2144 if (checkClashes) {
2145 if (hasOwn(checkClashes, expr.name))
2146 { this.raiseRecoverable(expr.start, "Argument name clash"); }
2147 checkClashes[expr.name] = true;
2148 }
2149 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
2150 }
2151 break
2152
2153 case "ChainExpression":
2154 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
2155 break
2156
2157 case "MemberExpression":
2158 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
2159 break
2160
2161 case "ParenthesizedExpression":
2162 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
2163 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
2164
2165 default:
2166 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
2167 }
2168};
2169
2170pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
2171 if ( bindingType === void 0 ) bindingType = BIND_NONE;
2172
2173 switch (expr.type) {
2174 case "ObjectPattern":
2175 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
2176 var prop = list[i];
2177
2178 this.checkLValInnerPattern(prop, bindingType, checkClashes);
2179 }
2180 break
2181
2182 case "ArrayPattern":
2183 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
2184 var elem = list$1[i$1];
2185
2186 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
2187 }
2188 break
2189
2190 default:
2191 this.checkLValSimple(expr, bindingType, checkClashes);
2192 }
2193};
2194
2195pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
2196 if ( bindingType === void 0 ) bindingType = BIND_NONE;
2197
2198 switch (expr.type) {
2199 case "Property":
2200 // AssignmentProperty has type === "Property"
2201 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
2202 break
2203
2204 case "AssignmentPattern":
2205 this.checkLValPattern(expr.left, bindingType, checkClashes);
2206 break
2207
2208 case "RestElement":
2209 this.checkLValPattern(expr.argument, bindingType, checkClashes);
2210 break
2211
2212 default:
2213 this.checkLValPattern(expr, bindingType, checkClashes);
2214 }
2215};
2216
2217// The algorithm used to determine whether a regexp can appear at a
2218
2219var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
2220 this.token = token;
2221 this.isExpr = !!isExpr;
2222 this.preserveSpace = !!preserveSpace;
2223 this.override = override;
2224 this.generator = !!generator;
2225};
2226
2227var types = {
2228 b_stat: new TokContext("{", false),
2229 b_expr: new TokContext("{", true),
2230 b_tmpl: new TokContext("${", false),
2231 p_stat: new TokContext("(", false),
2232 p_expr: new TokContext("(", true),
2233 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
2234 f_stat: new TokContext("function", false),
2235 f_expr: new TokContext("function", true),
2236 f_expr_gen: new TokContext("function", true, false, null, true),
2237 f_gen: new TokContext("function", false, false, null, true)
2238};
2239
2240var pp$6 = Parser.prototype;
2241
2242pp$6.initialContext = function() {
2243 return [types.b_stat]
2244};
2245
2246pp$6.curContext = function() {
2247 return this.context[this.context.length - 1]
2248};
2249
2250pp$6.braceIsBlock = function(prevType) {
2251 var parent = this.curContext();
2252 if (parent === types.f_expr || parent === types.f_stat)
2253 { return true }
2254 if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
2255 { return !parent.isExpr }
2256
2257 // The check for `tt.name && exprAllowed` detects whether we are
2258 // after a `yield` or `of` construct. See the `updateContext` for
2259 // `tt.name`.
2260 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
2261 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
2262 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
2263 { return true }
2264 if (prevType === types$1.braceL)
2265 { return parent === types.b_stat }
2266 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
2267 { return false }
2268 return !this.exprAllowed
2269};
2270
2271pp$6.inGeneratorContext = function() {
2272 for (var i = this.context.length - 1; i >= 1; i--) {
2273 var context = this.context[i];
2274 if (context.token === "function")
2275 { return context.generator }
2276 }
2277 return false
2278};
2279
2280pp$6.updateContext = function(prevType) {
2281 var update, type = this.type;
2282 if (type.keyword && prevType === types$1.dot)
2283 { this.exprAllowed = false; }
2284 else if (update = type.updateContext)
2285 { update.call(this, prevType); }
2286 else
2287 { this.exprAllowed = type.beforeExpr; }
2288};
2289
2290// Used to handle egde cases when token context could not be inferred correctly during tokenization phase
2291
2292pp$6.overrideContext = function(tokenCtx) {
2293 if (this.curContext() !== tokenCtx) {
2294 this.context[this.context.length - 1] = tokenCtx;
2295 }
2296};
2297
2298// Token-specific context update code
2299
2300types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
2301 if (this.context.length === 1) {
2302 this.exprAllowed = true;
2303 return
2304 }
2305 var out = this.context.pop();
2306 if (out === types.b_stat && this.curContext().token === "function") {
2307 out = this.context.pop();
2308 }
2309 this.exprAllowed = !out.isExpr;
2310};
2311
2312types$1.braceL.updateContext = function(prevType) {
2313 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
2314 this.exprAllowed = true;
2315};
2316
2317types$1.dollarBraceL.updateContext = function() {
2318 this.context.push(types.b_tmpl);
2319 this.exprAllowed = true;
2320};
2321
2322types$1.parenL.updateContext = function(prevType) {
2323 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
2324 this.context.push(statementParens ? types.p_stat : types.p_expr);
2325 this.exprAllowed = true;
2326};
2327
2328types$1.incDec.updateContext = function() {
2329 // tokExprAllowed stays unchanged
2330};
2331
2332types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
2333 if (prevType.beforeExpr && prevType !== types$1._else &&
2334 !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
2335 !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
2336 !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
2337 { this.context.push(types.f_expr); }
2338 else
2339 { this.context.push(types.f_stat); }
2340 this.exprAllowed = false;
2341};
2342
2343types$1.backQuote.updateContext = function() {
2344 if (this.curContext() === types.q_tmpl)
2345 { this.context.pop(); }
2346 else
2347 { this.context.push(types.q_tmpl); }
2348 this.exprAllowed = false;
2349};
2350
2351types$1.star.updateContext = function(prevType) {
2352 if (prevType === types$1._function) {
2353 var index = this.context.length - 1;
2354 if (this.context[index] === types.f_expr)
2355 { this.context[index] = types.f_expr_gen; }
2356 else
2357 { this.context[index] = types.f_gen; }
2358 }
2359 this.exprAllowed = true;
2360};
2361
2362types$1.name.updateContext = function(prevType) {
2363 var allowed = false;
2364 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
2365 if (this.value === "of" && !this.exprAllowed ||
2366 this.value === "yield" && this.inGeneratorContext())
2367 { allowed = true; }
2368 }
2369 this.exprAllowed = allowed;
2370};
2371
2372// A recursive descent parser operates by defining functions for all
2373
2374var pp$5 = Parser.prototype;
2375
2376// Check if property name clashes with already added.
2377// Object/class getters and setters are not allowed to clash —
2378// either with each other or with an init property — and in
2379// strict mode, init properties are also not allowed to be repeated.
2380
2381pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
2382 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
2383 { return }
2384 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
2385 { return }
2386 var key = prop.key;
2387 var name;
2388 switch (key.type) {
2389 case "Identifier": name = key.name; break
2390 case "Literal": name = String(key.value); break
2391 default: return
2392 }
2393 var kind = prop.kind;
2394 if (this.options.ecmaVersion >= 6) {
2395 if (name === "__proto__" && kind === "init") {
2396 if (propHash.proto) {
2397 if (refDestructuringErrors) {
2398 if (refDestructuringErrors.doubleProto < 0) {
2399 refDestructuringErrors.doubleProto = key.start;
2400 }
2401 } else {
2402 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
2403 }
2404 }
2405 propHash.proto = true;
2406 }
2407 return
2408 }
2409 name = "$" + name;
2410 var other = propHash[name];
2411 if (other) {
2412 var redefinition;
2413 if (kind === "init") {
2414 redefinition = this.strict && other.init || other.get || other.set;
2415 } else {
2416 redefinition = other.init || other[kind];
2417 }
2418 if (redefinition)
2419 { this.raiseRecoverable(key.start, "Redefinition of property"); }
2420 } else {
2421 other = propHash[name] = {
2422 init: false,
2423 get: false,
2424 set: false
2425 };
2426 }
2427 other[kind] = true;
2428};
2429
2430// ### Expression parsing
2431
2432// These nest, from the most general expression type at the top to
2433// 'atomic', nondivisible expression types at the bottom. Most of
2434// the functions will simply let the function(s) below them parse,
2435// and, *if* the syntactic construct they handle is present, wrap
2436// the AST node that the inner parser gave them in another node.
2437
2438// Parse a full expression. The optional arguments are used to
2439// forbid the `in` operator (in for loops initalization expressions)
2440// and provide reference for storing '=' operator inside shorthand
2441// property assignment in contexts where both object expression
2442// and object pattern might appear (so it's possible to raise
2443// delayed syntax error at correct position).
2444
2445pp$5.parseExpression = function(forInit, refDestructuringErrors) {
2446 var startPos = this.start, startLoc = this.startLoc;
2447 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
2448 if (this.type === types$1.comma) {
2449 var node = this.startNodeAt(startPos, startLoc);
2450 node.expressions = [expr];
2451 while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
2452 return this.finishNode(node, "SequenceExpression")
2453 }
2454 return expr
2455};
2456
2457// Parse an assignment expression. This includes applications of
2458// operators like `+=`.
2459
2460pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
2461 if (this.isContextual("yield")) {
2462 if (this.inGenerator) { return this.parseYield(forInit) }
2463 // The tokenizer will assume an expression is allowed after
2464 // `yield`, but this isn't that kind of yield
2465 else { this.exprAllowed = false; }
2466 }
2467
2468 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
2469 if (refDestructuringErrors) {
2470 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
2471 oldTrailingComma = refDestructuringErrors.trailingComma;
2472 oldDoubleProto = refDestructuringErrors.doubleProto;
2473 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
2474 } else {
2475 refDestructuringErrors = new DestructuringErrors;
2476 ownDestructuringErrors = true;
2477 }
2478
2479 var startPos = this.start, startLoc = this.startLoc;
2480 if (this.type === types$1.parenL || this.type === types$1.name) {
2481 this.potentialArrowAt = this.start;
2482 this.potentialArrowInForAwait = forInit === "await";
2483 }
2484 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
2485 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
2486 if (this.type.isAssign) {
2487 var node = this.startNodeAt(startPos, startLoc);
2488 node.operator = this.value;
2489 if (this.type === types$1.eq)
2490 { left = this.toAssignable(left, false, refDestructuringErrors); }
2491 if (!ownDestructuringErrors) {
2492 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
2493 }
2494 if (refDestructuringErrors.shorthandAssign >= left.start)
2495 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
2496 if (this.type === types$1.eq)
2497 { this.checkLValPattern(left); }
2498 else
2499 { this.checkLValSimple(left); }
2500 node.left = left;
2501 this.next();
2502 node.right = this.parseMaybeAssign(forInit);
2503 if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
2504 return this.finishNode(node, "AssignmentExpression")
2505 } else {
2506 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
2507 }
2508 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
2509 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
2510 return left
2511};
2512
2513// Parse a ternary conditional (`?:`) operator.
2514
2515pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
2516 var startPos = this.start, startLoc = this.startLoc;
2517 var expr = this.parseExprOps(forInit, refDestructuringErrors);
2518 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
2519 if (this.eat(types$1.question)) {
2520 var node = this.startNodeAt(startPos, startLoc);
2521 node.test = expr;
2522 node.consequent = this.parseMaybeAssign();
2523 this.expect(types$1.colon);
2524 node.alternate = this.parseMaybeAssign(forInit);
2525 return this.finishNode(node, "ConditionalExpression")
2526 }
2527 return expr
2528};
2529
2530// Start the precedence parser.
2531
2532pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
2533 var startPos = this.start, startLoc = this.startLoc;
2534 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
2535 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
2536 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
2537};
2538
2539// Parse binary operators with the operator precedence parsing
2540// algorithm. `left` is the left-hand side of the operator.
2541// `minPrec` provides context that allows the function to stop and
2542// defer further parser to one of its callers when it encounters an
2543// operator that has a lower precedence than the set it is parsing.
2544
2545pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
2546 var prec = this.type.binop;
2547 if (prec != null && (!forInit || this.type !== types$1._in)) {
2548 if (prec > minPrec) {
2549 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
2550 var coalesce = this.type === types$1.coalesce;
2551 if (coalesce) {
2552 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
2553 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
2554 prec = types$1.logicalAND.binop;
2555 }
2556 var op = this.value;
2557 this.next();
2558 var startPos = this.start, startLoc = this.startLoc;
2559 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
2560 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
2561 if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
2562 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
2563 }
2564 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
2565 }
2566 }
2567 return left
2568};
2569
2570pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
2571 if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
2572 var node = this.startNodeAt(startPos, startLoc);
2573 node.left = left;
2574 node.operator = op;
2575 node.right = right;
2576 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
2577};
2578
2579// Parse unary operators, both prefix and postfix.
2580
2581pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
2582 var startPos = this.start, startLoc = this.startLoc, expr;
2583 if (this.isContextual("await") && this.canAwait) {
2584 expr = this.parseAwait(forInit);
2585 sawUnary = true;
2586 } else if (this.type.prefix) {
2587 var node = this.startNode(), update = this.type === types$1.incDec;
2588 node.operator = this.value;
2589 node.prefix = true;
2590 this.next();
2591 node.argument = this.parseMaybeUnary(null, true, update, forInit);
2592 this.checkExpressionErrors(refDestructuringErrors, true);
2593 if (update) { this.checkLValSimple(node.argument); }
2594 else if (this.strict && node.operator === "delete" &&
2595 node.argument.type === "Identifier")
2596 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
2597 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
2598 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
2599 else { sawUnary = true; }
2600 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
2601 } else if (!sawUnary && this.type === types$1.privateId) {
2602 if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
2603 expr = this.parsePrivateIdent();
2604 // only could be private fields in 'in', such as #x in obj
2605 if (this.type !== types$1._in) { this.unexpected(); }
2606 } else {
2607 expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
2608 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
2609 while (this.type.postfix && !this.canInsertSemicolon()) {
2610 var node$1 = this.startNodeAt(startPos, startLoc);
2611 node$1.operator = this.value;
2612 node$1.prefix = false;
2613 node$1.argument = expr;
2614 this.checkLValSimple(expr);
2615 this.next();
2616 expr = this.finishNode(node$1, "UpdateExpression");
2617 }
2618 }
2619
2620 if (!incDec && this.eat(types$1.starstar)) {
2621 if (sawUnary)
2622 { this.unexpected(this.lastTokStart); }
2623 else
2624 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
2625 } else {
2626 return expr
2627 }
2628};
2629
2630function isPrivateFieldAccess(node) {
2631 return (
2632 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
2633 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
2634 )
2635}
2636
2637// Parse call, dot, and `[]`-subscript expressions.
2638
2639pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
2640 var startPos = this.start, startLoc = this.startLoc;
2641 var expr = this.parseExprAtom(refDestructuringErrors, forInit);
2642 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
2643 { return expr }
2644 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
2645 if (refDestructuringErrors && result.type === "MemberExpression") {
2646 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
2647 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
2648 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
2649 }
2650 return result
2651};
2652
2653pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
2654 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
2655 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
2656 this.potentialArrowAt === base.start;
2657 var optionalChained = false;
2658
2659 while (true) {
2660 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
2661
2662 if (element.optional) { optionalChained = true; }
2663 if (element === base || element.type === "ArrowFunctionExpression") {
2664 if (optionalChained) {
2665 var chainNode = this.startNodeAt(startPos, startLoc);
2666 chainNode.expression = element;
2667 element = this.finishNode(chainNode, "ChainExpression");
2668 }
2669 return element
2670 }
2671
2672 base = element;
2673 }
2674};
2675
2676pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
2677 var optionalSupported = this.options.ecmaVersion >= 11;
2678 var optional = optionalSupported && this.eat(types$1.questionDot);
2679 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
2680
2681 var computed = this.eat(types$1.bracketL);
2682 if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
2683 var node = this.startNodeAt(startPos, startLoc);
2684 node.object = base;
2685 if (computed) {
2686 node.property = this.parseExpression();
2687 this.expect(types$1.bracketR);
2688 } else if (this.type === types$1.privateId && base.type !== "Super") {
2689 node.property = this.parsePrivateIdent();
2690 } else {
2691 node.property = this.parseIdent(this.options.allowReserved !== "never");
2692 }
2693 node.computed = !!computed;
2694 if (optionalSupported) {
2695 node.optional = optional;
2696 }
2697 base = this.finishNode(node, "MemberExpression");
2698 } else if (!noCalls && this.eat(types$1.parenL)) {
2699 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
2700 this.yieldPos = 0;
2701 this.awaitPos = 0;
2702 this.awaitIdentPos = 0;
2703 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
2704 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
2705 this.checkPatternErrors(refDestructuringErrors, false);
2706 this.checkYieldAwaitInDefaultParams();
2707 if (this.awaitIdentPos > 0)
2708 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
2709 this.yieldPos = oldYieldPos;
2710 this.awaitPos = oldAwaitPos;
2711 this.awaitIdentPos = oldAwaitIdentPos;
2712 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
2713 }
2714 this.checkExpressionErrors(refDestructuringErrors, true);
2715 this.yieldPos = oldYieldPos || this.yieldPos;
2716 this.awaitPos = oldAwaitPos || this.awaitPos;
2717 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
2718 var node$1 = this.startNodeAt(startPos, startLoc);
2719 node$1.callee = base;
2720 node$1.arguments = exprList;
2721 if (optionalSupported) {
2722 node$1.optional = optional;
2723 }
2724 base = this.finishNode(node$1, "CallExpression");
2725 } else if (this.type === types$1.backQuote) {
2726 if (optional || optionalChained) {
2727 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
2728 }
2729 var node$2 = this.startNodeAt(startPos, startLoc);
2730 node$2.tag = base;
2731 node$2.quasi = this.parseTemplate({isTagged: true});
2732 base = this.finishNode(node$2, "TaggedTemplateExpression");
2733 }
2734 return base
2735};
2736
2737// Parse an atomic expression — either a single token that is an
2738// expression, an expression started by a keyword like `function` or
2739// `new`, or an expression wrapped in punctuation like `()`, `[]`,
2740// or `{}`.
2741
2742pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
2743 // If a division operator appears in an expression position, the
2744 // tokenizer got confused, and we force it to read a regexp instead.
2745 if (this.type === types$1.slash) { this.readRegexp(); }
2746
2747 var node, canBeArrow = this.potentialArrowAt === this.start;
2748 switch (this.type) {
2749 case types$1._super:
2750 if (!this.allowSuper)
2751 { this.raise(this.start, "'super' keyword outside a method"); }
2752 node = this.startNode();
2753 this.next();
2754 if (this.type === types$1.parenL && !this.allowDirectSuper)
2755 { this.raise(node.start, "super() call outside constructor of a subclass"); }
2756 // The `super` keyword can appear at below:
2757 // SuperProperty:
2758 // super [ Expression ]
2759 // super . IdentifierName
2760 // SuperCall:
2761 // super ( Arguments )
2762 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
2763 { this.unexpected(); }
2764 return this.finishNode(node, "Super")
2765
2766 case types$1._this:
2767 node = this.startNode();
2768 this.next();
2769 return this.finishNode(node, "ThisExpression")
2770
2771 case types$1.name:
2772 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
2773 var id = this.parseIdent(false);
2774 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
2775 this.overrideContext(types.f_expr);
2776 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
2777 }
2778 if (canBeArrow && !this.canInsertSemicolon()) {
2779 if (this.eat(types$1.arrow))
2780 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
2781 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
2782 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
2783 id = this.parseIdent(false);
2784 if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
2785 { this.unexpected(); }
2786 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
2787 }
2788 }
2789 return id
2790
2791 case types$1.regexp:
2792 var value = this.value;
2793 node = this.parseLiteral(value.value);
2794 node.regex = {pattern: value.pattern, flags: value.flags};
2795 return node
2796
2797 case types$1.num: case types$1.string:
2798 return this.parseLiteral(this.value)
2799
2800 case types$1._null: case types$1._true: case types$1._false:
2801 node = this.startNode();
2802 node.value = this.type === types$1._null ? null : this.type === types$1._true;
2803 node.raw = this.type.keyword;
2804 this.next();
2805 return this.finishNode(node, "Literal")
2806
2807 case types$1.parenL:
2808 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
2809 if (refDestructuringErrors) {
2810 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
2811 { refDestructuringErrors.parenthesizedAssign = start; }
2812 if (refDestructuringErrors.parenthesizedBind < 0)
2813 { refDestructuringErrors.parenthesizedBind = start; }
2814 }
2815 return expr
2816
2817 case types$1.bracketL:
2818 node = this.startNode();
2819 this.next();
2820 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
2821 return this.finishNode(node, "ArrayExpression")
2822
2823 case types$1.braceL:
2824 this.overrideContext(types.b_expr);
2825 return this.parseObj(false, refDestructuringErrors)
2826
2827 case types$1._function:
2828 node = this.startNode();
2829 this.next();
2830 return this.parseFunction(node, 0)
2831
2832 case types$1._class:
2833 return this.parseClass(this.startNode(), false)
2834
2835 case types$1._new:
2836 return this.parseNew()
2837
2838 case types$1.backQuote:
2839 return this.parseTemplate()
2840
2841 case types$1._import:
2842 if (this.options.ecmaVersion >= 11) {
2843 return this.parseExprImport()
2844 } else {
2845 return this.unexpected()
2846 }
2847
2848 default:
2849 this.unexpected();
2850 }
2851};
2852
2853pp$5.parseExprImport = function() {
2854 var node = this.startNode();
2855
2856 // Consume `import` as an identifier for `import.meta`.
2857 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
2858 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
2859 var meta = this.parseIdent(true);
2860
2861 switch (this.type) {
2862 case types$1.parenL:
2863 return this.parseDynamicImport(node)
2864 case types$1.dot:
2865 node.meta = meta;
2866 return this.parseImportMeta(node)
2867 default:
2868 this.unexpected();
2869 }
2870};
2871
2872pp$5.parseDynamicImport = function(node) {
2873 this.next(); // skip `(`
2874
2875 // Parse node.source.
2876 node.source = this.parseMaybeAssign();
2877
2878 // Verify ending.
2879 if (!this.eat(types$1.parenR)) {
2880 var errorPos = this.start;
2881 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
2882 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
2883 } else {
2884 this.unexpected(errorPos);
2885 }
2886 }
2887
2888 return this.finishNode(node, "ImportExpression")
2889};
2890
2891pp$5.parseImportMeta = function(node) {
2892 this.next(); // skip `.`
2893
2894 var containsEsc = this.containsEsc;
2895 node.property = this.parseIdent(true);
2896
2897 if (node.property.name !== "meta")
2898 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
2899 if (containsEsc)
2900 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
2901 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
2902 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
2903
2904 return this.finishNode(node, "MetaProperty")
2905};
2906
2907pp$5.parseLiteral = function(value) {
2908 var node = this.startNode();
2909 node.value = value;
2910 node.raw = this.input.slice(this.start, this.end);
2911 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
2912 this.next();
2913 return this.finishNode(node, "Literal")
2914};
2915
2916pp$5.parseParenExpression = function() {
2917 this.expect(types$1.parenL);
2918 var val = this.parseExpression();
2919 this.expect(types$1.parenR);
2920 return val
2921};
2922
2923pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
2924 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
2925 if (this.options.ecmaVersion >= 6) {
2926 this.next();
2927
2928 var innerStartPos = this.start, innerStartLoc = this.startLoc;
2929 var exprList = [], first = true, lastIsComma = false;
2930 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
2931 this.yieldPos = 0;
2932 this.awaitPos = 0;
2933 // Do not save awaitIdentPos to allow checking awaits nested in parameters
2934 while (this.type !== types$1.parenR) {
2935 first ? first = false : this.expect(types$1.comma);
2936 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
2937 lastIsComma = true;
2938 break
2939 } else if (this.type === types$1.ellipsis) {
2940 spreadStart = this.start;
2941 exprList.push(this.parseParenItem(this.parseRestBinding()));
2942 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
2943 break
2944 } else {
2945 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
2946 }
2947 }
2948 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
2949 this.expect(types$1.parenR);
2950
2951 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
2952 this.checkPatternErrors(refDestructuringErrors, false);
2953 this.checkYieldAwaitInDefaultParams();
2954 this.yieldPos = oldYieldPos;
2955 this.awaitPos = oldAwaitPos;
2956 return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
2957 }
2958
2959 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
2960 if (spreadStart) { this.unexpected(spreadStart); }
2961 this.checkExpressionErrors(refDestructuringErrors, true);
2962 this.yieldPos = oldYieldPos || this.yieldPos;
2963 this.awaitPos = oldAwaitPos || this.awaitPos;
2964
2965 if (exprList.length > 1) {
2966 val = this.startNodeAt(innerStartPos, innerStartLoc);
2967 val.expressions = exprList;
2968 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
2969 } else {
2970 val = exprList[0];
2971 }
2972 } else {
2973 val = this.parseParenExpression();
2974 }
2975
2976 if (this.options.preserveParens) {
2977 var par = this.startNodeAt(startPos, startLoc);
2978 par.expression = val;
2979 return this.finishNode(par, "ParenthesizedExpression")
2980 } else {
2981 return val
2982 }
2983};
2984
2985pp$5.parseParenItem = function(item) {
2986 return item
2987};
2988
2989pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
2990 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
2991};
2992
2993// New's precedence is slightly tricky. It must allow its argument to
2994// be a `[]` or dot subscript expression, but not a call — at least,
2995// not without wrapping it in parentheses. Thus, it uses the noCalls
2996// argument to parseSubscripts to prevent it from consuming the
2997// argument list.
2998
2999var empty = [];
3000
3001pp$5.parseNew = function() {
3002 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
3003 var node = this.startNode();
3004 var meta = this.parseIdent(true);
3005 if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
3006 node.meta = meta;
3007 var containsEsc = this.containsEsc;
3008 node.property = this.parseIdent(true);
3009 if (node.property.name !== "target")
3010 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
3011 if (containsEsc)
3012 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
3013 if (!this.allowNewDotTarget)
3014 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
3015 return this.finishNode(node, "MetaProperty")
3016 }
3017 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
3018 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
3019 if (isImport && node.callee.type === "ImportExpression") {
3020 this.raise(startPos, "Cannot use new with import()");
3021 }
3022 if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
3023 else { node.arguments = empty; }
3024 return this.finishNode(node, "NewExpression")
3025};
3026
3027// Parse template expression.
3028
3029pp$5.parseTemplateElement = function(ref) {
3030 var isTagged = ref.isTagged;
3031
3032 var elem = this.startNode();
3033 if (this.type === types$1.invalidTemplate) {
3034 if (!isTagged) {
3035 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
3036 }
3037 elem.value = {
3038 raw: this.value,
3039 cooked: null
3040 };
3041 } else {
3042 elem.value = {
3043 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
3044 cooked: this.value
3045 };
3046 }
3047 this.next();
3048 elem.tail = this.type === types$1.backQuote;
3049 return this.finishNode(elem, "TemplateElement")
3050};
3051
3052pp$5.parseTemplate = function(ref) {
3053 if ( ref === void 0 ) ref = {};
3054 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
3055
3056 var node = this.startNode();
3057 this.next();
3058 node.expressions = [];
3059 var curElt = this.parseTemplateElement({isTagged: isTagged});
3060 node.quasis = [curElt];
3061 while (!curElt.tail) {
3062 if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
3063 this.expect(types$1.dollarBraceL);
3064 node.expressions.push(this.parseExpression());
3065 this.expect(types$1.braceR);
3066 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
3067 }
3068 this.next();
3069 return this.finishNode(node, "TemplateLiteral")
3070};
3071
3072pp$5.isAsyncProp = function(prop) {
3073 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
3074 (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
3075 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
3076};
3077
3078// Parse an object literal or binding pattern.
3079
3080pp$5.parseObj = function(isPattern, refDestructuringErrors) {
3081 var node = this.startNode(), first = true, propHash = {};
3082 node.properties = [];
3083 this.next();
3084 while (!this.eat(types$1.braceR)) {
3085 if (!first) {
3086 this.expect(types$1.comma);
3087 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
3088 } else { first = false; }
3089
3090 var prop = this.parseProperty(isPattern, refDestructuringErrors);
3091 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
3092 node.properties.push(prop);
3093 }
3094 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
3095};
3096
3097pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
3098 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
3099 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
3100 if (isPattern) {
3101 prop.argument = this.parseIdent(false);
3102 if (this.type === types$1.comma) {
3103 this.raise(this.start, "Comma is not permitted after the rest element");
3104 }
3105 return this.finishNode(prop, "RestElement")
3106 }
3107 // Parse argument.
3108 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
3109 // To disallow trailing comma via `this.toAssignable()`.
3110 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
3111 refDestructuringErrors.trailingComma = this.start;
3112 }
3113 // Finish
3114 return this.finishNode(prop, "SpreadElement")
3115 }
3116 if (this.options.ecmaVersion >= 6) {
3117 prop.method = false;
3118 prop.shorthand = false;
3119 if (isPattern || refDestructuringErrors) {
3120 startPos = this.start;
3121 startLoc = this.startLoc;
3122 }
3123 if (!isPattern)
3124 { isGenerator = this.eat(types$1.star); }
3125 }
3126 var containsEsc = this.containsEsc;
3127 this.parsePropertyName(prop);
3128 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
3129 isAsync = true;
3130 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
3131 this.parsePropertyName(prop, refDestructuringErrors);
3132 } else {
3133 isAsync = false;
3134 }
3135 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
3136 return this.finishNode(prop, "Property")
3137};
3138
3139pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
3140 if ((isGenerator || isAsync) && this.type === types$1.colon)
3141 { this.unexpected(); }
3142
3143 if (this.eat(types$1.colon)) {
3144 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
3145 prop.kind = "init";
3146 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
3147 if (isPattern) { this.unexpected(); }
3148 prop.kind = "init";
3149 prop.method = true;
3150 prop.value = this.parseMethod(isGenerator, isAsync);
3151 } else if (!isPattern && !containsEsc &&
3152 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
3153 (prop.key.name === "get" || prop.key.name === "set") &&
3154 (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
3155 if (isGenerator || isAsync) { this.unexpected(); }
3156 prop.kind = prop.key.name;
3157 this.parsePropertyName(prop);
3158 prop.value = this.parseMethod(false);
3159 var paramCount = prop.kind === "get" ? 0 : 1;
3160 if (prop.value.params.length !== paramCount) {
3161 var start = prop.value.start;
3162 if (prop.kind === "get")
3163 { this.raiseRecoverable(start, "getter should have no params"); }
3164 else
3165 { this.raiseRecoverable(start, "setter should have exactly one param"); }
3166 } else {
3167 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
3168 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
3169 }
3170 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
3171 if (isGenerator || isAsync) { this.unexpected(); }
3172 this.checkUnreserved(prop.key);
3173 if (prop.key.name === "await" && !this.awaitIdentPos)
3174 { this.awaitIdentPos = startPos; }
3175 prop.kind = "init";
3176 if (isPattern) {
3177 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
3178 } else if (this.type === types$1.eq && refDestructuringErrors) {
3179 if (refDestructuringErrors.shorthandAssign < 0)
3180 { refDestructuringErrors.shorthandAssign = this.start; }
3181 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
3182 } else {
3183 prop.value = this.copyNode(prop.key);
3184 }
3185 prop.shorthand = true;
3186 } else { this.unexpected(); }
3187};
3188
3189pp$5.parsePropertyName = function(prop) {
3190 if (this.options.ecmaVersion >= 6) {
3191 if (this.eat(types$1.bracketL)) {
3192 prop.computed = true;
3193 prop.key = this.parseMaybeAssign();
3194 this.expect(types$1.bracketR);
3195 return prop.key
3196 } else {
3197 prop.computed = false;
3198 }
3199 }
3200 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
3201};
3202
3203// Initialize empty function node.
3204
3205pp$5.initFunction = function(node) {
3206 node.id = null;
3207 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
3208 if (this.options.ecmaVersion >= 8) { node.async = false; }
3209};
3210
3211// Parse object or class method.
3212
3213pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
3214 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
3215
3216 this.initFunction(node);
3217 if (this.options.ecmaVersion >= 6)
3218 { node.generator = isGenerator; }
3219 if (this.options.ecmaVersion >= 8)
3220 { node.async = !!isAsync; }
3221
3222 this.yieldPos = 0;
3223 this.awaitPos = 0;
3224 this.awaitIdentPos = 0;
3225 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
3226
3227 this.expect(types$1.parenL);
3228 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
3229 this.checkYieldAwaitInDefaultParams();
3230 this.parseFunctionBody(node, false, true, false);
3231
3232 this.yieldPos = oldYieldPos;
3233 this.awaitPos = oldAwaitPos;
3234 this.awaitIdentPos = oldAwaitIdentPos;
3235 return this.finishNode(node, "FunctionExpression")
3236};
3237
3238// Parse arrow function expression with given parameters.
3239
3240pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
3241 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
3242
3243 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
3244 this.initFunction(node);
3245 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
3246
3247 this.yieldPos = 0;
3248 this.awaitPos = 0;
3249 this.awaitIdentPos = 0;
3250
3251 node.params = this.toAssignableList(params, true);
3252 this.parseFunctionBody(node, true, false, forInit);
3253
3254 this.yieldPos = oldYieldPos;
3255 this.awaitPos = oldAwaitPos;
3256 this.awaitIdentPos = oldAwaitIdentPos;
3257 return this.finishNode(node, "ArrowFunctionExpression")
3258};
3259
3260// Parse function body and check parameters.
3261
3262pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
3263 var isExpression = isArrowFunction && this.type !== types$1.braceL;
3264 var oldStrict = this.strict, useStrict = false;
3265
3266 if (isExpression) {
3267 node.body = this.parseMaybeAssign(forInit);
3268 node.expression = true;
3269 this.checkParams(node, false);
3270 } else {
3271 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
3272 if (!oldStrict || nonSimple) {
3273 useStrict = this.strictDirective(this.end);
3274 // If this is a strict mode function, verify that argument names
3275 // are not repeated, and it does not try to bind the words `eval`
3276 // or `arguments`.
3277 if (useStrict && nonSimple)
3278 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
3279 }
3280 // Start a new scope with regard to labels and the `inFunction`
3281 // flag (restore them to their old value afterwards).
3282 var oldLabels = this.labels;
3283 this.labels = [];
3284 if (useStrict) { this.strict = true; }
3285
3286 // Add the params to varDeclaredNames to ensure that an error is thrown
3287 // if a let/const declaration in the function clashes with one of the params.
3288 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
3289 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
3290 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
3291 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
3292 node.expression = false;
3293 this.adaptDirectivePrologue(node.body.body);
3294 this.labels = oldLabels;
3295 }
3296 this.exitScope();
3297};
3298
3299pp$5.isSimpleParamList = function(params) {
3300 for (var i = 0, list = params; i < list.length; i += 1)
3301 {
3302 var param = list[i];
3303
3304 if (param.type !== "Identifier") { return false
3305 } }
3306 return true
3307};
3308
3309// Checks function params for various disallowed patterns such as using "eval"
3310// or "arguments" and duplicate parameters.
3311
3312pp$5.checkParams = function(node, allowDuplicates) {
3313 var nameHash = Object.create(null);
3314 for (var i = 0, list = node.params; i < list.length; i += 1)
3315 {
3316 var param = list[i];
3317
3318 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
3319 }
3320};
3321
3322// Parses a comma-separated list of expressions, and returns them as
3323// an array. `close` is the token type that ends the list, and
3324// `allowEmpty` can be turned on to allow subsequent commas with
3325// nothing in between them to be parsed as `null` (which is needed
3326// for array literals).
3327
3328pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
3329 var elts = [], first = true;
3330 while (!this.eat(close)) {
3331 if (!first) {
3332 this.expect(types$1.comma);
3333 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
3334 } else { first = false; }
3335
3336 var elt = (void 0);
3337 if (allowEmpty && this.type === types$1.comma)
3338 { elt = null; }
3339 else if (this.type === types$1.ellipsis) {
3340 elt = this.parseSpread(refDestructuringErrors);
3341 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
3342 { refDestructuringErrors.trailingComma = this.start; }
3343 } else {
3344 elt = this.parseMaybeAssign(false, refDestructuringErrors);
3345 }
3346 elts.push(elt);
3347 }
3348 return elts
3349};
3350
3351pp$5.checkUnreserved = function(ref) {
3352 var start = ref.start;
3353 var end = ref.end;
3354 var name = ref.name;
3355
3356 if (this.inGenerator && name === "yield")
3357 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
3358 if (this.inAsync && name === "await")
3359 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
3360 if (this.currentThisScope().inClassFieldInit && name === "arguments")
3361 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
3362 if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
3363 { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
3364 if (this.keywords.test(name))
3365 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
3366 if (this.options.ecmaVersion < 6 &&
3367 this.input.slice(start, end).indexOf("\\") !== -1) { return }
3368 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
3369 if (re.test(name)) {
3370 if (!this.inAsync && name === "await")
3371 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
3372 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
3373 }
3374};
3375
3376// Parse the next token as an identifier. If `liberal` is true (used
3377// when parsing properties), it will also convert keywords into
3378// identifiers.
3379
3380pp$5.parseIdent = function(liberal, isBinding) {
3381 var node = this.startNode();
3382 if (this.type === types$1.name) {
3383 node.name = this.value;
3384 } else if (this.type.keyword) {
3385 node.name = this.type.keyword;
3386
3387 // To fix https://github.com/acornjs/acorn/issues/575
3388 // `class` and `function` keywords push new context into this.context.
3389 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
3390 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
3391 if ((node.name === "class" || node.name === "function") &&
3392 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
3393 this.context.pop();
3394 }
3395 } else {
3396 this.unexpected();
3397 }
3398 this.next(!!liberal);
3399 this.finishNode(node, "Identifier");
3400 if (!liberal) {
3401 this.checkUnreserved(node);
3402 if (node.name === "await" && !this.awaitIdentPos)
3403 { this.awaitIdentPos = node.start; }
3404 }
3405 return node
3406};
3407
3408pp$5.parsePrivateIdent = function() {
3409 var node = this.startNode();
3410 if (this.type === types$1.privateId) {
3411 node.name = this.value;
3412 } else {
3413 this.unexpected();
3414 }
3415 this.next();
3416 this.finishNode(node, "PrivateIdentifier");
3417
3418 // For validating existence
3419 if (this.privateNameStack.length === 0) {
3420 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
3421 } else {
3422 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
3423 }
3424
3425 return node
3426};
3427
3428// Parses yield expression inside generator.
3429
3430pp$5.parseYield = function(forInit) {
3431 if (!this.yieldPos) { this.yieldPos = this.start; }
3432
3433 var node = this.startNode();
3434 this.next();
3435 if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
3436 node.delegate = false;
3437 node.argument = null;
3438 } else {
3439 node.delegate = this.eat(types$1.star);
3440 node.argument = this.parseMaybeAssign(forInit);
3441 }
3442 return this.finishNode(node, "YieldExpression")
3443};
3444
3445pp$5.parseAwait = function(forInit) {
3446 if (!this.awaitPos) { this.awaitPos = this.start; }
3447
3448 var node = this.startNode();
3449 this.next();
3450 node.argument = this.parseMaybeUnary(null, true, false, forInit);
3451 return this.finishNode(node, "AwaitExpression")
3452};
3453
3454var pp$4 = Parser.prototype;
3455
3456// This function is used to raise exceptions on parse errors. It
3457// takes an offset integer (into the current `input`) to indicate
3458// the location of the error, attaches the position to the end
3459// of the error message, and then raises a `SyntaxError` with that
3460// message.
3461
3462pp$4.raise = function(pos, message) {
3463 var loc = getLineInfo(this.input, pos);
3464 message += " (" + loc.line + ":" + loc.column + ")";
3465 var err = new SyntaxError(message);
3466 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
3467 throw err
3468};
3469
3470pp$4.raiseRecoverable = pp$4.raise;
3471
3472pp$4.curPosition = function() {
3473 if (this.options.locations) {
3474 return new Position(this.curLine, this.pos - this.lineStart)
3475 }
3476};
3477
3478var pp$3 = Parser.prototype;
3479
3480var Scope = function Scope(flags) {
3481 this.flags = flags;
3482 // A list of var-declared names in the current lexical scope
3483 this.var = [];
3484 // A list of lexically-declared names in the current lexical scope
3485 this.lexical = [];
3486 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
3487 this.functions = [];
3488 // A switch to disallow the identifier reference 'arguments'
3489 this.inClassFieldInit = false;
3490};
3491
3492// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
3493
3494pp$3.enterScope = function(flags) {
3495 this.scopeStack.push(new Scope(flags));
3496};
3497
3498pp$3.exitScope = function() {
3499 this.scopeStack.pop();
3500};
3501
3502// The spec says:
3503// > At the top level of a function, or script, function declarations are
3504// > treated like var declarations rather than like lexical declarations.
3505pp$3.treatFunctionsAsVarInScope = function(scope) {
3506 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
3507};
3508
3509pp$3.declareName = function(name, bindingType, pos) {
3510 var redeclared = false;
3511 if (bindingType === BIND_LEXICAL) {
3512 var scope = this.currentScope();
3513 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
3514 scope.lexical.push(name);
3515 if (this.inModule && (scope.flags & SCOPE_TOP))
3516 { delete this.undefinedExports[name]; }
3517 } else if (bindingType === BIND_SIMPLE_CATCH) {
3518 var scope$1 = this.currentScope();
3519 scope$1.lexical.push(name);
3520 } else if (bindingType === BIND_FUNCTION) {
3521 var scope$2 = this.currentScope();
3522 if (this.treatFunctionsAsVar)
3523 { redeclared = scope$2.lexical.indexOf(name) > -1; }
3524 else
3525 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
3526 scope$2.functions.push(name);
3527 } else {
3528 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
3529 var scope$3 = this.scopeStack[i];
3530 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
3531 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
3532 redeclared = true;
3533 break
3534 }
3535 scope$3.var.push(name);
3536 if (this.inModule && (scope$3.flags & SCOPE_TOP))
3537 { delete this.undefinedExports[name]; }
3538 if (scope$3.flags & SCOPE_VAR) { break }
3539 }
3540 }
3541 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
3542};
3543
3544pp$3.checkLocalExport = function(id) {
3545 // scope.functions must be empty as Module code is always strict.
3546 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
3547 this.scopeStack[0].var.indexOf(id.name) === -1) {
3548 this.undefinedExports[id.name] = id;
3549 }
3550};
3551
3552pp$3.currentScope = function() {
3553 return this.scopeStack[this.scopeStack.length - 1]
3554};
3555
3556pp$3.currentVarScope = function() {
3557 for (var i = this.scopeStack.length - 1;; i--) {
3558 var scope = this.scopeStack[i];
3559 if (scope.flags & SCOPE_VAR) { return scope }
3560 }
3561};
3562
3563// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
3564pp$3.currentThisScope = function() {
3565 for (var i = this.scopeStack.length - 1;; i--) {
3566 var scope = this.scopeStack[i];
3567 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
3568 }
3569};
3570
3571var Node = function Node(parser, pos, loc) {
3572 this.type = "";
3573 this.start = pos;
3574 this.end = 0;
3575 if (parser.options.locations)
3576 { this.loc = new SourceLocation(parser, loc); }
3577 if (parser.options.directSourceFile)
3578 { this.sourceFile = parser.options.directSourceFile; }
3579 if (parser.options.ranges)
3580 { this.range = [pos, 0]; }
3581};
3582
3583// Start an AST node, attaching a start offset.
3584
3585var pp$2 = Parser.prototype;
3586
3587pp$2.startNode = function() {
3588 return new Node(this, this.start, this.startLoc)
3589};
3590
3591pp$2.startNodeAt = function(pos, loc) {
3592 return new Node(this, pos, loc)
3593};
3594
3595// Finish an AST node, adding `type` and `end` properties.
3596
3597function finishNodeAt(node, type, pos, loc) {
3598 node.type = type;
3599 node.end = pos;
3600 if (this.options.locations)
3601 { node.loc.end = loc; }
3602 if (this.options.ranges)
3603 { node.range[1] = pos; }
3604 return node
3605}
3606
3607pp$2.finishNode = function(node, type) {
3608 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
3609};
3610
3611// Finish node at given position
3612
3613pp$2.finishNodeAt = function(node, type, pos, loc) {
3614 return finishNodeAt.call(this, node, type, pos, loc)
3615};
3616
3617pp$2.copyNode = function(node) {
3618 var newNode = new Node(this, node.start, this.startLoc);
3619 for (var prop in node) { newNode[prop] = node[prop]; }
3620 return newNode
3621};
3622
3623// This file contains Unicode properties extracted from the ECMAScript
3624// specification. The lists are extracted like so:
3625// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
3626
3627// #table-binary-unicode-properties
3628var 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";
3629var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
3630var ecma11BinaryProperties = ecma10BinaryProperties;
3631var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
3632var ecma13BinaryProperties = ecma12BinaryProperties;
3633var unicodeBinaryProperties = {
3634 9: ecma9BinaryProperties,
3635 10: ecma10BinaryProperties,
3636 11: ecma11BinaryProperties,
3637 12: ecma12BinaryProperties,
3638 13: ecma13BinaryProperties
3639};
3640
3641// #table-unicode-general-category-values
3642var 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";
3643
3644// #table-unicode-script-values
3645var ecma9ScriptValues = "Adlam Adlm 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 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";
3646var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
3647var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
3648var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
3649var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
3650var unicodeScriptValues = {
3651 9: ecma9ScriptValues,
3652 10: ecma10ScriptValues,
3653 11: ecma11ScriptValues,
3654 12: ecma12ScriptValues,
3655 13: ecma13ScriptValues
3656};
3657
3658var data = {};
3659function buildUnicodeData(ecmaVersion) {
3660 var d = data[ecmaVersion] = {
3661 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
3662 nonBinary: {
3663 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
3664 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
3665 }
3666 };
3667 d.nonBinary.Script_Extensions = d.nonBinary.Script;
3668
3669 d.nonBinary.gc = d.nonBinary.General_Category;
3670 d.nonBinary.sc = d.nonBinary.Script;
3671 d.nonBinary.scx = d.nonBinary.Script_Extensions;
3672}
3673
3674for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
3675 var ecmaVersion = list[i];
3676
3677 buildUnicodeData(ecmaVersion);
3678}
3679
3680var pp$1 = Parser.prototype;
3681
3682var RegExpValidationState = function RegExpValidationState(parser) {
3683 this.parser = parser;
3684 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
3685 this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
3686 this.source = "";
3687 this.flags = "";
3688 this.start = 0;
3689 this.switchU = false;
3690 this.switchN = false;
3691 this.pos = 0;
3692 this.lastIntValue = 0;
3693 this.lastStringValue = "";
3694 this.lastAssertionIsQuantifiable = false;
3695 this.numCapturingParens = 0;
3696 this.maxBackReference = 0;
3697 this.groupNames = [];
3698 this.backReferenceNames = [];
3699};
3700
3701RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
3702 var unicode = flags.indexOf("u") !== -1;
3703 this.start = start | 0;
3704 this.source = pattern + "";
3705 this.flags = flags;
3706 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
3707 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
3708};
3709
3710RegExpValidationState.prototype.raise = function raise (message) {
3711 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
3712};
3713
3714// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
3715// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
3716RegExpValidationState.prototype.at = function at (i, forceU) {
3717 if ( forceU === void 0 ) forceU = false;
3718
3719 var s = this.source;
3720 var l = s.length;
3721 if (i >= l) {
3722 return -1
3723 }
3724 var c = s.charCodeAt(i);
3725 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
3726 return c
3727 }
3728 var next = s.charCodeAt(i + 1);
3729 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
3730};
3731
3732RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
3733 if ( forceU === void 0 ) forceU = false;
3734
3735 var s = this.source;
3736 var l = s.length;
3737 if (i >= l) {
3738 return l
3739 }
3740 var c = s.charCodeAt(i), next;
3741 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
3742 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
3743 return i + 1
3744 }
3745 return i + 2
3746};
3747
3748RegExpValidationState.prototype.current = function current (forceU) {
3749 if ( forceU === void 0 ) forceU = false;
3750
3751 return this.at(this.pos, forceU)
3752};
3753
3754RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
3755 if ( forceU === void 0 ) forceU = false;
3756
3757 return this.at(this.nextIndex(this.pos, forceU), forceU)
3758};
3759
3760RegExpValidationState.prototype.advance = function advance (forceU) {
3761 if ( forceU === void 0 ) forceU = false;
3762
3763 this.pos = this.nextIndex(this.pos, forceU);
3764};
3765
3766RegExpValidationState.prototype.eat = function eat (ch, forceU) {
3767 if ( forceU === void 0 ) forceU = false;
3768
3769 if (this.current(forceU) === ch) {
3770 this.advance(forceU);
3771 return true
3772 }
3773 return false
3774};
3775
3776/**
3777 * Validate the flags part of a given RegExpLiteral.
3778 *
3779 * @param {RegExpValidationState} state The state to validate RegExp.
3780 * @returns {void}
3781 */
3782pp$1.validateRegExpFlags = function(state) {
3783 var validFlags = state.validFlags;
3784 var flags = state.flags;
3785
3786 for (var i = 0; i < flags.length; i++) {
3787 var flag = flags.charAt(i);
3788 if (validFlags.indexOf(flag) === -1) {
3789 this.raise(state.start, "Invalid regular expression flag");
3790 }
3791 if (flags.indexOf(flag, i + 1) > -1) {
3792 this.raise(state.start, "Duplicate regular expression flag");
3793 }
3794 }
3795};
3796
3797/**
3798 * Validate the pattern part of a given RegExpLiteral.
3799 *
3800 * @param {RegExpValidationState} state The state to validate RegExp.
3801 * @returns {void}
3802 */
3803pp$1.validateRegExpPattern = function(state) {
3804 this.regexp_pattern(state);
3805
3806 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
3807 // parsing contains a |GroupName|, reparse with the goal symbol
3808 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
3809 // exception if _P_ did not conform to the grammar, if any elements of _P_
3810 // were not matched by the parse, or if any Early Error conditions exist.
3811 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
3812 state.switchN = true;
3813 this.regexp_pattern(state);
3814 }
3815};
3816
3817// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
3818pp$1.regexp_pattern = function(state) {
3819 state.pos = 0;
3820 state.lastIntValue = 0;
3821 state.lastStringValue = "";
3822 state.lastAssertionIsQuantifiable = false;
3823 state.numCapturingParens = 0;
3824 state.maxBackReference = 0;
3825 state.groupNames.length = 0;
3826 state.backReferenceNames.length = 0;
3827
3828 this.regexp_disjunction(state);
3829
3830 if (state.pos !== state.source.length) {
3831 // Make the same messages as V8.
3832 if (state.eat(0x29 /* ) */)) {
3833 state.raise("Unmatched ')'");
3834 }
3835 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
3836 state.raise("Lone quantifier brackets");
3837 }
3838 }
3839 if (state.maxBackReference > state.numCapturingParens) {
3840 state.raise("Invalid escape");
3841 }
3842 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
3843 var name = list[i];
3844
3845 if (state.groupNames.indexOf(name) === -1) {
3846 state.raise("Invalid named capture referenced");
3847 }
3848 }
3849};
3850
3851// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
3852pp$1.regexp_disjunction = function(state) {
3853 this.regexp_alternative(state);
3854 while (state.eat(0x7C /* | */)) {
3855 this.regexp_alternative(state);
3856 }
3857
3858 // Make the same message as V8.
3859 if (this.regexp_eatQuantifier(state, true)) {
3860 state.raise("Nothing to repeat");
3861 }
3862 if (state.eat(0x7B /* { */)) {
3863 state.raise("Lone quantifier brackets");
3864 }
3865};
3866
3867// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
3868pp$1.regexp_alternative = function(state) {
3869 while (state.pos < state.source.length && this.regexp_eatTerm(state))
3870 { }
3871};
3872
3873// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
3874pp$1.regexp_eatTerm = function(state) {
3875 if (this.regexp_eatAssertion(state)) {
3876 // Handle `QuantifiableAssertion Quantifier` alternative.
3877 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
3878 // is a QuantifiableAssertion.
3879 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
3880 // Make the same message as V8.
3881 if (state.switchU) {
3882 state.raise("Invalid quantifier");
3883 }
3884 }
3885 return true
3886 }
3887
3888 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
3889 this.regexp_eatQuantifier(state);
3890 return true
3891 }
3892
3893 return false
3894};
3895
3896// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
3897pp$1.regexp_eatAssertion = function(state) {
3898 var start = state.pos;
3899 state.lastAssertionIsQuantifiable = false;
3900
3901 // ^, $
3902 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
3903 return true
3904 }
3905
3906 // \b \B
3907 if (state.eat(0x5C /* \ */)) {
3908 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
3909 return true
3910 }
3911 state.pos = start;
3912 }
3913
3914 // Lookahead / Lookbehind
3915 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
3916 var lookbehind = false;
3917 if (this.options.ecmaVersion >= 9) {
3918 lookbehind = state.eat(0x3C /* < */);
3919 }
3920 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
3921 this.regexp_disjunction(state);
3922 if (!state.eat(0x29 /* ) */)) {
3923 state.raise("Unterminated group");
3924 }
3925 state.lastAssertionIsQuantifiable = !lookbehind;
3926 return true
3927 }
3928 }
3929
3930 state.pos = start;
3931 return false
3932};
3933
3934// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
3935pp$1.regexp_eatQuantifier = function(state, noError) {
3936 if ( noError === void 0 ) noError = false;
3937
3938 if (this.regexp_eatQuantifierPrefix(state, noError)) {
3939 state.eat(0x3F /* ? */);
3940 return true
3941 }
3942 return false
3943};
3944
3945// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
3946pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
3947 return (
3948 state.eat(0x2A /* * */) ||
3949 state.eat(0x2B /* + */) ||
3950 state.eat(0x3F /* ? */) ||
3951 this.regexp_eatBracedQuantifier(state, noError)
3952 )
3953};
3954pp$1.regexp_eatBracedQuantifier = function(state, noError) {
3955 var start = state.pos;
3956 if (state.eat(0x7B /* { */)) {
3957 var min = 0, max = -1;
3958 if (this.regexp_eatDecimalDigits(state)) {
3959 min = state.lastIntValue;
3960 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
3961 max = state.lastIntValue;
3962 }
3963 if (state.eat(0x7D /* } */)) {
3964 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
3965 if (max !== -1 && max < min && !noError) {
3966 state.raise("numbers out of order in {} quantifier");
3967 }
3968 return true
3969 }
3970 }
3971 if (state.switchU && !noError) {
3972 state.raise("Incomplete quantifier");
3973 }
3974 state.pos = start;
3975 }
3976 return false
3977};
3978
3979// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
3980pp$1.regexp_eatAtom = function(state) {
3981 return (
3982 this.regexp_eatPatternCharacters(state) ||
3983 state.eat(0x2E /* . */) ||
3984 this.regexp_eatReverseSolidusAtomEscape(state) ||
3985 this.regexp_eatCharacterClass(state) ||
3986 this.regexp_eatUncapturingGroup(state) ||
3987 this.regexp_eatCapturingGroup(state)
3988 )
3989};
3990pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
3991 var start = state.pos;
3992 if (state.eat(0x5C /* \ */)) {
3993 if (this.regexp_eatAtomEscape(state)) {
3994 return true
3995 }
3996 state.pos = start;
3997 }
3998 return false
3999};
4000pp$1.regexp_eatUncapturingGroup = function(state) {
4001 var start = state.pos;
4002 if (state.eat(0x28 /* ( */)) {
4003 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
4004 this.regexp_disjunction(state);
4005 if (state.eat(0x29 /* ) */)) {
4006 return true
4007 }
4008 state.raise("Unterminated group");
4009 }
4010 state.pos = start;
4011 }
4012 return false
4013};
4014pp$1.regexp_eatCapturingGroup = function(state) {
4015 if (state.eat(0x28 /* ( */)) {
4016 if (this.options.ecmaVersion >= 9) {
4017 this.regexp_groupSpecifier(state);
4018 } else if (state.current() === 0x3F /* ? */) {
4019 state.raise("Invalid group");
4020 }
4021 this.regexp_disjunction(state);
4022 if (state.eat(0x29 /* ) */)) {
4023 state.numCapturingParens += 1;
4024 return true
4025 }
4026 state.raise("Unterminated group");
4027 }
4028 return false
4029};
4030
4031// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
4032pp$1.regexp_eatExtendedAtom = function(state) {
4033 return (
4034 state.eat(0x2E /* . */) ||
4035 this.regexp_eatReverseSolidusAtomEscape(state) ||
4036 this.regexp_eatCharacterClass(state) ||
4037 this.regexp_eatUncapturingGroup(state) ||
4038 this.regexp_eatCapturingGroup(state) ||
4039 this.regexp_eatInvalidBracedQuantifier(state) ||
4040 this.regexp_eatExtendedPatternCharacter(state)
4041 )
4042};
4043
4044// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
4045pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
4046 if (this.regexp_eatBracedQuantifier(state, true)) {
4047 state.raise("Nothing to repeat");
4048 }
4049 return false
4050};
4051
4052// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
4053pp$1.regexp_eatSyntaxCharacter = function(state) {
4054 var ch = state.current();
4055 if (isSyntaxCharacter(ch)) {
4056 state.lastIntValue = ch;
4057 state.advance();
4058 return true
4059 }
4060 return false
4061};
4062function isSyntaxCharacter(ch) {
4063 return (
4064 ch === 0x24 /* $ */ ||
4065 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
4066 ch === 0x2E /* . */ ||
4067 ch === 0x3F /* ? */ ||
4068 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
4069 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
4070 )
4071}
4072
4073// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
4074// But eat eager.
4075pp$1.regexp_eatPatternCharacters = function(state) {
4076 var start = state.pos;
4077 var ch = 0;
4078 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
4079 state.advance();
4080 }
4081 return state.pos !== start
4082};
4083
4084// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
4085pp$1.regexp_eatExtendedPatternCharacter = function(state) {
4086 var ch = state.current();
4087 if (
4088 ch !== -1 &&
4089 ch !== 0x24 /* $ */ &&
4090 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
4091 ch !== 0x2E /* . */ &&
4092 ch !== 0x3F /* ? */ &&
4093 ch !== 0x5B /* [ */ &&
4094 ch !== 0x5E /* ^ */ &&
4095 ch !== 0x7C /* | */
4096 ) {
4097 state.advance();
4098 return true
4099 }
4100 return false
4101};
4102
4103// GroupSpecifier ::
4104// [empty]
4105// `?` GroupName
4106pp$1.regexp_groupSpecifier = function(state) {
4107 if (state.eat(0x3F /* ? */)) {
4108 if (this.regexp_eatGroupName(state)) {
4109 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
4110 state.raise("Duplicate capture group name");
4111 }
4112 state.groupNames.push(state.lastStringValue);
4113 return
4114 }
4115 state.raise("Invalid group");
4116 }
4117};
4118
4119// GroupName ::
4120// `<` RegExpIdentifierName `>`
4121// Note: this updates `state.lastStringValue` property with the eaten name.
4122pp$1.regexp_eatGroupName = function(state) {
4123 state.lastStringValue = "";
4124 if (state.eat(0x3C /* < */)) {
4125 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
4126 return true
4127 }
4128 state.raise("Invalid capture group name");
4129 }
4130 return false
4131};
4132
4133// RegExpIdentifierName ::
4134// RegExpIdentifierStart
4135// RegExpIdentifierName RegExpIdentifierPart
4136// Note: this updates `state.lastStringValue` property with the eaten name.
4137pp$1.regexp_eatRegExpIdentifierName = function(state) {
4138 state.lastStringValue = "";
4139 if (this.regexp_eatRegExpIdentifierStart(state)) {
4140 state.lastStringValue += codePointToString(state.lastIntValue);
4141 while (this.regexp_eatRegExpIdentifierPart(state)) {
4142 state.lastStringValue += codePointToString(state.lastIntValue);
4143 }
4144 return true
4145 }
4146 return false
4147};
4148
4149// RegExpIdentifierStart ::
4150// UnicodeIDStart
4151// `$`
4152// `_`
4153// `\` RegExpUnicodeEscapeSequence[+U]
4154pp$1.regexp_eatRegExpIdentifierStart = function(state) {
4155 var start = state.pos;
4156 var forceU = this.options.ecmaVersion >= 11;
4157 var ch = state.current(forceU);
4158 state.advance(forceU);
4159
4160 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
4161 ch = state.lastIntValue;
4162 }
4163 if (isRegExpIdentifierStart(ch)) {
4164 state.lastIntValue = ch;
4165 return true
4166 }
4167
4168 state.pos = start;
4169 return false
4170};
4171function isRegExpIdentifierStart(ch) {
4172 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
4173}
4174
4175// RegExpIdentifierPart ::
4176// UnicodeIDContinue
4177// `$`
4178// `_`
4179// `\` RegExpUnicodeEscapeSequence[+U]
4180// <ZWNJ>
4181// <ZWJ>
4182pp$1.regexp_eatRegExpIdentifierPart = function(state) {
4183 var start = state.pos;
4184 var forceU = this.options.ecmaVersion >= 11;
4185 var ch = state.current(forceU);
4186 state.advance(forceU);
4187
4188 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
4189 ch = state.lastIntValue;
4190 }
4191 if (isRegExpIdentifierPart(ch)) {
4192 state.lastIntValue = ch;
4193 return true
4194 }
4195
4196 state.pos = start;
4197 return false
4198};
4199function isRegExpIdentifierPart(ch) {
4200 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
4201}
4202
4203// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
4204pp$1.regexp_eatAtomEscape = function(state) {
4205 if (
4206 this.regexp_eatBackReference(state) ||
4207 this.regexp_eatCharacterClassEscape(state) ||
4208 this.regexp_eatCharacterEscape(state) ||
4209 (state.switchN && this.regexp_eatKGroupName(state))
4210 ) {
4211 return true
4212 }
4213 if (state.switchU) {
4214 // Make the same message as V8.
4215 if (state.current() === 0x63 /* c */) {
4216 state.raise("Invalid unicode escape");
4217 }
4218 state.raise("Invalid escape");
4219 }
4220 return false
4221};
4222pp$1.regexp_eatBackReference = function(state) {
4223 var start = state.pos;
4224 if (this.regexp_eatDecimalEscape(state)) {
4225 var n = state.lastIntValue;
4226 if (state.switchU) {
4227 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
4228 if (n > state.maxBackReference) {
4229 state.maxBackReference = n;
4230 }
4231 return true
4232 }
4233 if (n <= state.numCapturingParens) {
4234 return true
4235 }
4236 state.pos = start;
4237 }
4238 return false
4239};
4240pp$1.regexp_eatKGroupName = function(state) {
4241 if (state.eat(0x6B /* k */)) {
4242 if (this.regexp_eatGroupName(state)) {
4243 state.backReferenceNames.push(state.lastStringValue);
4244 return true
4245 }
4246 state.raise("Invalid named reference");
4247 }
4248 return false
4249};
4250
4251// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
4252pp$1.regexp_eatCharacterEscape = function(state) {
4253 return (
4254 this.regexp_eatControlEscape(state) ||
4255 this.regexp_eatCControlLetter(state) ||
4256 this.regexp_eatZero(state) ||
4257 this.regexp_eatHexEscapeSequence(state) ||
4258 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
4259 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
4260 this.regexp_eatIdentityEscape(state)
4261 )
4262};
4263pp$1.regexp_eatCControlLetter = function(state) {
4264 var start = state.pos;
4265 if (state.eat(0x63 /* c */)) {
4266 if (this.regexp_eatControlLetter(state)) {
4267 return true
4268 }
4269 state.pos = start;
4270 }
4271 return false
4272};
4273pp$1.regexp_eatZero = function(state) {
4274 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
4275 state.lastIntValue = 0;
4276 state.advance();
4277 return true
4278 }
4279 return false
4280};
4281
4282// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
4283pp$1.regexp_eatControlEscape = function(state) {
4284 var ch = state.current();
4285 if (ch === 0x74 /* t */) {
4286 state.lastIntValue = 0x09; /* \t */
4287 state.advance();
4288 return true
4289 }
4290 if (ch === 0x6E /* n */) {
4291 state.lastIntValue = 0x0A; /* \n */
4292 state.advance();
4293 return true
4294 }
4295 if (ch === 0x76 /* v */) {
4296 state.lastIntValue = 0x0B; /* \v */
4297 state.advance();
4298 return true
4299 }
4300 if (ch === 0x66 /* f */) {
4301 state.lastIntValue = 0x0C; /* \f */
4302 state.advance();
4303 return true
4304 }
4305 if (ch === 0x72 /* r */) {
4306 state.lastIntValue = 0x0D; /* \r */
4307 state.advance();
4308 return true
4309 }
4310 return false
4311};
4312
4313// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
4314pp$1.regexp_eatControlLetter = function(state) {
4315 var ch = state.current();
4316 if (isControlLetter(ch)) {
4317 state.lastIntValue = ch % 0x20;
4318 state.advance();
4319 return true
4320 }
4321 return false
4322};
4323function isControlLetter(ch) {
4324 return (
4325 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
4326 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
4327 )
4328}
4329
4330// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
4331pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
4332 if ( forceU === void 0 ) forceU = false;
4333
4334 var start = state.pos;
4335 var switchU = forceU || state.switchU;
4336
4337 if (state.eat(0x75 /* u */)) {
4338 if (this.regexp_eatFixedHexDigits(state, 4)) {
4339 var lead = state.lastIntValue;
4340 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
4341 var leadSurrogateEnd = state.pos;
4342 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
4343 var trail = state.lastIntValue;
4344 if (trail >= 0xDC00 && trail <= 0xDFFF) {
4345 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
4346 return true
4347 }
4348 }
4349 state.pos = leadSurrogateEnd;
4350 state.lastIntValue = lead;
4351 }
4352 return true
4353 }
4354 if (
4355 switchU &&
4356 state.eat(0x7B /* { */) &&
4357 this.regexp_eatHexDigits(state) &&
4358 state.eat(0x7D /* } */) &&
4359 isValidUnicode(state.lastIntValue)
4360 ) {
4361 return true
4362 }
4363 if (switchU) {
4364 state.raise("Invalid unicode escape");
4365 }
4366 state.pos = start;
4367 }
4368
4369 return false
4370};
4371function isValidUnicode(ch) {
4372 return ch >= 0 && ch <= 0x10FFFF
4373}
4374
4375// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
4376pp$1.regexp_eatIdentityEscape = function(state) {
4377 if (state.switchU) {
4378 if (this.regexp_eatSyntaxCharacter(state)) {
4379 return true
4380 }
4381 if (state.eat(0x2F /* / */)) {
4382 state.lastIntValue = 0x2F; /* / */
4383 return true
4384 }
4385 return false
4386 }
4387
4388 var ch = state.current();
4389 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
4390 state.lastIntValue = ch;
4391 state.advance();
4392 return true
4393 }
4394
4395 return false
4396};
4397
4398// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
4399pp$1.regexp_eatDecimalEscape = function(state) {
4400 state.lastIntValue = 0;
4401 var ch = state.current();
4402 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
4403 do {
4404 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
4405 state.advance();
4406 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
4407 return true
4408 }
4409 return false
4410};
4411
4412// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
4413pp$1.regexp_eatCharacterClassEscape = function(state) {
4414 var ch = state.current();
4415
4416 if (isCharacterClassEscape(ch)) {
4417 state.lastIntValue = -1;
4418 state.advance();
4419 return true
4420 }
4421
4422 if (
4423 state.switchU &&
4424 this.options.ecmaVersion >= 9 &&
4425 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
4426 ) {
4427 state.lastIntValue = -1;
4428 state.advance();
4429 if (
4430 state.eat(0x7B /* { */) &&
4431 this.regexp_eatUnicodePropertyValueExpression(state) &&
4432 state.eat(0x7D /* } */)
4433 ) {
4434 return true
4435 }
4436 state.raise("Invalid property name");
4437 }
4438
4439 return false
4440};
4441function isCharacterClassEscape(ch) {
4442 return (
4443 ch === 0x64 /* d */ ||
4444 ch === 0x44 /* D */ ||
4445 ch === 0x73 /* s */ ||
4446 ch === 0x53 /* S */ ||
4447 ch === 0x77 /* w */ ||
4448 ch === 0x57 /* W */
4449 )
4450}
4451
4452// UnicodePropertyValueExpression ::
4453// UnicodePropertyName `=` UnicodePropertyValue
4454// LoneUnicodePropertyNameOrValue
4455pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
4456 var start = state.pos;
4457
4458 // UnicodePropertyName `=` UnicodePropertyValue
4459 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
4460 var name = state.lastStringValue;
4461 if (this.regexp_eatUnicodePropertyValue(state)) {
4462 var value = state.lastStringValue;
4463 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
4464 return true
4465 }
4466 }
4467 state.pos = start;
4468
4469 // LoneUnicodePropertyNameOrValue
4470 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
4471 var nameOrValue = state.lastStringValue;
4472 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
4473 return true
4474 }
4475 return false
4476};
4477pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
4478 if (!hasOwn(state.unicodeProperties.nonBinary, name))
4479 { state.raise("Invalid property name"); }
4480 if (!state.unicodeProperties.nonBinary[name].test(value))
4481 { state.raise("Invalid property value"); }
4482};
4483pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
4484 if (!state.unicodeProperties.binary.test(nameOrValue))
4485 { state.raise("Invalid property name"); }
4486};
4487
4488// UnicodePropertyName ::
4489// UnicodePropertyNameCharacters
4490pp$1.regexp_eatUnicodePropertyName = function(state) {
4491 var ch = 0;
4492 state.lastStringValue = "";
4493 while (isUnicodePropertyNameCharacter(ch = state.current())) {
4494 state.lastStringValue += codePointToString(ch);
4495 state.advance();
4496 }
4497 return state.lastStringValue !== ""
4498};
4499function isUnicodePropertyNameCharacter(ch) {
4500 return isControlLetter(ch) || ch === 0x5F /* _ */
4501}
4502
4503// UnicodePropertyValue ::
4504// UnicodePropertyValueCharacters
4505pp$1.regexp_eatUnicodePropertyValue = function(state) {
4506 var ch = 0;
4507 state.lastStringValue = "";
4508 while (isUnicodePropertyValueCharacter(ch = state.current())) {
4509 state.lastStringValue += codePointToString(ch);
4510 state.advance();
4511 }
4512 return state.lastStringValue !== ""
4513};
4514function isUnicodePropertyValueCharacter(ch) {
4515 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
4516}
4517
4518// LoneUnicodePropertyNameOrValue ::
4519// UnicodePropertyValueCharacters
4520pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
4521 return this.regexp_eatUnicodePropertyValue(state)
4522};
4523
4524// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
4525pp$1.regexp_eatCharacterClass = function(state) {
4526 if (state.eat(0x5B /* [ */)) {
4527 state.eat(0x5E /* ^ */);
4528 this.regexp_classRanges(state);
4529 if (state.eat(0x5D /* ] */)) {
4530 return true
4531 }
4532 // Unreachable since it threw "unterminated regular expression" error before.
4533 state.raise("Unterminated character class");
4534 }
4535 return false
4536};
4537
4538// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
4539// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
4540// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
4541pp$1.regexp_classRanges = function(state) {
4542 while (this.regexp_eatClassAtom(state)) {
4543 var left = state.lastIntValue;
4544 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
4545 var right = state.lastIntValue;
4546 if (state.switchU && (left === -1 || right === -1)) {
4547 state.raise("Invalid character class");
4548 }
4549 if (left !== -1 && right !== -1 && left > right) {
4550 state.raise("Range out of order in character class");
4551 }
4552 }
4553 }
4554};
4555
4556// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
4557// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
4558pp$1.regexp_eatClassAtom = function(state) {
4559 var start = state.pos;
4560
4561 if (state.eat(0x5C /* \ */)) {
4562 if (this.regexp_eatClassEscape(state)) {
4563 return true
4564 }
4565 if (state.switchU) {
4566 // Make the same message as V8.
4567 var ch$1 = state.current();
4568 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
4569 state.raise("Invalid class escape");
4570 }
4571 state.raise("Invalid escape");
4572 }
4573 state.pos = start;
4574 }
4575
4576 var ch = state.current();
4577 if (ch !== 0x5D /* ] */) {
4578 state.lastIntValue = ch;
4579 state.advance();
4580 return true
4581 }
4582
4583 return false
4584};
4585
4586// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
4587pp$1.regexp_eatClassEscape = function(state) {
4588 var start = state.pos;
4589
4590 if (state.eat(0x62 /* b */)) {
4591 state.lastIntValue = 0x08; /* <BS> */
4592 return true
4593 }
4594
4595 if (state.switchU && state.eat(0x2D /* - */)) {
4596 state.lastIntValue = 0x2D; /* - */
4597 return true
4598 }
4599
4600 if (!state.switchU && state.eat(0x63 /* c */)) {
4601 if (this.regexp_eatClassControlLetter(state)) {
4602 return true
4603 }
4604 state.pos = start;
4605 }
4606
4607 return (
4608 this.regexp_eatCharacterClassEscape(state) ||
4609 this.regexp_eatCharacterEscape(state)
4610 )
4611};
4612
4613// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
4614pp$1.regexp_eatClassControlLetter = function(state) {
4615 var ch = state.current();
4616 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
4617 state.lastIntValue = ch % 0x20;
4618 state.advance();
4619 return true
4620 }
4621 return false
4622};
4623
4624// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
4625pp$1.regexp_eatHexEscapeSequence = function(state) {
4626 var start = state.pos;
4627 if (state.eat(0x78 /* x */)) {
4628 if (this.regexp_eatFixedHexDigits(state, 2)) {
4629 return true
4630 }
4631 if (state.switchU) {
4632 state.raise("Invalid escape");
4633 }
4634 state.pos = start;
4635 }
4636 return false
4637};
4638
4639// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
4640pp$1.regexp_eatDecimalDigits = function(state) {
4641 var start = state.pos;
4642 var ch = 0;
4643 state.lastIntValue = 0;
4644 while (isDecimalDigit(ch = state.current())) {
4645 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
4646 state.advance();
4647 }
4648 return state.pos !== start
4649};
4650function isDecimalDigit(ch) {
4651 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
4652}
4653
4654// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
4655pp$1.regexp_eatHexDigits = function(state) {
4656 var start = state.pos;
4657 var ch = 0;
4658 state.lastIntValue = 0;
4659 while (isHexDigit(ch = state.current())) {
4660 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
4661 state.advance();
4662 }
4663 return state.pos !== start
4664};
4665function isHexDigit(ch) {
4666 return (
4667 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
4668 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
4669 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
4670 )
4671}
4672function hexToInt(ch) {
4673 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
4674 return 10 + (ch - 0x41 /* A */)
4675 }
4676 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
4677 return 10 + (ch - 0x61 /* a */)
4678 }
4679 return ch - 0x30 /* 0 */
4680}
4681
4682// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
4683// Allows only 0-377(octal) i.e. 0-255(decimal).
4684pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
4685 if (this.regexp_eatOctalDigit(state)) {
4686 var n1 = state.lastIntValue;
4687 if (this.regexp_eatOctalDigit(state)) {
4688 var n2 = state.lastIntValue;
4689 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
4690 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
4691 } else {
4692 state.lastIntValue = n1 * 8 + n2;
4693 }
4694 } else {
4695 state.lastIntValue = n1;
4696 }
4697 return true
4698 }
4699 return false
4700};
4701
4702// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
4703pp$1.regexp_eatOctalDigit = function(state) {
4704 var ch = state.current();
4705 if (isOctalDigit(ch)) {
4706 state.lastIntValue = ch - 0x30; /* 0 */
4707 state.advance();
4708 return true
4709 }
4710 state.lastIntValue = 0;
4711 return false
4712};
4713function isOctalDigit(ch) {
4714 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
4715}
4716
4717// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
4718// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
4719// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
4720pp$1.regexp_eatFixedHexDigits = function(state, length) {
4721 var start = state.pos;
4722 state.lastIntValue = 0;
4723 for (var i = 0; i < length; ++i) {
4724 var ch = state.current();
4725 if (!isHexDigit(ch)) {
4726 state.pos = start;
4727 return false
4728 }
4729 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
4730 state.advance();
4731 }
4732 return true
4733};
4734
4735// Object type used to represent tokens. Note that normally, tokens
4736// simply exist as properties on the parser object. This is only
4737// used for the onToken callback and the external tokenizer.
4738
4739var Token = function Token(p) {
4740 this.type = p.type;
4741 this.value = p.value;
4742 this.start = p.start;
4743 this.end = p.end;
4744 if (p.options.locations)
4745 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
4746 if (p.options.ranges)
4747 { this.range = [p.start, p.end]; }
4748};
4749
4750// ## Tokenizer
4751
4752var pp = Parser.prototype;
4753
4754// Move to the next token
4755
4756pp.next = function(ignoreEscapeSequenceInKeyword) {
4757 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
4758 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
4759 if (this.options.onToken)
4760 { this.options.onToken(new Token(this)); }
4761
4762 this.lastTokEnd = this.end;
4763 this.lastTokStart = this.start;
4764 this.lastTokEndLoc = this.endLoc;
4765 this.lastTokStartLoc = this.startLoc;
4766 this.nextToken();
4767};
4768
4769pp.getToken = function() {
4770 this.next();
4771 return new Token(this)
4772};
4773
4774// If we're in an ES6 environment, make parsers iterable
4775if (typeof Symbol !== "undefined")
4776 { pp[Symbol.iterator] = function() {
4777 var this$1$1 = this;
4778
4779 return {
4780 next: function () {
4781 var token = this$1$1.getToken();
4782 return {
4783 done: token.type === types$1.eof,
4784 value: token
4785 }
4786 }
4787 }
4788 }; }
4789
4790// Toggle strict mode. Re-reads the next number or string to please
4791// pedantic tests (`"use strict"; 010;` should fail).
4792
4793// Read a single token, updating the parser object's token-related
4794// properties.
4795
4796pp.nextToken = function() {
4797 var curContext = this.curContext();
4798 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
4799
4800 this.start = this.pos;
4801 if (this.options.locations) { this.startLoc = this.curPosition(); }
4802 if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
4803
4804 if (curContext.override) { return curContext.override(this) }
4805 else { this.readToken(this.fullCharCodeAtPos()); }
4806};
4807
4808pp.readToken = function(code) {
4809 // Identifier or keyword. '\uXXXX' sequences are allowed in
4810 // identifiers, so '\' also dispatches to that.
4811 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
4812 { return this.readWord() }
4813
4814 return this.getTokenFromCode(code)
4815};
4816
4817pp.fullCharCodeAtPos = function() {
4818 var code = this.input.charCodeAt(this.pos);
4819 if (code <= 0xd7ff || code >= 0xdc00) { return code }
4820 var next = this.input.charCodeAt(this.pos + 1);
4821 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
4822};
4823
4824pp.skipBlockComment = function() {
4825 var startLoc = this.options.onComment && this.curPosition();
4826 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
4827 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
4828 this.pos = end + 2;
4829 if (this.options.locations) {
4830 for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
4831 ++this.curLine;
4832 pos = this.lineStart = nextBreak;
4833 }
4834 }
4835 if (this.options.onComment)
4836 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
4837 startLoc, this.curPosition()); }
4838};
4839
4840pp.skipLineComment = function(startSkip) {
4841 var start = this.pos;
4842 var startLoc = this.options.onComment && this.curPosition();
4843 var ch = this.input.charCodeAt(this.pos += startSkip);
4844 while (this.pos < this.input.length && !isNewLine(ch)) {
4845 ch = this.input.charCodeAt(++this.pos);
4846 }
4847 if (this.options.onComment)
4848 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
4849 startLoc, this.curPosition()); }
4850};
4851
4852// Called at the start of the parse and after every token. Skips
4853// whitespace and comments, and.
4854
4855pp.skipSpace = function() {
4856 loop: while (this.pos < this.input.length) {
4857 var ch = this.input.charCodeAt(this.pos);
4858 switch (ch) {
4859 case 32: case 160: // ' '
4860 ++this.pos;
4861 break
4862 case 13:
4863 if (this.input.charCodeAt(this.pos + 1) === 10) {
4864 ++this.pos;
4865 }
4866 case 10: case 8232: case 8233:
4867 ++this.pos;
4868 if (this.options.locations) {
4869 ++this.curLine;
4870 this.lineStart = this.pos;
4871 }
4872 break
4873 case 47: // '/'
4874 switch (this.input.charCodeAt(this.pos + 1)) {
4875 case 42: // '*'
4876 this.skipBlockComment();
4877 break
4878 case 47:
4879 this.skipLineComment(2);
4880 break
4881 default:
4882 break loop
4883 }
4884 break
4885 default:
4886 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
4887 ++this.pos;
4888 } else {
4889 break loop
4890 }
4891 }
4892 }
4893};
4894
4895// Called at the end of every token. Sets `end`, `val`, and
4896// maintains `context` and `exprAllowed`, and skips the space after
4897// the token, so that the next one's `start` will point at the
4898// right position.
4899
4900pp.finishToken = function(type, val) {
4901 this.end = this.pos;
4902 if (this.options.locations) { this.endLoc = this.curPosition(); }
4903 var prevType = this.type;
4904 this.type = type;
4905 this.value = val;
4906
4907 this.updateContext(prevType);
4908};
4909
4910// ### Token reading
4911
4912// This is the function that is called to fetch the next token. It
4913// is somewhat obscure, because it works in character codes rather
4914// than characters, and because operator parsing has been inlined
4915// into it.
4916//
4917// All in the name of speed.
4918//
4919pp.readToken_dot = function() {
4920 var next = this.input.charCodeAt(this.pos + 1);
4921 if (next >= 48 && next <= 57) { return this.readNumber(true) }
4922 var next2 = this.input.charCodeAt(this.pos + 2);
4923 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
4924 this.pos += 3;
4925 return this.finishToken(types$1.ellipsis)
4926 } else {
4927 ++this.pos;
4928 return this.finishToken(types$1.dot)
4929 }
4930};
4931
4932pp.readToken_slash = function() { // '/'
4933 var next = this.input.charCodeAt(this.pos + 1);
4934 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
4935 if (next === 61) { return this.finishOp(types$1.assign, 2) }
4936 return this.finishOp(types$1.slash, 1)
4937};
4938
4939pp.readToken_mult_modulo_exp = function(code) { // '%*'
4940 var next = this.input.charCodeAt(this.pos + 1);
4941 var size = 1;
4942 var tokentype = code === 42 ? types$1.star : types$1.modulo;
4943
4944 // exponentiation operator ** and **=
4945 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
4946 ++size;
4947 tokentype = types$1.starstar;
4948 next = this.input.charCodeAt(this.pos + 2);
4949 }
4950
4951 if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
4952 return this.finishOp(tokentype, size)
4953};
4954
4955pp.readToken_pipe_amp = function(code) { // '|&'
4956 var next = this.input.charCodeAt(this.pos + 1);
4957 if (next === code) {
4958 if (this.options.ecmaVersion >= 12) {
4959 var next2 = this.input.charCodeAt(this.pos + 2);
4960 if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
4961 }
4962 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
4963 }
4964 if (next === 61) { return this.finishOp(types$1.assign, 2) }
4965 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
4966};
4967
4968pp.readToken_caret = function() { // '^'
4969 var next = this.input.charCodeAt(this.pos + 1);
4970 if (next === 61) { return this.finishOp(types$1.assign, 2) }
4971 return this.finishOp(types$1.bitwiseXOR, 1)
4972};
4973
4974pp.readToken_plus_min = function(code) { // '+-'
4975 var next = this.input.charCodeAt(this.pos + 1);
4976 if (next === code) {
4977 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
4978 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
4979 // A `-->` line comment
4980 this.skipLineComment(3);
4981 this.skipSpace();
4982 return this.nextToken()
4983 }
4984 return this.finishOp(types$1.incDec, 2)
4985 }
4986 if (next === 61) { return this.finishOp(types$1.assign, 2) }
4987 return this.finishOp(types$1.plusMin, 1)
4988};
4989
4990pp.readToken_lt_gt = function(code) { // '<>'
4991 var next = this.input.charCodeAt(this.pos + 1);
4992 var size = 1;
4993 if (next === code) {
4994 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
4995 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
4996 return this.finishOp(types$1.bitShift, size)
4997 }
4998 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
4999 this.input.charCodeAt(this.pos + 3) === 45) {
5000 // `<!--`, an XML-style comment that should be interpreted as a line comment
5001 this.skipLineComment(4);
5002 this.skipSpace();
5003 return this.nextToken()
5004 }
5005 if (next === 61) { size = 2; }
5006 return this.finishOp(types$1.relational, size)
5007};
5008
5009pp.readToken_eq_excl = function(code) { // '=!'
5010 var next = this.input.charCodeAt(this.pos + 1);
5011 if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
5012 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
5013 this.pos += 2;
5014 return this.finishToken(types$1.arrow)
5015 }
5016 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
5017};
5018
5019pp.readToken_question = function() { // '?'
5020 var ecmaVersion = this.options.ecmaVersion;
5021 if (ecmaVersion >= 11) {
5022 var next = this.input.charCodeAt(this.pos + 1);
5023 if (next === 46) {
5024 var next2 = this.input.charCodeAt(this.pos + 2);
5025 if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
5026 }
5027 if (next === 63) {
5028 if (ecmaVersion >= 12) {
5029 var next2$1 = this.input.charCodeAt(this.pos + 2);
5030 if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
5031 }
5032 return this.finishOp(types$1.coalesce, 2)
5033 }
5034 }
5035 return this.finishOp(types$1.question, 1)
5036};
5037
5038pp.readToken_numberSign = function() { // '#'
5039 var ecmaVersion = this.options.ecmaVersion;
5040 var code = 35; // '#'
5041 if (ecmaVersion >= 13) {
5042 ++this.pos;
5043 code = this.fullCharCodeAtPos();
5044 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
5045 return this.finishToken(types$1.privateId, this.readWord1())
5046 }
5047 }
5048
5049 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
5050};
5051
5052pp.getTokenFromCode = function(code) {
5053 switch (code) {
5054 // The interpretation of a dot depends on whether it is followed
5055 // by a digit or another two dots.
5056 case 46: // '.'
5057 return this.readToken_dot()
5058
5059 // Punctuation tokens.
5060 case 40: ++this.pos; return this.finishToken(types$1.parenL)
5061 case 41: ++this.pos; return this.finishToken(types$1.parenR)
5062 case 59: ++this.pos; return this.finishToken(types$1.semi)
5063 case 44: ++this.pos; return this.finishToken(types$1.comma)
5064 case 91: ++this.pos; return this.finishToken(types$1.bracketL)
5065 case 93: ++this.pos; return this.finishToken(types$1.bracketR)
5066 case 123: ++this.pos; return this.finishToken(types$1.braceL)
5067 case 125: ++this.pos; return this.finishToken(types$1.braceR)
5068 case 58: ++this.pos; return this.finishToken(types$1.colon)
5069
5070 case 96: // '`'
5071 if (this.options.ecmaVersion < 6) { break }
5072 ++this.pos;
5073 return this.finishToken(types$1.backQuote)
5074
5075 case 48: // '0'
5076 var next = this.input.charCodeAt(this.pos + 1);
5077 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
5078 if (this.options.ecmaVersion >= 6) {
5079 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
5080 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
5081 }
5082
5083 // Anything else beginning with a digit is an integer, octal
5084 // number, or float.
5085 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
5086 return this.readNumber(false)
5087
5088 // Quotes produce strings.
5089 case 34: case 39: // '"', "'"
5090 return this.readString(code)
5091
5092 // Operators are parsed inline in tiny state machines. '=' (61) is
5093 // often referred to. `finishOp` simply skips the amount of
5094 // characters it is given as second argument, and returns a token
5095 // of the type given by its first argument.
5096 case 47: // '/'
5097 return this.readToken_slash()
5098
5099 case 37: case 42: // '%*'
5100 return this.readToken_mult_modulo_exp(code)
5101
5102 case 124: case 38: // '|&'
5103 return this.readToken_pipe_amp(code)
5104
5105 case 94: // '^'
5106 return this.readToken_caret()
5107
5108 case 43: case 45: // '+-'
5109 return this.readToken_plus_min(code)
5110
5111 case 60: case 62: // '<>'
5112 return this.readToken_lt_gt(code)
5113
5114 case 61: case 33: // '=!'
5115 return this.readToken_eq_excl(code)
5116
5117 case 63: // '?'
5118 return this.readToken_question()
5119
5120 case 126: // '~'
5121 return this.finishOp(types$1.prefix, 1)
5122
5123 case 35: // '#'
5124 return this.readToken_numberSign()
5125 }
5126
5127 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
5128};
5129
5130pp.finishOp = function(type, size) {
5131 var str = this.input.slice(this.pos, this.pos + size);
5132 this.pos += size;
5133 return this.finishToken(type, str)
5134};
5135
5136pp.readRegexp = function() {
5137 var escaped, inClass, start = this.pos;
5138 for (;;) {
5139 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
5140 var ch = this.input.charAt(this.pos);
5141 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
5142 if (!escaped) {
5143 if (ch === "[") { inClass = true; }
5144 else if (ch === "]" && inClass) { inClass = false; }
5145 else if (ch === "/" && !inClass) { break }
5146 escaped = ch === "\\";
5147 } else { escaped = false; }
5148 ++this.pos;
5149 }
5150 var pattern = this.input.slice(start, this.pos);
5151 ++this.pos;
5152 var flagsStart = this.pos;
5153 var flags = this.readWord1();
5154 if (this.containsEsc) { this.unexpected(flagsStart); }
5155
5156 // Validate pattern
5157 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
5158 state.reset(start, pattern, flags);
5159 this.validateRegExpFlags(state);
5160 this.validateRegExpPattern(state);
5161
5162 // Create Literal#value property value.
5163 var value = null;
5164 try {
5165 value = new RegExp(pattern, flags);
5166 } catch (e) {
5167 // ESTree requires null if it failed to instantiate RegExp object.
5168 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
5169 }
5170
5171 return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
5172};
5173
5174// Read an integer in the given radix. Return null if zero digits
5175// were read, the integer value otherwise. When `len` is given, this
5176// will return `null` unless the integer has exactly `len` digits.
5177
5178pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
5179 // `len` is used for character escape sequences. In that case, disallow separators.
5180 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
5181
5182 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
5183 // and isn't fraction part nor exponent part. In that case, if the first digit
5184 // is zero then disallow separators.
5185 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
5186
5187 var start = this.pos, total = 0, lastCode = 0;
5188 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
5189 var code = this.input.charCodeAt(this.pos), val = (void 0);
5190
5191 if (allowSeparators && code === 95) {
5192 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
5193 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
5194 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
5195 lastCode = code;
5196 continue
5197 }
5198
5199 if (code >= 97) { val = code - 97 + 10; } // a
5200 else if (code >= 65) { val = code - 65 + 10; } // A
5201 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
5202 else { val = Infinity; }
5203 if (val >= radix) { break }
5204 lastCode = code;
5205 total = total * radix + val;
5206 }
5207
5208 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
5209 if (this.pos === start || len != null && this.pos - start !== len) { return null }
5210
5211 return total
5212};
5213
5214function stringToNumber(str, isLegacyOctalNumericLiteral) {
5215 if (isLegacyOctalNumericLiteral) {
5216 return parseInt(str, 8)
5217 }
5218
5219 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
5220 return parseFloat(str.replace(/_/g, ""))
5221}
5222
5223function stringToBigInt(str) {
5224 if (typeof BigInt !== "function") {
5225 return null
5226 }
5227
5228 // `BigInt(value)` throws syntax error if the string contains numeric separators.
5229 return BigInt(str.replace(/_/g, ""))
5230}
5231
5232pp.readRadixNumber = function(radix) {
5233 var start = this.pos;
5234 this.pos += 2; // 0x
5235 var val = this.readInt(radix);
5236 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
5237 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
5238 val = stringToBigInt(this.input.slice(start, this.pos));
5239 ++this.pos;
5240 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5241 return this.finishToken(types$1.num, val)
5242};
5243
5244// Read an integer, octal integer, or floating-point number.
5245
5246pp.readNumber = function(startsWithDot) {
5247 var start = this.pos;
5248 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
5249 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
5250 if (octal && this.strict) { this.raise(start, "Invalid number"); }
5251 var next = this.input.charCodeAt(this.pos);
5252 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
5253 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
5254 ++this.pos;
5255 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5256 return this.finishToken(types$1.num, val$1)
5257 }
5258 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
5259 if (next === 46 && !octal) { // '.'
5260 ++this.pos;
5261 this.readInt(10);
5262 next = this.input.charCodeAt(this.pos);
5263 }
5264 if ((next === 69 || next === 101) && !octal) { // 'eE'
5265 next = this.input.charCodeAt(++this.pos);
5266 if (next === 43 || next === 45) { ++this.pos; } // '+-'
5267 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
5268 }
5269 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5270
5271 var val = stringToNumber(this.input.slice(start, this.pos), octal);
5272 return this.finishToken(types$1.num, val)
5273};
5274
5275// Read a string value, interpreting backslash-escapes.
5276
5277pp.readCodePoint = function() {
5278 var ch = this.input.charCodeAt(this.pos), code;
5279
5280 if (ch === 123) { // '{'
5281 if (this.options.ecmaVersion < 6) { this.unexpected(); }
5282 var codePos = ++this.pos;
5283 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
5284 ++this.pos;
5285 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
5286 } else {
5287 code = this.readHexChar(4);
5288 }
5289 return code
5290};
5291
5292pp.readString = function(quote) {
5293 var out = "", chunkStart = ++this.pos;
5294 for (;;) {
5295 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
5296 var ch = this.input.charCodeAt(this.pos);
5297 if (ch === quote) { break }
5298 if (ch === 92) { // '\'
5299 out += this.input.slice(chunkStart, this.pos);
5300 out += this.readEscapedChar(false);
5301 chunkStart = this.pos;
5302 } else if (ch === 0x2028 || ch === 0x2029) {
5303 if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
5304 ++this.pos;
5305 if (this.options.locations) {
5306 this.curLine++;
5307 this.lineStart = this.pos;
5308 }
5309 } else {
5310 if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
5311 ++this.pos;
5312 }
5313 }
5314 out += this.input.slice(chunkStart, this.pos++);
5315 return this.finishToken(types$1.string, out)
5316};
5317
5318// Reads template string tokens.
5319
5320var INVALID_TEMPLATE_ESCAPE_ERROR = {};
5321
5322pp.tryReadTemplateToken = function() {
5323 this.inTemplateElement = true;
5324 try {
5325 this.readTmplToken();
5326 } catch (err) {
5327 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
5328 this.readInvalidTemplateToken();
5329 } else {
5330 throw err
5331 }
5332 }
5333
5334 this.inTemplateElement = false;
5335};
5336
5337pp.invalidStringToken = function(position, message) {
5338 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
5339 throw INVALID_TEMPLATE_ESCAPE_ERROR
5340 } else {
5341 this.raise(position, message);
5342 }
5343};
5344
5345pp.readTmplToken = function() {
5346 var out = "", chunkStart = this.pos;
5347 for (;;) {
5348 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
5349 var ch = this.input.charCodeAt(this.pos);
5350 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
5351 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
5352 if (ch === 36) {
5353 this.pos += 2;
5354 return this.finishToken(types$1.dollarBraceL)
5355 } else {
5356 ++this.pos;
5357 return this.finishToken(types$1.backQuote)
5358 }
5359 }
5360 out += this.input.slice(chunkStart, this.pos);
5361 return this.finishToken(types$1.template, out)
5362 }
5363 if (ch === 92) { // '\'
5364 out += this.input.slice(chunkStart, this.pos);
5365 out += this.readEscapedChar(true);
5366 chunkStart = this.pos;
5367 } else if (isNewLine(ch)) {
5368 out += this.input.slice(chunkStart, this.pos);
5369 ++this.pos;
5370 switch (ch) {
5371 case 13:
5372 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
5373 case 10:
5374 out += "\n";
5375 break
5376 default:
5377 out += String.fromCharCode(ch);
5378 break
5379 }
5380 if (this.options.locations) {
5381 ++this.curLine;
5382 this.lineStart = this.pos;
5383 }
5384 chunkStart = this.pos;
5385 } else {
5386 ++this.pos;
5387 }
5388 }
5389};
5390
5391// Reads a template token to search for the end, without validating any escape sequences
5392pp.readInvalidTemplateToken = function() {
5393 for (; this.pos < this.input.length; this.pos++) {
5394 switch (this.input[this.pos]) {
5395 case "\\":
5396 ++this.pos;
5397 break
5398
5399 case "$":
5400 if (this.input[this.pos + 1] !== "{") {
5401 break
5402 }
5403
5404 // falls through
5405 case "`":
5406 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
5407
5408 // no default
5409 }
5410 }
5411 this.raise(this.start, "Unterminated template");
5412};
5413
5414// Used to read escaped characters
5415
5416pp.readEscapedChar = function(inTemplate) {
5417 var ch = this.input.charCodeAt(++this.pos);
5418 ++this.pos;
5419 switch (ch) {
5420 case 110: return "\n" // 'n' -> '\n'
5421 case 114: return "\r" // 'r' -> '\r'
5422 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
5423 case 117: return codePointToString(this.readCodePoint()) // 'u'
5424 case 116: return "\t" // 't' -> '\t'
5425 case 98: return "\b" // 'b' -> '\b'
5426 case 118: return "\u000b" // 'v' -> '\u000b'
5427 case 102: return "\f" // 'f' -> '\f'
5428 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
5429 case 10: // ' \n'
5430 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
5431 return ""
5432 case 56:
5433 case 57:
5434 if (this.strict) {
5435 this.invalidStringToken(
5436 this.pos - 1,
5437 "Invalid escape sequence"
5438 );
5439 }
5440 if (inTemplate) {
5441 var codePos = this.pos - 1;
5442
5443 this.invalidStringToken(
5444 codePos,
5445 "Invalid escape sequence in template string"
5446 );
5447
5448 return null
5449 }
5450 default:
5451 if (ch >= 48 && ch <= 55) {
5452 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
5453 var octal = parseInt(octalStr, 8);
5454 if (octal > 255) {
5455 octalStr = octalStr.slice(0, -1);
5456 octal = parseInt(octalStr, 8);
5457 }
5458 this.pos += octalStr.length - 1;
5459 ch = this.input.charCodeAt(this.pos);
5460 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
5461 this.invalidStringToken(
5462 this.pos - 1 - octalStr.length,
5463 inTemplate
5464 ? "Octal literal in template string"
5465 : "Octal literal in strict mode"
5466 );
5467 }
5468 return String.fromCharCode(octal)
5469 }
5470 if (isNewLine(ch)) {
5471 // Unicode new line characters after \ get removed from output in both
5472 // template literals and strings
5473 return ""
5474 }
5475 return String.fromCharCode(ch)
5476 }
5477};
5478
5479// Used to read character escape sequences ('\x', '\u', '\U').
5480
5481pp.readHexChar = function(len) {
5482 var codePos = this.pos;
5483 var n = this.readInt(16, len);
5484 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
5485 return n
5486};
5487
5488// Read an identifier, and return it as a string. Sets `this.containsEsc`
5489// to whether the word contained a '\u' escape.
5490//
5491// Incrementally adds only escaped chars, adding other chunks as-is
5492// as a micro-optimization.
5493
5494pp.readWord1 = function() {
5495 this.containsEsc = false;
5496 var word = "", first = true, chunkStart = this.pos;
5497 var astral = this.options.ecmaVersion >= 6;
5498 while (this.pos < this.input.length) {
5499 var ch = this.fullCharCodeAtPos();
5500 if (isIdentifierChar(ch, astral)) {
5501 this.pos += ch <= 0xffff ? 1 : 2;
5502 } else if (ch === 92) { // "\"
5503 this.containsEsc = true;
5504 word += this.input.slice(chunkStart, this.pos);
5505 var escStart = this.pos;
5506 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
5507 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
5508 ++this.pos;
5509 var esc = this.readCodePoint();
5510 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
5511 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
5512 word += codePointToString(esc);
5513 chunkStart = this.pos;
5514 } else {
5515 break
5516 }
5517 first = false;
5518 }
5519 return word + this.input.slice(chunkStart, this.pos)
5520};
5521
5522// Read an identifier or keyword token. Will check for reserved
5523// words when necessary.
5524
5525pp.readWord = function() {
5526 var word = this.readWord1();
5527 var type = types$1.name;
5528 if (this.keywords.test(word)) {
5529 type = keywords[word];
5530 }
5531 return this.finishToken(type, word)
5532};
5533
5534// Acorn is a tiny, fast JavaScript parser written in JavaScript.
5535
5536var version = "8.8.1";
5537
5538Parser.acorn = {
5539 Parser: Parser,
5540 version: version,
5541 defaultOptions: defaultOptions,
5542 Position: Position,
5543 SourceLocation: SourceLocation,
5544 getLineInfo: getLineInfo,
5545 Node: Node,
5546 TokenType: TokenType,
5547 tokTypes: types$1,
5548 keywordTypes: keywords,
5549 TokContext: TokContext,
5550 tokContexts: types,
5551 isIdentifierChar: isIdentifierChar,
5552 isIdentifierStart: isIdentifierStart,
5553 Token: Token,
5554 isNewLine: isNewLine,
5555 lineBreak: lineBreak,
5556 lineBreakG: lineBreakG,
5557 nonASCIIwhitespace: nonASCIIwhitespace
5558};
5559
5560function normalizeWindowsPath(input = "") {
5561 if (!input || !input.includes("\\")) {
5562 return input;
5563 }
5564 return input.replace(/\\/g, "/");
5565}
5566const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
5567function cwd() {
5568 if (typeof process !== "undefined") {
5569 return process.cwd().replace(/\\/g, "/");
5570 }
5571 return "/";
5572}
5573const resolve = function(...arguments_) {
5574 arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
5575 let resolvedPath = "";
5576 let resolvedAbsolute = false;
5577 for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
5578 const path = index >= 0 ? arguments_[index] : cwd();
5579 if (!path || path.length === 0) {
5580 continue;
5581 }
5582 resolvedPath = `${path}/${resolvedPath}`;
5583 resolvedAbsolute = isAbsolute(path);
5584 }
5585 resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
5586 if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
5587 return `/${resolvedPath}`;
5588 }
5589 return resolvedPath.length > 0 ? resolvedPath : ".";
5590};
5591function normalizeString(path, allowAboveRoot) {
5592 let res = "";
5593 let lastSegmentLength = 0;
5594 let lastSlash = -1;
5595 let dots = 0;
5596 let char = null;
5597 for (let index = 0; index <= path.length; ++index) {
5598 if (index < path.length) {
5599 char = path[index];
5600 } else if (char === "/") {
5601 break;
5602 } else {
5603 char = "/";
5604 }
5605 if (char === "/") {
5606 if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
5607 if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
5608 if (res.length > 2) {
5609 const lastSlashIndex = res.lastIndexOf("/");
5610 if (lastSlashIndex === -1) {
5611 res = "";
5612 lastSegmentLength = 0;
5613 } else {
5614 res = res.slice(0, lastSlashIndex);
5615 lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
5616 }
5617 lastSlash = index;
5618 dots = 0;
5619 continue;
5620 } else if (res.length > 0) {
5621 res = "";
5622 lastSegmentLength = 0;
5623 lastSlash = index;
5624 dots = 0;
5625 continue;
5626 }
5627 }
5628 if (allowAboveRoot) {
5629 res += res.length > 0 ? "/.." : "..";
5630 lastSegmentLength = 2;
5631 }
5632 } else {
5633 if (res.length > 0) {
5634 res += `/${path.slice(lastSlash + 1, index)}`;
5635 } else {
5636 res = path.slice(lastSlash + 1, index);
5637 }
5638 lastSegmentLength = index - lastSlash - 1;
5639 }
5640 lastSlash = index;
5641 dots = 0;
5642 } else if (char === "." && dots !== -1) {
5643 ++dots;
5644 } else {
5645 dots = -1;
5646 }
5647 }
5648 return res;
5649}
5650const isAbsolute = function(p) {
5651 return _IS_ABSOLUTE_RE.test(p);
5652};
5653
5654const BUILTIN_MODULES = new Set(builtinModules);
5655
5656/**
5657 * @typedef ErrnoExceptionFields
5658 * @property {number | undefined} [errnode]
5659 * @property {string | undefined} [code]
5660 * @property {string | undefined} [path]
5661 * @property {string | undefined} [syscall]
5662 * @property {string | undefined} [url]
5663 *
5664 * @typedef {Error & ErrnoExceptionFields} ErrnoException
5665 */
5666
5667const isWindows$1 = process$1.platform === 'win32';
5668
5669const own$1 = {}.hasOwnProperty;
5670
5671/**
5672 * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
5673 * We cannot use Intl.ListFormat because it's not available in
5674 * --without-intl builds.
5675 *
5676 * @param {Array<string>} array
5677 * An array of strings.
5678 * @param {string} [type]
5679 * The list type to be inserted before the last element.
5680 * @returns {string}
5681 */
5682function formatList(array, type = 'and') {
5683 return array.length < 3
5684 ? array.join(` ${type} `)
5685 : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
5686}
5687
5688/** @type {Map<string, MessageFunction|string>} */
5689const messages = new Map();
5690const nodeInternalPrefix = '__node_internal_';
5691/** @type {number} */
5692let userStackTraceLimit;
5693
5694createError(
5695 'ERR_INVALID_MODULE_SPECIFIER',
5696 /**
5697 * @param {string} request
5698 * @param {string} reason
5699 * @param {string} [base]
5700 */
5701 (request, reason, base = undefined) => {
5702 return `Invalid module "${request}" ${reason}${
5703 base ? ` imported from ${base}` : ''
5704 }`
5705 },
5706 TypeError
5707);
5708
5709createError(
5710 'ERR_INVALID_PACKAGE_CONFIG',
5711 /**
5712 * @param {string} path
5713 * @param {string} [base]
5714 * @param {string} [message]
5715 */
5716 (path, base, message) => {
5717 return `Invalid package config ${path}${
5718 base ? ` while importing ${base}` : ''
5719 }${message ? `. ${message}` : ''}`
5720 },
5721 Error
5722);
5723
5724createError(
5725 'ERR_INVALID_PACKAGE_TARGET',
5726 /**
5727 * @param {string} pkgPath
5728 * @param {string} key
5729 * @param {unknown} target
5730 * @param {boolean} [isImport=false]
5731 * @param {string} [base]
5732 */
5733 (pkgPath, key, target, isImport = false, base = undefined) => {
5734 const relError =
5735 typeof target === 'string' &&
5736 !isImport &&
5737 target.length > 0 &&
5738 !target.startsWith('./');
5739 if (key === '.') {
5740 assert(isImport === false);
5741 return (
5742 `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
5743 `in the package config ${pkgPath}package.json${
5744 base ? ` imported from ${base}` : ''
5745 }${relError ? '; targets must start with "./"' : ''}`
5746 )
5747 }
5748
5749 return `Invalid "${
5750 isImport ? 'imports' : 'exports'
5751 }" target ${JSON.stringify(
5752 target
5753 )} defined for '${key}' in the package config ${pkgPath}package.json${
5754 base ? ` imported from ${base}` : ''
5755 }${relError ? '; targets must start with "./"' : ''}`
5756 },
5757 Error
5758);
5759
5760createError(
5761 'ERR_MODULE_NOT_FOUND',
5762 /**
5763 * @param {string} path
5764 * @param {string} base
5765 * @param {string} [type]
5766 */
5767 (path, base, type = 'package') => {
5768 return `Cannot find ${type} '${path}' imported from ${base}`
5769 },
5770 Error
5771);
5772
5773createError(
5774 'ERR_NETWORK_IMPORT_DISALLOWED',
5775 "import of '%s' by %s is not supported: %s",
5776 Error
5777);
5778
5779createError(
5780 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
5781 /**
5782 * @param {string} specifier
5783 * @param {string} packagePath
5784 * @param {string} base
5785 */
5786 (specifier, packagePath, base) => {
5787 return `Package import specifier "${specifier}" is not defined${
5788 packagePath ? ` in package ${packagePath}package.json` : ''
5789 } imported from ${base}`
5790 },
5791 TypeError
5792);
5793
5794createError(
5795 'ERR_PACKAGE_PATH_NOT_EXPORTED',
5796 /**
5797 * @param {string} pkgPath
5798 * @param {string} subpath
5799 * @param {string} [base]
5800 */
5801 (pkgPath, subpath, base = undefined) => {
5802 if (subpath === '.')
5803 return `No "exports" main defined in ${pkgPath}package.json${
5804 base ? ` imported from ${base}` : ''
5805 }`
5806 return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
5807 base ? ` imported from ${base}` : ''
5808 }`
5809 },
5810 Error
5811);
5812
5813createError(
5814 'ERR_UNSUPPORTED_DIR_IMPORT',
5815 "Directory import '%s' is not supported " +
5816 'resolving ES modules imported from %s',
5817 Error
5818);
5819
5820createError(
5821 'ERR_UNKNOWN_FILE_EXTENSION',
5822 /**
5823 * @param {string} ext
5824 * @param {string} path
5825 */
5826 (ext, path) => {
5827 return `Unknown file extension "${ext}" for ${path}`
5828 },
5829 TypeError
5830);
5831
5832createError(
5833 'ERR_INVALID_ARG_VALUE',
5834 /**
5835 * @param {string} name
5836 * @param {unknown} value
5837 * @param {string} [reason='is invalid']
5838 */
5839 (name, value, reason = 'is invalid') => {
5840 let inspected = inspect(value);
5841
5842 if (inspected.length > 128) {
5843 inspected = `${inspected.slice(0, 128)}...`;
5844 }
5845
5846 const type = name.includes('.') ? 'property' : 'argument';
5847
5848 return `The ${type} '${name}' ${reason}. Received ${inspected}`
5849 },
5850 TypeError
5851 // Note: extra classes have been shaken out.
5852 // , RangeError
5853);
5854
5855createError(
5856 'ERR_UNSUPPORTED_ESM_URL_SCHEME',
5857 /**
5858 * @param {URL} url
5859 * @param {Array<string>} supported
5860 */
5861 (url, supported) => {
5862 let message = `Only URLs with a scheme in: ${formatList(
5863 supported
5864 )} are supported by the default ESM loader`;
5865
5866 if (isWindows$1 && url.protocol.length === 2) {
5867 message += '. On Windows, absolute paths must be valid file:// URLs';
5868 }
5869
5870 message += `. Received protocol '${url.protocol}'`;
5871 return message
5872 },
5873 Error
5874);
5875
5876/**
5877 * Utility function for registering the error codes. Only used here. Exported
5878 * *only* to allow for testing.
5879 * @param {string} sym
5880 * @param {MessageFunction|string} value
5881 * @param {ErrorConstructor} def
5882 * @returns {new (...args: Array<any>) => Error}
5883 */
5884function createError(sym, value, def) {
5885 // Special case for SystemError that formats the error message differently
5886 // The SystemErrors only have SystemError as their base classes.
5887 messages.set(sym, value);
5888
5889 return makeNodeErrorWithCode(def, sym)
5890}
5891
5892/**
5893 * @param {ErrorConstructor} Base
5894 * @param {string} key
5895 * @returns {ErrorConstructor}
5896 */
5897function makeNodeErrorWithCode(Base, key) {
5898 // @ts-expect-error It’s a Node error.
5899 return NodeError
5900 /**
5901 * @param {Array<unknown>} args
5902 */
5903 function NodeError(...args) {
5904 const limit = Error.stackTraceLimit;
5905 if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
5906 const error = new Base();
5907 // Reset the limit and setting the name property.
5908 if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
5909 const message = getMessage(key, args, error);
5910 Object.defineProperties(error, {
5911 // Note: no need to implement `kIsNodeError` symbol, would be hard,
5912 // probably.
5913 message: {
5914 value: message,
5915 enumerable: false,
5916 writable: true,
5917 configurable: true
5918 },
5919 toString: {
5920 /** @this {Error} */
5921 value() {
5922 return `${this.name} [${key}]: ${this.message}`
5923 },
5924 enumerable: false,
5925 writable: true,
5926 configurable: true
5927 }
5928 });
5929
5930 captureLargerStackTrace(error);
5931 // @ts-expect-error It’s a Node error.
5932 error.code = key;
5933 return error
5934 }
5935}
5936
5937/**
5938 * @returns {boolean}
5939 */
5940function isErrorStackTraceLimitWritable() {
5941 // Do no touch Error.stackTraceLimit as V8 would attempt to install
5942 // it again during deserialization.
5943 try {
5944 // @ts-expect-error: not in types?
5945 if (v8.startupSnapshot.isBuildingSnapshot()) {
5946 return false
5947 }
5948 } catch {}
5949
5950 const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
5951 if (desc === undefined) {
5952 return Object.isExtensible(Error)
5953 }
5954
5955 return own$1.call(desc, 'writable') && desc.writable !== undefined
5956 ? desc.writable
5957 : desc.set !== undefined
5958}
5959
5960/**
5961 * This function removes unnecessary frames from Node.js core errors.
5962 * @template {(...args: unknown[]) => unknown} T
5963 * @param {T} fn
5964 * @returns {T}
5965 */
5966function hideStackFrames(fn) {
5967 // We rename the functions that will be hidden to cut off the stacktrace
5968 // at the outermost one
5969 const hidden = nodeInternalPrefix + fn.name;
5970 Object.defineProperty(fn, 'name', {value: hidden});
5971 return fn
5972}
5973
5974const captureLargerStackTrace = hideStackFrames(
5975 /**
5976 * @param {Error} error
5977 * @returns {Error}
5978 */
5979 // @ts-expect-error: fine
5980 function (error) {
5981 const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
5982 if (stackTraceLimitIsWritable) {
5983 userStackTraceLimit = Error.stackTraceLimit;
5984 Error.stackTraceLimit = Number.POSITIVE_INFINITY;
5985 }
5986
5987 Error.captureStackTrace(error);
5988
5989 // Reset the limit
5990 if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
5991
5992 return error
5993 }
5994);
5995
5996/**
5997 * @param {string} key
5998 * @param {Array<unknown>} args
5999 * @param {Error} self
6000 * @returns {string}
6001 */
6002function getMessage(key, args, self) {
6003 const message = messages.get(key);
6004 assert(typeof message !== 'undefined', 'expected `message` to be found');
6005
6006 if (typeof message === 'function') {
6007 assert(
6008 message.length <= args.length, // Default options do not count.
6009 `Code: ${key}; The provided arguments length (${args.length}) does not ` +
6010 `match the required ones (${message.length}).`
6011 );
6012 return Reflect.apply(message, self, args)
6013 }
6014
6015 const regex = /%[dfijoOs]/g;
6016 let expectedLength = 0;
6017 while (regex.exec(message) !== null) expectedLength++;
6018 assert(
6019 expectedLength === args.length,
6020 `Code: ${key}; The provided arguments length (${args.length}) does not ` +
6021 `match the required ones (${expectedLength}).`
6022 );
6023 if (args.length === 0) return message
6024
6025 args.unshift(message);
6026 return Reflect.apply(format, null, args)
6027}
6028function isNodeBuiltin(id = "") {
6029 id = id.replace(/^node:/, "").split("/")[0];
6030 return BUILTIN_MODULES.has(id);
6031}
6032pathToFileURL(process.cwd());
6033
6034function getDefaultExportFromCjs (x) {
6035 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
6036}
6037
6038var src = {exports: {}};
6039
6040var browser$1 = {exports: {}};
6041
6042/**
6043 * Helpers.
6044 */
6045
6046var ms;
6047var hasRequiredMs;
6048
6049function requireMs () {
6050 if (hasRequiredMs) return ms;
6051 hasRequiredMs = 1;
6052 var s = 1000;
6053 var m = s * 60;
6054 var h = m * 60;
6055 var d = h * 24;
6056 var w = d * 7;
6057 var y = d * 365.25;
6058
6059 /**
6060 * Parse or format the given `val`.
6061 *
6062 * Options:
6063 *
6064 * - `long` verbose formatting [false]
6065 *
6066 * @param {String|Number} val
6067 * @param {Object} [options]
6068 * @throws {Error} throw an error if val is not a non-empty string or a number
6069 * @return {String|Number}
6070 * @api public
6071 */
6072
6073 ms = function(val, options) {
6074 options = options || {};
6075 var type = typeof val;
6076 if (type === 'string' && val.length > 0) {
6077 return parse(val);
6078 } else if (type === 'number' && isFinite(val)) {
6079 return options.long ? fmtLong(val) : fmtShort(val);
6080 }
6081 throw new Error(
6082 'val is not a non-empty string or a valid number. val=' +
6083 JSON.stringify(val)
6084 );
6085 };
6086
6087 /**
6088 * Parse the given `str` and return milliseconds.
6089 *
6090 * @param {String} str
6091 * @return {Number}
6092 * @api private
6093 */
6094
6095 function parse(str) {
6096 str = String(str);
6097 if (str.length > 100) {
6098 return;
6099 }
6100 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
6101 str
6102 );
6103 if (!match) {
6104 return;
6105 }
6106 var n = parseFloat(match[1]);
6107 var type = (match[2] || 'ms').toLowerCase();
6108 switch (type) {
6109 case 'years':
6110 case 'year':
6111 case 'yrs':
6112 case 'yr':
6113 case 'y':
6114 return n * y;
6115 case 'weeks':
6116 case 'week':
6117 case 'w':
6118 return n * w;
6119 case 'days':
6120 case 'day':
6121 case 'd':
6122 return n * d;
6123 case 'hours':
6124 case 'hour':
6125 case 'hrs':
6126 case 'hr':
6127 case 'h':
6128 return n * h;
6129 case 'minutes':
6130 case 'minute':
6131 case 'mins':
6132 case 'min':
6133 case 'm':
6134 return n * m;
6135 case 'seconds':
6136 case 'second':
6137 case 'secs':
6138 case 'sec':
6139 case 's':
6140 return n * s;
6141 case 'milliseconds':
6142 case 'millisecond':
6143 case 'msecs':
6144 case 'msec':
6145 case 'ms':
6146 return n;
6147 default:
6148 return undefined;
6149 }
6150 }
6151
6152 /**
6153 * Short format for `ms`.
6154 *
6155 * @param {Number} ms
6156 * @return {String}
6157 * @api private
6158 */
6159
6160 function fmtShort(ms) {
6161 var msAbs = Math.abs(ms);
6162 if (msAbs >= d) {
6163 return Math.round(ms / d) + 'd';
6164 }
6165 if (msAbs >= h) {
6166 return Math.round(ms / h) + 'h';
6167 }
6168 if (msAbs >= m) {
6169 return Math.round(ms / m) + 'm';
6170 }
6171 if (msAbs >= s) {
6172 return Math.round(ms / s) + 's';
6173 }
6174 return ms + 'ms';
6175 }
6176
6177 /**
6178 * Long format for `ms`.
6179 *
6180 * @param {Number} ms
6181 * @return {String}
6182 * @api private
6183 */
6184
6185 function fmtLong(ms) {
6186 var msAbs = Math.abs(ms);
6187 if (msAbs >= d) {
6188 return plural(ms, msAbs, d, 'day');
6189 }
6190 if (msAbs >= h) {
6191 return plural(ms, msAbs, h, 'hour');
6192 }
6193 if (msAbs >= m) {
6194 return plural(ms, msAbs, m, 'minute');
6195 }
6196 if (msAbs >= s) {
6197 return plural(ms, msAbs, s, 'second');
6198 }
6199 return ms + ' ms';
6200 }
6201
6202 /**
6203 * Pluralization helper.
6204 */
6205
6206 function plural(ms, msAbs, n, name) {
6207 var isPlural = msAbs >= n * 1.5;
6208 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
6209 }
6210 return ms;
6211}
6212
6213var common;
6214var hasRequiredCommon;
6215
6216function requireCommon () {
6217 if (hasRequiredCommon) return common;
6218 hasRequiredCommon = 1;
6219 /**
6220 * This is the common logic for both the Node.js and web browser
6221 * implementations of `debug()`.
6222 */
6223
6224 function setup(env) {
6225 createDebug.debug = createDebug;
6226 createDebug.default = createDebug;
6227 createDebug.coerce = coerce;
6228 createDebug.disable = disable;
6229 createDebug.enable = enable;
6230 createDebug.enabled = enabled;
6231 createDebug.humanize = requireMs();
6232 createDebug.destroy = destroy;
6233
6234 Object.keys(env).forEach(key => {
6235 createDebug[key] = env[key];
6236 });
6237
6238 /**
6239 * The currently active debug mode names, and names to skip.
6240 */
6241
6242 createDebug.names = [];
6243 createDebug.skips = [];
6244
6245 /**
6246 * Map of special "%n" handling functions, for the debug "format" argument.
6247 *
6248 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
6249 */
6250 createDebug.formatters = {};
6251
6252 /**
6253 * Selects a color for a debug namespace
6254 * @param {String} namespace The namespace string for the debug instance to be colored
6255 * @return {Number|String} An ANSI color code for the given namespace
6256 * @api private
6257 */
6258 function selectColor(namespace) {
6259 let hash = 0;
6260
6261 for (let i = 0; i < namespace.length; i++) {
6262 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
6263 hash |= 0; // Convert to 32bit integer
6264 }
6265
6266 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
6267 }
6268 createDebug.selectColor = selectColor;
6269
6270 /**
6271 * Create a debugger with the given `namespace`.
6272 *
6273 * @param {String} namespace
6274 * @return {Function}
6275 * @api public
6276 */
6277 function createDebug(namespace) {
6278 let prevTime;
6279 let enableOverride = null;
6280 let namespacesCache;
6281 let enabledCache;
6282
6283 function debug(...args) {
6284 // Disabled?
6285 if (!debug.enabled) {
6286 return;
6287 }
6288
6289 const self = debug;
6290
6291 // Set `diff` timestamp
6292 const curr = Number(new Date());
6293 const ms = curr - (prevTime || curr);
6294 self.diff = ms;
6295 self.prev = prevTime;
6296 self.curr = curr;
6297 prevTime = curr;
6298
6299 args[0] = createDebug.coerce(args[0]);
6300
6301 if (typeof args[0] !== 'string') {
6302 // Anything else let's inspect with %O
6303 args.unshift('%O');
6304 }
6305
6306 // Apply any `formatters` transformations
6307 let index = 0;
6308 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
6309 // If we encounter an escaped % then don't increase the array index
6310 if (match === '%%') {
6311 return '%';
6312 }
6313 index++;
6314 const formatter = createDebug.formatters[format];
6315 if (typeof formatter === 'function') {
6316 const val = args[index];
6317 match = formatter.call(self, val);
6318
6319 // Now we need to remove `args[index]` since it's inlined in the `format`
6320 args.splice(index, 1);
6321 index--;
6322 }
6323 return match;
6324 });
6325
6326 // Apply env-specific formatting (colors, etc.)
6327 createDebug.formatArgs.call(self, args);
6328
6329 const logFn = self.log || createDebug.log;
6330 logFn.apply(self, args);
6331 }
6332
6333 debug.namespace = namespace;
6334 debug.useColors = createDebug.useColors();
6335 debug.color = createDebug.selectColor(namespace);
6336 debug.extend = extend;
6337 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
6338
6339 Object.defineProperty(debug, 'enabled', {
6340 enumerable: true,
6341 configurable: false,
6342 get: () => {
6343 if (enableOverride !== null) {
6344 return enableOverride;
6345 }
6346 if (namespacesCache !== createDebug.namespaces) {
6347 namespacesCache = createDebug.namespaces;
6348 enabledCache = createDebug.enabled(namespace);
6349 }
6350
6351 return enabledCache;
6352 },
6353 set: v => {
6354 enableOverride = v;
6355 }
6356 });
6357
6358 // Env-specific initialization logic for debug instances
6359 if (typeof createDebug.init === 'function') {
6360 createDebug.init(debug);
6361 }
6362
6363 return debug;
6364 }
6365
6366 function extend(namespace, delimiter) {
6367 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
6368 newDebug.log = this.log;
6369 return newDebug;
6370 }
6371
6372 /**
6373 * Enables a debug mode by namespaces. This can include modes
6374 * separated by a colon and wildcards.
6375 *
6376 * @param {String} namespaces
6377 * @api public
6378 */
6379 function enable(namespaces) {
6380 createDebug.save(namespaces);
6381 createDebug.namespaces = namespaces;
6382
6383 createDebug.names = [];
6384 createDebug.skips = [];
6385
6386 let i;
6387 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
6388 const len = split.length;
6389
6390 for (i = 0; i < len; i++) {
6391 if (!split[i]) {
6392 // ignore empty strings
6393 continue;
6394 }
6395
6396 namespaces = split[i].replace(/\*/g, '.*?');
6397
6398 if (namespaces[0] === '-') {
6399 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
6400 } else {
6401 createDebug.names.push(new RegExp('^' + namespaces + '$'));
6402 }
6403 }
6404 }
6405
6406 /**
6407 * Disable debug output.
6408 *
6409 * @return {String} namespaces
6410 * @api public
6411 */
6412 function disable() {
6413 const namespaces = [
6414 ...createDebug.names.map(toNamespace),
6415 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
6416 ].join(',');
6417 createDebug.enable('');
6418 return namespaces;
6419 }
6420
6421 /**
6422 * Returns true if the given mode name is enabled, false otherwise.
6423 *
6424 * @param {String} name
6425 * @return {Boolean}
6426 * @api public
6427 */
6428 function enabled(name) {
6429 if (name[name.length - 1] === '*') {
6430 return true;
6431 }
6432
6433 let i;
6434 let len;
6435
6436 for (i = 0, len = createDebug.skips.length; i < len; i++) {
6437 if (createDebug.skips[i].test(name)) {
6438 return false;
6439 }
6440 }
6441
6442 for (i = 0, len = createDebug.names.length; i < len; i++) {
6443 if (createDebug.names[i].test(name)) {
6444 return true;
6445 }
6446 }
6447
6448 return false;
6449 }
6450
6451 /**
6452 * Convert regexp to namespace
6453 *
6454 * @param {RegExp} regxep
6455 * @return {String} namespace
6456 * @api private
6457 */
6458 function toNamespace(regexp) {
6459 return regexp.toString()
6460 .substring(2, regexp.toString().length - 2)
6461 .replace(/\.\*\?$/, '*');
6462 }
6463
6464 /**
6465 * Coerce `val`.
6466 *
6467 * @param {Mixed} val
6468 * @return {Mixed}
6469 * @api private
6470 */
6471 function coerce(val) {
6472 if (val instanceof Error) {
6473 return val.stack || val.message;
6474 }
6475 return val;
6476 }
6477
6478 /**
6479 * XXX DO NOT USE. This is a temporary stub function.
6480 * XXX It WILL be removed in the next major release.
6481 */
6482 function destroy() {
6483 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
6484 }
6485
6486 createDebug.enable(createDebug.load());
6487
6488 return createDebug;
6489 }
6490
6491 common = setup;
6492 return common;
6493}
6494
6495/* eslint-env browser */
6496
6497var hasRequiredBrowser$1;
6498
6499function requireBrowser$1 () {
6500 if (hasRequiredBrowser$1) return browser$1.exports;
6501 hasRequiredBrowser$1 = 1;
6502 (function (module, exports) {
6503 /**
6504 * This is the web browser implementation of `debug()`.
6505 */
6506
6507 exports.formatArgs = formatArgs;
6508 exports.save = save;
6509 exports.load = load;
6510 exports.useColors = useColors;
6511 exports.storage = localstorage();
6512 exports.destroy = (() => {
6513 let warned = false;
6514
6515 return () => {
6516 if (!warned) {
6517 warned = true;
6518 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
6519 }
6520 };
6521 })();
6522
6523 /**
6524 * Colors.
6525 */
6526
6527 exports.colors = [
6528 '#0000CC',
6529 '#0000FF',
6530 '#0033CC',
6531 '#0033FF',
6532 '#0066CC',
6533 '#0066FF',
6534 '#0099CC',
6535 '#0099FF',
6536 '#00CC00',
6537 '#00CC33',
6538 '#00CC66',
6539 '#00CC99',
6540 '#00CCCC',
6541 '#00CCFF',
6542 '#3300CC',
6543 '#3300FF',
6544 '#3333CC',
6545 '#3333FF',
6546 '#3366CC',
6547 '#3366FF',
6548 '#3399CC',
6549 '#3399FF',
6550 '#33CC00',
6551 '#33CC33',
6552 '#33CC66',
6553 '#33CC99',
6554 '#33CCCC',
6555 '#33CCFF',
6556 '#6600CC',
6557 '#6600FF',
6558 '#6633CC',
6559 '#6633FF',
6560 '#66CC00',
6561 '#66CC33',
6562 '#9900CC',
6563 '#9900FF',
6564 '#9933CC',
6565 '#9933FF',
6566 '#99CC00',
6567 '#99CC33',
6568 '#CC0000',
6569 '#CC0033',
6570 '#CC0066',
6571 '#CC0099',
6572 '#CC00CC',
6573 '#CC00FF',
6574 '#CC3300',
6575 '#CC3333',
6576 '#CC3366',
6577 '#CC3399',
6578 '#CC33CC',
6579 '#CC33FF',
6580 '#CC6600',
6581 '#CC6633',
6582 '#CC9900',
6583 '#CC9933',
6584 '#CCCC00',
6585 '#CCCC33',
6586 '#FF0000',
6587 '#FF0033',
6588 '#FF0066',
6589 '#FF0099',
6590 '#FF00CC',
6591 '#FF00FF',
6592 '#FF3300',
6593 '#FF3333',
6594 '#FF3366',
6595 '#FF3399',
6596 '#FF33CC',
6597 '#FF33FF',
6598 '#FF6600',
6599 '#FF6633',
6600 '#FF9900',
6601 '#FF9933',
6602 '#FFCC00',
6603 '#FFCC33'
6604 ];
6605
6606 /**
6607 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
6608 * and the Firebug extension (any Firefox version) are known
6609 * to support "%c" CSS customizations.
6610 *
6611 * TODO: add a `localStorage` variable to explicitly enable/disable colors
6612 */
6613
6614 // eslint-disable-next-line complexity
6615 function useColors() {
6616 // NB: In an Electron preload script, document will be defined but not fully
6617 // initialized. Since we know we're in Chrome, we'll just detect this case
6618 // explicitly
6619 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
6620 return true;
6621 }
6622
6623 // Internet Explorer and Edge do not support colors.
6624 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
6625 return false;
6626 }
6627
6628 // Is webkit? http://stackoverflow.com/a/16459606/376773
6629 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
6630 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
6631 // Is firebug? http://stackoverflow.com/a/398120/376773
6632 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
6633 // Is firefox >= v31?
6634 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
6635 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
6636 // Double check webkit in userAgent just in case we are in a worker
6637 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
6638 }
6639
6640 /**
6641 * Colorize log arguments if enabled.
6642 *
6643 * @api public
6644 */
6645
6646 function formatArgs(args) {
6647 args[0] = (this.useColors ? '%c' : '') +
6648 this.namespace +
6649 (this.useColors ? ' %c' : ' ') +
6650 args[0] +
6651 (this.useColors ? '%c ' : ' ') +
6652 '+' + module.exports.humanize(this.diff);
6653
6654 if (!this.useColors) {
6655 return;
6656 }
6657
6658 const c = 'color: ' + this.color;
6659 args.splice(1, 0, c, 'color: inherit');
6660
6661 // The final "%c" is somewhat tricky, because there could be other
6662 // arguments passed either before or after the %c, so we need to
6663 // figure out the correct index to insert the CSS into
6664 let index = 0;
6665 let lastC = 0;
6666 args[0].replace(/%[a-zA-Z%]/g, match => {
6667 if (match === '%%') {
6668 return;
6669 }
6670 index++;
6671 if (match === '%c') {
6672 // We only are interested in the *last* %c
6673 // (the user may have provided their own)
6674 lastC = index;
6675 }
6676 });
6677
6678 args.splice(lastC, 0, c);
6679 }
6680
6681 /**
6682 * Invokes `console.debug()` when available.
6683 * No-op when `console.debug` is not a "function".
6684 * If `console.debug` is not available, falls back
6685 * to `console.log`.
6686 *
6687 * @api public
6688 */
6689 exports.log = console.debug || console.log || (() => {});
6690
6691 /**
6692 * Save `namespaces`.
6693 *
6694 * @param {String} namespaces
6695 * @api private
6696 */
6697 function save(namespaces) {
6698 try {
6699 if (namespaces) {
6700 exports.storage.setItem('debug', namespaces);
6701 } else {
6702 exports.storage.removeItem('debug');
6703 }
6704 } catch (error) {
6705 // Swallow
6706 // XXX (@Qix-) should we be logging these?
6707 }
6708 }
6709
6710 /**
6711 * Load `namespaces`.
6712 *
6713 * @return {String} returns the previously persisted debug modes
6714 * @api private
6715 */
6716 function load() {
6717 let r;
6718 try {
6719 r = exports.storage.getItem('debug');
6720 } catch (error) {
6721 // Swallow
6722 // XXX (@Qix-) should we be logging these?
6723 }
6724
6725 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
6726 if (!r && typeof process !== 'undefined' && 'env' in process) {
6727 r = process.env.DEBUG;
6728 }
6729
6730 return r;
6731 }
6732
6733 /**
6734 * Localstorage attempts to return the localstorage.
6735 *
6736 * This is necessary because safari throws
6737 * when a user disables cookies/localstorage
6738 * and you attempt to access it.
6739 *
6740 * @return {LocalStorage}
6741 * @api private
6742 */
6743
6744 function localstorage() {
6745 try {
6746 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
6747 // The Browser also has localStorage in the global context.
6748 return localStorage;
6749 } catch (error) {
6750 // Swallow
6751 // XXX (@Qix-) should we be logging these?
6752 }
6753 }
6754
6755 module.exports = requireCommon()(exports);
6756
6757 const {formatters} = module.exports;
6758
6759 /**
6760 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
6761 */
6762
6763 formatters.j = function (v) {
6764 try {
6765 return JSON.stringify(v);
6766 } catch (error) {
6767 return '[UnexpectedJSONParseError]: ' + error.message;
6768 }
6769 };
6770} (browser$1, browser$1.exports));
6771 return browser$1.exports;
6772}
6773
6774var node = {exports: {}};
6775
6776/* eslint-env browser */
6777
6778var browser;
6779var hasRequiredBrowser;
6780
6781function requireBrowser () {
6782 if (hasRequiredBrowser) return browser;
6783 hasRequiredBrowser = 1;
6784
6785 function getChromeVersion() {
6786 const matches = /(Chrome|Chromium)\/(?<chromeVersion>\d+)\./.exec(navigator.userAgent);
6787
6788 if (!matches) {
6789 return;
6790 }
6791
6792 return Number.parseInt(matches.groups.chromeVersion, 10);
6793 }
6794
6795 const colorSupport = getChromeVersion() >= 69 ? {
6796 level: 1,
6797 hasBasic: true,
6798 has256: false,
6799 has16m: false
6800 } : false;
6801
6802 browser = {
6803 stdout: colorSupport,
6804 stderr: colorSupport
6805 };
6806 return browser;
6807}
6808
6809/**
6810 * Module dependencies.
6811 */
6812
6813var hasRequiredNode;
6814
6815function requireNode () {
6816 if (hasRequiredNode) return node.exports;
6817 hasRequiredNode = 1;
6818 (function (module, exports) {
6819 const tty = require$$0;
6820 const util = require$$1;
6821
6822 /**
6823 * This is the Node.js implementation of `debug()`.
6824 */
6825
6826 exports.init = init;
6827 exports.log = log;
6828 exports.formatArgs = formatArgs;
6829 exports.save = save;
6830 exports.load = load;
6831 exports.useColors = useColors;
6832 exports.destroy = util.deprecate(
6833 () => {},
6834 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
6835 );
6836
6837 /**
6838 * Colors.
6839 */
6840
6841 exports.colors = [6, 2, 3, 4, 5, 1];
6842
6843 try {
6844 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
6845 // eslint-disable-next-line import/no-extraneous-dependencies
6846 const supportsColor = requireBrowser();
6847
6848 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
6849 exports.colors = [
6850 20,
6851 21,
6852 26,
6853 27,
6854 32,
6855 33,
6856 38,
6857 39,
6858 40,
6859 41,
6860 42,
6861 43,
6862 44,
6863 45,
6864 56,
6865 57,
6866 62,
6867 63,
6868 68,
6869 69,
6870 74,
6871 75,
6872 76,
6873 77,
6874 78,
6875 79,
6876 80,
6877 81,
6878 92,
6879 93,
6880 98,
6881 99,
6882 112,
6883 113,
6884 128,
6885 129,
6886 134,
6887 135,
6888 148,
6889 149,
6890 160,
6891 161,
6892 162,
6893 163,
6894 164,
6895 165,
6896 166,
6897 167,
6898 168,
6899 169,
6900 170,
6901 171,
6902 172,
6903 173,
6904 178,
6905 179,
6906 184,
6907 185,
6908 196,
6909 197,
6910 198,
6911 199,
6912 200,
6913 201,
6914 202,
6915 203,
6916 204,
6917 205,
6918 206,
6919 207,
6920 208,
6921 209,
6922 214,
6923 215,
6924 220,
6925 221
6926 ];
6927 }
6928 } catch (error) {
6929 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
6930 }
6931
6932 /**
6933 * Build up the default `inspectOpts` object from the environment variables.
6934 *
6935 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
6936 */
6937
6938 exports.inspectOpts = Object.keys(process.env).filter(key => {
6939 return /^debug_/i.test(key);
6940 }).reduce((obj, key) => {
6941 // Camel-case
6942 const prop = key
6943 .substring(6)
6944 .toLowerCase()
6945 .replace(/_([a-z])/g, (_, k) => {
6946 return k.toUpperCase();
6947 });
6948
6949 // Coerce string value into JS value
6950 let val = process.env[key];
6951 if (/^(yes|on|true|enabled)$/i.test(val)) {
6952 val = true;
6953 } else if (/^(no|off|false|disabled)$/i.test(val)) {
6954 val = false;
6955 } else if (val === 'null') {
6956 val = null;
6957 } else {
6958 val = Number(val);
6959 }
6960
6961 obj[prop] = val;
6962 return obj;
6963 }, {});
6964
6965 /**
6966 * Is stdout a TTY? Colored output is enabled when `true`.
6967 */
6968
6969 function useColors() {
6970 return 'colors' in exports.inspectOpts ?
6971 Boolean(exports.inspectOpts.colors) :
6972 tty.isatty(process.stderr.fd);
6973 }
6974
6975 /**
6976 * Adds ANSI color escape codes if enabled.
6977 *
6978 * @api public
6979 */
6980
6981 function formatArgs(args) {
6982 const {namespace: name, useColors} = this;
6983
6984 if (useColors) {
6985 const c = this.color;
6986 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
6987 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
6988
6989 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
6990 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
6991 } else {
6992 args[0] = getDate() + name + ' ' + args[0];
6993 }
6994 }
6995
6996 function getDate() {
6997 if (exports.inspectOpts.hideDate) {
6998 return '';
6999 }
7000 return new Date().toISOString() + ' ';
7001 }
7002
7003 /**
7004 * Invokes `util.format()` with the specified arguments and writes to stderr.
7005 */
7006
7007 function log(...args) {
7008 return process.stderr.write(util.format(...args) + '\n');
7009 }
7010
7011 /**
7012 * Save `namespaces`.
7013 *
7014 * @param {String} namespaces
7015 * @api private
7016 */
7017 function save(namespaces) {
7018 if (namespaces) {
7019 process.env.DEBUG = namespaces;
7020 } else {
7021 // If you set a process.env field to null or undefined, it gets cast to the
7022 // string 'null' or 'undefined'. Just delete instead.
7023 delete process.env.DEBUG;
7024 }
7025 }
7026
7027 /**
7028 * Load `namespaces`.
7029 *
7030 * @return {String} returns the previously persisted debug modes
7031 * @api private
7032 */
7033
7034 function load() {
7035 return process.env.DEBUG;
7036 }
7037
7038 /**
7039 * Init logic for `debug` instances.
7040 *
7041 * Create a new `inspectOpts` object in case `useColors` is set
7042 * differently for a particular `debug` instance.
7043 */
7044
7045 function init(debug) {
7046 debug.inspectOpts = {};
7047
7048 const keys = Object.keys(exports.inspectOpts);
7049 for (let i = 0; i < keys.length; i++) {
7050 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
7051 }
7052 }
7053
7054 module.exports = requireCommon()(exports);
7055
7056 const {formatters} = module.exports;
7057
7058 /**
7059 * Map %o to `util.inspect()`, all on a single line.
7060 */
7061
7062 formatters.o = function (v) {
7063 this.inspectOpts.colors = this.useColors;
7064 return util.inspect(v, this.inspectOpts)
7065 .split('\n')
7066 .map(str => str.trim())
7067 .join(' ');
7068 };
7069
7070 /**
7071 * Map %O to `util.inspect()`, allowing multiple lines if needed.
7072 */
7073
7074 formatters.O = function (v) {
7075 this.inspectOpts.colors = this.useColors;
7076 return util.inspect(v, this.inspectOpts);
7077 };
7078} (node, node.exports));
7079 return node.exports;
7080}
7081
7082/**
7083 * Detect Electron renderer / nwjs process, which is node, but we should
7084 * treat as a browser.
7085 */
7086
7087(function (module) {
7088 if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
7089 module.exports = requireBrowser$1();
7090 } else {
7091 module.exports = requireNode();
7092 }
7093} (src));
7094
7095var createDebug = /*@__PURE__*/getDefaultExportFromCjs(src.exports);
7096
7097const isWindows = process.platform === "win32";
7098function slash(str) {
7099 return str.replace(/\\/g, "/");
7100}
7101const VALID_ID_PREFIX = "/@id/";
7102function normalizeRequestId(id, base) {
7103 if (base && id.startsWith(base))
7104 id = `/${id.slice(base.length)}`;
7105 return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
7106}
7107const queryRE = /\?.*$/s;
7108const hashRE = /#.*$/s;
7109const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, "");
7110const internalRequests = [
7111 "@vite/client",
7112 "@vite/env"
7113];
7114const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`);
7115const isInternalRequest = (id) => {
7116 return internalRequestRegexp.test(id);
7117};
7118function normalizeModuleId(id) {
7119 return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").replace(/^node:/, "").replace(/^\/+/, "/");
7120}
7121function isPrimitive(v) {
7122 return v !== Object(v);
7123}
7124function toFilePath(id, root) {
7125 let { absolute, exists } = (() => {
7126 if (id.startsWith("/@fs/"))
7127 return { absolute: id.slice(4), exists: true };
7128 if (!id.startsWith(root) && id.startsWith("/")) {
7129 const resolved = resolve(root, id.slice(1));
7130 if (existsSync(cleanUrl(resolved)))
7131 return { absolute: resolved, exists: true };
7132 } else if (id.startsWith(root) && existsSync(cleanUrl(id))) {
7133 return { absolute: id, exists: true };
7134 }
7135 return { absolute: id, exists: false };
7136 })();
7137 if (absolute.startsWith("//"))
7138 absolute = absolute.slice(1);
7139 return {
7140 path: isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute,
7141 exists
7142 };
7143}
7144
7145const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
7146const intToChar = new Uint8Array(64); // 64 possible chars.
7147const charToInt = new Uint8Array(128); // z is 122 in ASCII
7148for (let i = 0; i < chars.length; i++) {
7149 const c = chars.charCodeAt(i);
7150 intToChar[i] = c;
7151 charToInt[c] = i;
7152}
7153
7154// Matches the scheme of a URL, eg "http://"
7155var UrlType;
7156(function (UrlType) {
7157 UrlType[UrlType["Empty"] = 1] = "Empty";
7158 UrlType[UrlType["Hash"] = 2] = "Hash";
7159 UrlType[UrlType["Query"] = 3] = "Query";
7160 UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
7161 UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
7162 UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
7163 UrlType[UrlType["Absolute"] = 7] = "Absolute";
7164})(UrlType || (UrlType = {}));
7165
7166let fileContentsCache = {};
7167const reSourceMap = /^data:application\/json[^,]+base64,/;
7168let retrieveFileHandlers = [];
7169let retrieveMapHandlers = [];
7170function handlerExec(list) {
7171 return function(arg) {
7172 for (let i = 0; i < list.length; i++) {
7173 const ret = list[i](arg);
7174 if (ret)
7175 return ret;
7176 }
7177 return null;
7178 };
7179}
7180let retrieveFile = handlerExec(retrieveFileHandlers);
7181retrieveFileHandlers.push((path2) => {
7182 path2 = path2.trim();
7183 if (path2.startsWith("file:")) {
7184 path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
7185 return drive ? "" : "/";
7186 });
7187 }
7188 if (path2 in fileContentsCache)
7189 return fileContentsCache[path2];
7190 let contents = "";
7191 try {
7192 if (fs.existsSync(path2))
7193 contents = fs.readFileSync(path2, "utf8");
7194 } catch (er) {
7195 }
7196 return fileContentsCache[path2] = contents;
7197});
7198function supportRelativeURL(file, url) {
7199 if (!file)
7200 return url;
7201 const dir = path.dirname(file);
7202 const match = /^\w+:\/\/[^\/]*/.exec(dir);
7203 let protocol = match ? match[0] : "";
7204 const startPath = dir.slice(protocol.length);
7205 if (protocol && /^\/\w\:/.test(startPath)) {
7206 protocol += "/";
7207 return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
7208 }
7209 return protocol + path.resolve(dir.slice(protocol.length), url);
7210}
7211function retrieveSourceMapURL(source) {
7212 const fileData = retrieveFile(source);
7213 if (!fileData)
7214 return null;
7215 const re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
7216 let lastMatch, match;
7217 while (match = re.exec(fileData))
7218 lastMatch = match;
7219 if (!lastMatch)
7220 return null;
7221 return lastMatch[1];
7222}
7223retrieveMapHandlers.push((source) => {
7224 let sourceMappingURL = retrieveSourceMapURL(source);
7225 if (!sourceMappingURL)
7226 return null;
7227 let sourceMapData;
7228 if (reSourceMap.test(sourceMappingURL)) {
7229 const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
7230 sourceMapData = Buffer.from(rawData, "base64").toString();
7231 sourceMappingURL = source;
7232 } else {
7233 sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
7234 sourceMapData = retrieveFile(sourceMappingURL);
7235 }
7236 if (!sourceMapData)
7237 return null;
7238 return {
7239 url: sourceMappingURL,
7240 map: sourceMapData
7241 };
7242});
7243retrieveFileHandlers.slice(0);
7244retrieveMapHandlers.slice(0);
7245
7246let SOURCEMAPPING_URL = "sourceMa";
7247SOURCEMAPPING_URL += "ppingURL";
7248const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
7249const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
7250function extractSourceMap(code) {
7251 var _a;
7252 const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
7253 if (mapString)
7254 return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
7255 return null;
7256}
7257
7258const { setTimeout, clearTimeout } = globalThis;
7259const debugExecute = createDebug("vite-node:client:execute");
7260const debugNative = createDebug("vite-node:client:native");
7261const clientStub = {
7262 injectQuery: (id) => id,
7263 createHotContext() {
7264 return {
7265 accept: () => {
7266 },
7267 prune: () => {
7268 },
7269 dispose: () => {
7270 },
7271 decline: () => {
7272 },
7273 invalidate: () => {
7274 },
7275 on: () => {
7276 }
7277 };
7278 },
7279 updateStyle(id, css) {
7280 if (typeof document === "undefined")
7281 return;
7282 const element = document.getElementById(id);
7283 if (element)
7284 element.remove();
7285 const head = document.querySelector("head");
7286 const style = document.createElement("style");
7287 style.setAttribute("type", "text/css");
7288 style.id = id;
7289 style.innerHTML = css;
7290 head == null ? void 0 : head.appendChild(style);
7291 }
7292};
7293const DEFAULT_REQUEST_STUBS = {
7294 "/@vite/client": clientStub,
7295 "@vite/client": clientStub
7296};
7297class ModuleCacheMap extends Map {
7298 normalizePath(fsPath) {
7299 return normalizeModuleId(fsPath);
7300 }
7301 update(fsPath, mod) {
7302 fsPath = this.normalizePath(fsPath);
7303 if (!super.has(fsPath))
7304 super.set(fsPath, mod);
7305 else
7306 Object.assign(super.get(fsPath), mod);
7307 return this;
7308 }
7309 setByModuleId(modulePath, mod) {
7310 return super.set(modulePath, mod);
7311 }
7312 set(fsPath, mod) {
7313 return this.setByModuleId(this.normalizePath(fsPath), mod);
7314 }
7315 getByModuleId(modulePath) {
7316 if (!super.has(modulePath))
7317 super.set(modulePath, {});
7318 return super.get(modulePath);
7319 }
7320 get(fsPath) {
7321 return this.getByModuleId(this.normalizePath(fsPath));
7322 }
7323 deleteByModuleId(modulePath) {
7324 return super.delete(modulePath);
7325 }
7326 delete(fsPath) {
7327 return this.deleteByModuleId(this.normalizePath(fsPath));
7328 }
7329 invalidateModule(mod) {
7330 delete mod.evaluated;
7331 delete mod.resolving;
7332 delete mod.promise;
7333 delete mod.exports;
7334 return true;
7335 }
7336 invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
7337 for (const _id of ids) {
7338 const id = this.normalizePath(_id);
7339 if (invalidated.has(id))
7340 continue;
7341 invalidated.add(id);
7342 const mod = super.get(id);
7343 if (mod == null ? void 0 : mod.importers)
7344 this.invalidateDepTree(mod.importers, invalidated);
7345 super.delete(id);
7346 }
7347 return invalidated;
7348 }
7349 invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
7350 for (const _id of ids) {
7351 const id = this.normalizePath(_id);
7352 if (invalidated.has(id))
7353 continue;
7354 invalidated.add(id);
7355 const subIds = Array.from(super.entries()).filter(([, mod]) => {
7356 var _a;
7357 return (_a = mod.importers) == null ? void 0 : _a.has(id);
7358 }).map(([key]) => key);
7359 subIds.length && this.invalidateSubDepTree(subIds, invalidated);
7360 super.delete(id);
7361 }
7362 return invalidated;
7363 }
7364 getSourceMap(id) {
7365 const cache = this.get(id);
7366 if (cache.map)
7367 return cache.map;
7368 const map = cache.code && extractSourceMap(cache.code);
7369 if (map) {
7370 cache.map = map;
7371 return map;
7372 }
7373 return null;
7374 }
7375}
7376class ViteNodeRunner {
7377 constructor(options) {
7378 this.options = options;
7379 this.root = options.root ?? process.cwd();
7380 this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
7381 this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
7382 }
7383 async executeFile(file) {
7384 const url = `/@fs/${slash(resolve(file))}`;
7385 return await this.cachedRequest(url, url, []);
7386 }
7387 async executeId(rawId) {
7388 const [id, url] = await this.resolveUrl(rawId);
7389 return await this.cachedRequest(id, url, []);
7390 }
7391 async cachedRequest(id, fsPath, callstack) {
7392 const importee = callstack[callstack.length - 1];
7393 const mod = this.moduleCache.get(fsPath);
7394 if (!mod.importers)
7395 mod.importers = /* @__PURE__ */ new Set();
7396 if (importee)
7397 mod.importers.add(importee);
7398 if (callstack.includes(fsPath) && mod.exports)
7399 return mod.exports;
7400 if (mod.promise)
7401 return mod.promise;
7402 const promise = this.directRequest(id, fsPath, callstack);
7403 Object.assign(mod, { promise, evaluated: false });
7404 try {
7405 return await promise;
7406 } finally {
7407 mod.evaluated = true;
7408 }
7409 }
7410 shouldResolveId(id, _importee) {
7411 return !isInternalRequest(id) && !isNodeBuiltin(id);
7412 }
7413 async _resolveUrl(id, importer) {
7414 if (importer && id.startsWith(VALID_ID_PREFIX))
7415 importer = void 0;
7416 id = normalizeRequestId(id, this.options.base);
7417 if (!this.shouldResolveId(id))
7418 return [id, id];
7419 const { path, exists } = toFilePath(id, this.root);
7420 if (!this.options.resolveId || exists)
7421 return [id, path];
7422 const resolved = await this.options.resolveId(id, importer);
7423 const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : id;
7424 const fsPath = resolved ? resolvedId : path;
7425 return [resolvedId, fsPath];
7426 }
7427 async resolveUrl(id, importee) {
7428 const resolveKey = `resolve:${id}`;
7429 this.moduleCache.setByModuleId(resolveKey, { resolving: true });
7430 try {
7431 return await this._resolveUrl(id, importee);
7432 } finally {
7433 this.moduleCache.deleteByModuleId(resolveKey);
7434 }
7435 }
7436 async dependencyRequest(id, fsPath, callstack) {
7437 var _a;
7438 const getStack = () => {
7439 return `stack:
7440${[...callstack, fsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
7441 };
7442 let debugTimer;
7443 if (this.debug)
7444 debugTimer = setTimeout(() => console.warn(() => `module ${fsPath} takes over 2s to load.
7445${getStack()}`), 2e3);
7446 try {
7447 if (callstack.includes(fsPath)) {
7448 const depExports = (_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports;
7449 if (depExports)
7450 return depExports;
7451 throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
7452 }
7453 return await this.cachedRequest(id, fsPath, callstack);
7454 } finally {
7455 if (debugTimer)
7456 clearTimeout(debugTimer);
7457 }
7458 }
7459 async directRequest(id, fsPath, _callstack) {
7460 const moduleId = normalizeModuleId(fsPath);
7461 const callstack = [..._callstack, moduleId];
7462 const mod = this.moduleCache.getByModuleId(moduleId);
7463 const request = async (dep) => {
7464 const [id2, depFsPath] = await this.resolveUrl(dep, fsPath);
7465 return this.dependencyRequest(id2, depFsPath, callstack);
7466 };
7467 const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
7468 if (id in requestStubs)
7469 return requestStubs[id];
7470 let { code: transformed, externalize } = await this.options.fetchModule(id);
7471 if (externalize) {
7472 debugNative(externalize);
7473 const exports2 = await this.interopedImport(externalize);
7474 mod.exports = exports2;
7475 return exports2;
7476 }
7477 if (transformed == null)
7478 throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
7479 const modulePath = cleanUrl(moduleId);
7480 const href = pathToFileURL(modulePath).href;
7481 const meta = { url: href };
7482 const exports = /* @__PURE__ */ Object.create(null);
7483 Object.defineProperty(exports, Symbol.toStringTag, {
7484 value: "Module",
7485 enumerable: false,
7486 configurable: false
7487 });
7488 const cjsExports = new Proxy(exports, {
7489 get: (target, p, receiver) => {
7490 if (Reflect.has(target, p))
7491 return Reflect.get(target, p, receiver);
7492 return Reflect.get(Object.prototype, p, receiver);
7493 },
7494 getPrototypeOf: () => Object.prototype,
7495 set: (_, p, value) => {
7496 if (p === "default" && this.shouldInterop(modulePath, { default: value })) {
7497 exportAll(cjsExports, value);
7498 exports.default = value;
7499 return true;
7500 }
7501 if (!Reflect.has(exports, "default"))
7502 exports.default = {};
7503 if (isPrimitive(exports.default)) {
7504 defineExport(exports, p, () => void 0);
7505 return true;
7506 }
7507 exports.default[p] = value;
7508 if (p !== "default")
7509 defineExport(exports, p, () => value);
7510 return true;
7511 }
7512 });
7513 Object.assign(mod, { code: transformed, exports });
7514 const __filename = fileURLToPath(href);
7515 const moduleProxy = {
7516 set exports(value) {
7517 exportAll(cjsExports, value);
7518 exports.default = value;
7519 },
7520 get exports() {
7521 return cjsExports;
7522 }
7523 };
7524 let hotContext;
7525 if (this.options.createHotContext) {
7526 Object.defineProperty(meta, "hot", {
7527 enumerable: true,
7528 get: () => {
7529 var _a, _b;
7530 hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
7531 return hotContext;
7532 },
7533 set: (value) => {
7534 hotContext = value;
7535 }
7536 });
7537 }
7538 const context = this.prepareContext({
7539 __vite_ssr_import__: request,
7540 __vite_ssr_dynamic_import__: request,
7541 __vite_ssr_exports__: exports,
7542 __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
7543 __vite_ssr_import_meta__: meta,
7544 require: createRequire(href),
7545 exports: cjsExports,
7546 module: moduleProxy,
7547 __filename,
7548 __dirname: dirname(__filename)
7549 });
7550 debugExecute(__filename);
7551 if (transformed[0] === "#")
7552 transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
7553 const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
7554 const code = `${codeDefinition}${transformed}
7555}}`;
7556 const fn = vm.runInThisContext(code, {
7557 filename: __filename,
7558 lineOffset: 0,
7559 columnOffset: -codeDefinition.length
7560 });
7561 await fn(...Object.values(context));
7562 return exports;
7563 }
7564 prepareContext(context) {
7565 return context;
7566 }
7567 shouldInterop(path, mod) {
7568 if (this.options.interopDefault === false)
7569 return false;
7570 return !path.endsWith(".mjs") && "default" in mod;
7571 }
7572 async interopedImport(path) {
7573 const importedModule = await import(path);
7574 if (!this.shouldInterop(path, importedModule))
7575 return importedModule;
7576 const { mod, defaultExport } = interopModule(importedModule);
7577 return new Proxy(mod, {
7578 get(mod2, prop) {
7579 if (prop === "default")
7580 return defaultExport;
7581 return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
7582 },
7583 has(mod2, prop) {
7584 if (prop === "default")
7585 return defaultExport !== void 0;
7586 return prop in mod2 || defaultExport && prop in defaultExport;
7587 },
7588 getOwnPropertyDescriptor(mod2, prop) {
7589 const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop);
7590 if (descriptor)
7591 return descriptor;
7592 if (prop === "default" && defaultExport !== void 0) {
7593 return {
7594 value: defaultExport,
7595 enumerable: true,
7596 configurable: true
7597 };
7598 }
7599 }
7600 });
7601 }
7602}
7603function interopModule(mod) {
7604 if (isPrimitive(mod)) {
7605 return {
7606 mod: { default: mod },
7607 defaultExport: mod
7608 };
7609 }
7610 let defaultExport = "default" in mod ? mod.default : mod;
7611 if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
7612 mod = defaultExport;
7613 if ("default" in defaultExport)
7614 defaultExport = defaultExport.default;
7615 }
7616 return { mod, defaultExport };
7617}
7618function defineExport(exports, key, value) {
7619 Object.defineProperty(exports, key, {
7620 enumerable: true,
7621 configurable: true,
7622 get: value
7623 });
7624}
7625function exportAll(exports, sourceModule) {
7626 if (exports === sourceModule)
7627 return;
7628 if (isPrimitive(sourceModule) || Array.isArray(sourceModule))
7629 return;
7630 for (const key in sourceModule) {
7631 if (key !== "default") {
7632 try {
7633 defineExport(exports, key, () => sourceModule[key]);
7634 } catch (_err) {
7635 }
7636 }
7637 }
7638}
7639
7640export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };